context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region File Description //----------------------------------------------------------------------------- // AudioManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using System.Collections.Generic; #endregion namespace RolePlaying { /// <summary> /// Component that manages audio playback for all cues. /// </summary> /// <remarks> /// Similar to a class found in the Net Rumble starter kit on the /// XNA Creators Club Online website (http://creators.xna.com). /// </remarks> public class AudioManager : GameComponent { #region Singleton /// <summary> /// The singleton for this type. /// </summary> private static AudioManager audioManager = null; public static AudioManager Instance { get { return audioManager; } } #endregion #region Audio Data Dictionary<string, SoundEffectInstance> soundBank; string[,] soundNames; #endregion #region Initialization Methods /// <summary> /// Constructs the manager for audio playback of all cues. /// </summary> /// <param name="game">The game that this component will be attached to.</param> /// <param name="settingsFile">The filename of the XACT settings file.</param> /// <param name="waveBankFile">The filename of the XACT wavebank file.</param> /// <param name="soundBankFile">The filename of the XACT soundbank file.</param> private AudioManager(Game game) : base(game) { } public static void Initialize(Game game) { audioManager = new AudioManager(game); game.Components.Add(audioManager); LoadSounds(); } #endregion #region Loading Methodes /// <summary> /// Loads a sounds and organizes them for future usage. /// </summary> public static void LoadSounds() { audioManager.soundNames = new string[,] { {"BattleTheme","BattleTheme"}, {"Continue","Continue"}, {"Death","Death"}, {"DungeonTheme","DungeonTheme"}, {"FireballCreate","FireballCreate"}, {"FireballHit","FireballHit"}, {"FireballTravel","FireballTravel"}, {"ForestTheme","ForestTheme"}, {"HealCreate","HealCreate"}, {"HealImpact","HealImpact"}, {"HealPotion","HealPotion"}, {"LevelUp","LevelUp"}, {"LoseTheme","LoseTheme"}, {"MainTheme","MainTheme"}, {"MenuMove","MenuMove"}, {"Money","Money"}, {"QuestComplete","QuestComplete"}, {"SpellBlock","SpellBlock"}, {"SpellCreate","SpellCreate"}, {"StaffBlock","StaffBlock"}, {"StaffHit","StaffHit"}, {"StaffSwing","StaffSwing"}, {"SwordBlock","SwordBlock"}, {"SwordHit","SwordHit"}, {"SwordSwing","SwordSwing"}, {"VillageTheme","VillageTheme"}, {"WinTheme","WinTheme"} }; audioManager.soundBank = new Dictionary<string, SoundEffectInstance>(); } #endregion #region Sounds Methods /// <summary> /// Retrieve a cue by name. /// </summary> /// <param name="cueName">The name of the cue requested.</param> /// <returns>The cue corresponding to the name provided.</returns> public static SoundEffectInstance GetCue(string assetName) { return LoadAsset<SoundEffect>(assetName).CreateInstance(); } /// <summary> /// Plays a cue by name. /// </summary> /// <param name="assetName">The name of the cue to play.</param> public static void PlayCue(string assetName) { LoadAsset<SoundEffect>(assetName).Play(); } #endregion #region Music /// <summary> /// The cue for the music currently playing, if any. /// </summary> private SoundEffectInstance musicSound; /// <summary> /// Stack of music cue names, for layered music playback. /// </summary> private Stack<string> musicSoundNameStack = new Stack<string>(); /// <summary> /// Plays the desired music, clearing the stack of music cues. /// </summary> /// <param name="assetName">The name of the music cue to play.</param> public static void PlayMusic(string assetName,bool isLooped) { // Stop the old music sound if (audioManager.musicSound != null && !audioManager.musicSound.IsDisposed) { audioManager.musicSound.Stop(true); UnoadAsset(audioManager.musicSound); } audioManager.musicSound = LoadAsset<SoundEffect>(assetName).CreateInstance(); audioManager.musicSound.IsLooped = isLooped; audioManager.musicSound.Play(); audioManager.musicSoundNameStack.Push(assetName); } /// <summary> /// Plays the music for this game, adding it to the music stack. /// </summary> /// <param name="cueName">The name of the music cue to play.</param> public static void PushMusic(string cueName,bool isLooped) { // start the new music cue if ((audioManager != null) && (audioManager.soundBank != null)) { audioManager.musicSoundNameStack.Push(cueName); if (audioManager.musicSound != null ) { audioManager.musicSound.Stop(); UnoadAsset(audioManager.musicSound); audioManager.musicSound = null; } audioManager.musicSound = GetCue(cueName); if (audioManager.musicSound != null ) { audioManager.musicSound.IsLooped = isLooped; audioManager.musicSound.Play(); } } } /// <summary> /// Stops the current music and plays the previous music on the stack. /// </summary> public static void PopMusic() { // start the new music cue if ((audioManager != null) && (audioManager.soundBank != null)) { string cueName = null; if (audioManager.musicSoundNameStack.Count > 0) { audioManager.musicSoundNameStack.Pop(); if (audioManager.musicSoundNameStack.Count > 0) { cueName = audioManager.musicSoundNameStack.Peek(); } } if (audioManager.musicSound != null) { audioManager.musicSound.Stop(); UnoadAsset(audioManager.musicSound); audioManager.musicSound = null; } if (!String.IsNullOrEmpty(cueName)) { audioManager.musicSound = GetCue(cueName); if (audioManager.musicSound != null) { if (!audioManager.musicSound.IsDisposed) { audioManager.musicSound.Play(); } } } } } /// <summary> /// Stop music playback, clearing the cue. /// </summary> public static void StopMusic() { foreach (var sound in audioManager.soundBank.Values) { if (sound.State != SoundState.Stopped) { sound.Stop(); UnoadAsset(sound); } } } private static T LoadAsset<T>(string assetName) where T : class { T sound = audioManager.Game.Content.Load<T>( "Audio/Waves/" + assetName); return sound; } private static void UnoadAsset(IDisposable asset) { asset.Dispose(); } #endregion #region Instance Disposal Methods /// <summary> /// Clean up the component when it is disposing. /// </summary> protected override void Dispose(bool disposing) { try { if (disposing) { foreach (var item in soundBank) { item.Value.Dispose(); } soundBank.Clear(); soundBank = null; } } finally { base.Dispose(disposing); } } #endregion } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.Internal.PropertyEditing.Model { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics; using System.Activities.Presentation.PropertyEditing; using System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Framework.Data; using System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Framework.PropertyInspector; using System.Activities.Presentation; // <summary> // Cider's concrete implementation of CategoryEntry (CategoryBase comes from Sparkle // and it has a few extra goodies that we want to reuse). This class implements // INotifyCollectionChanged. We need to push this implementation to the base class // in v2. // </summary> internal class ModelCategoryEntry : CategoryBase, INotifyCollectionChanged { private ObservableCollectionWorkaround<PropertyEntry> _basicProperties; private ObservableCollectionWorkaround<PropertyEntry> _advancedProperties; // <summary> // Basic ctor // </summary> // <param name="categoryName">Localized name for this category</param> public ModelCategoryEntry(string categoryName) : base(categoryName) { _basicProperties = new ObservableCollectionWorkaround<PropertyEntry>(); _advancedProperties = new ObservableCollectionWorkaround<PropertyEntry>(); } public event NotifyCollectionChangedEventHandler CollectionChanged; // <summary> // Gets the advanced properties contained in this category // </summary> public override ObservableCollection<PropertyEntry> AdvancedProperties { get { return _advancedProperties; } } // <summary> // Gets the basic properties contained in this category // </summary> public override ObservableCollection<PropertyEntry> BasicProperties { get { return _basicProperties; } } // <summary> // Gets a flag indicating whether this category contains any properties // </summary> internal bool IsEmpty { get { return _advancedProperties.Count + _basicProperties.Count == 0; } } // <summary> // Returns either the basic or the advanced bucket based on the IsAdvanced flag // set in the PropertyEntry itself // </summary> // <param name="property">Property to examine</param> // <returns>The corresponding basic or advanced bucket</returns> internal ObservableCollectionWorkaround<PropertyEntry> GetBucket(PropertyEntry property) { if (property == null) { throw FxTrace.Exception.ArgumentNull("property"); } return property.IsAdvanced ? _advancedProperties : _basicProperties; } // <summary> // Adds the given property to the specified property bucket (use // ModelCategoryEntry.BasicProperties, ModelCategoryEntry.AdvancedProperties, or // ModelCategoryEntry.GetBucket()) sorted using the specified comparer. // </summary> // <param name="property">Property to add</param> // <param name="bucket">Property bucket to populate</param> // <param name="comparer">Sort algorithm to use</param> // <param name="fireCollectionChangedEvent">If set to true, NotifyCollectionChanged event is fired</param> internal void Add( PropertyEntry property, ObservableCollection<PropertyEntry> bucket, IComparer<PropertyEntry> comparer) { Add(property, bucket, comparer, true); } // // Adds the given property to the specified property bucket (use // ModelCategoryEntry.BasicProperties, ModelCategoryEntry.AdvancedProperties, or // ModelCategoryEntry.GetBucket()) sorted using the specified comparer. // private void Add( PropertyEntry property, ObservableCollection<PropertyEntry> bucket, IComparer<PropertyEntry> comparer, bool fireCollectionChangedEvent) { if (property == null) { throw FxTrace.Exception.ArgumentNull("property"); } if (bucket == null) { throw FxTrace.Exception.ArgumentNull("bucket"); } if (comparer == null) { throw FxTrace.Exception.ArgumentNull("comparer"); } ObservableCollectionWorkaround<PropertyEntry> castBucket = bucket as ObservableCollectionWorkaround<PropertyEntry>; int insertionIndex = 0; if (castBucket == null) { Debug.Fail("Invalid property bucket. The property sort order will be broken."); } else { insertionIndex = castBucket.BinarySearch(property, comparer); if (insertionIndex < 0) { insertionIndex = ~insertionIndex; } } bucket.Insert(insertionIndex, property); if (fireCollectionChangedEvent) { FirePropertiesChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, property)); } } // <summary> // Removes and re-adds the specified property from this category, if it existed // there to begin with. Noop otherwise. // // Use this method to refresh the cate----zation of a property if it suddenly // becomes Advanced if it was Basic before, or if its IsBrowsable status changes. // </summary> // <param name="property">Property to refresh</param> // <param name="bucket">Property bucket to repopulate</param> // <param name="sortComparer">Comparer to use to reinsert the given property in its new place</param> internal void Refresh(ModelPropertyEntry property, ObservableCollection<PropertyEntry> bucket, IComparer<PropertyEntry> sortComparer) { if (property == null) { throw FxTrace.Exception.ArgumentNull("property"); } if (bucket != _basicProperties && bucket != _advancedProperties) { Debug.Fail("Invalid bucket specified. Property was not refreshed."); return; } // Let's see if we know about this property ObservableCollectionWorkaround<PropertyEntry> collection; collection = _advancedProperties; int index = collection.BinarySearch(property, null); if (index < 0) { collection = _basicProperties; index = collection.BinarySearch(property, null); } // If not, noop if (index < 0) { return; } // We know about this property, so refresh it. It may have changed // somehow (eg. switched from basic to advanced, become hidden, etc.) // so make sure it's thrown into the right bucket. collection.RemoveAt(index); Add(property, bucket, sortComparer, false); } // <summary> // This is a work-around fix because Blend's CategoryBase does not handle null filters (valid value) // correctly. We need to ask Blend to eventually fix this issue. // </summary> // <param name="filter">Filter to apply, can be null</param> public override void ApplyFilter(PropertyFilter filter) { if (filter == null) { this.MatchesFilter = true; this.BasicPropertyMatchesFilter = true; this.AdvancedPropertyMatchesFilter = true; foreach (PropertyEntry property in this.BasicProperties) { property.ApplyFilter(filter); } foreach (PropertyEntry property in this.AdvancedProperties) { property.ApplyFilter(filter); } } else { base.ApplyFilter(filter); } } // Another Blend work-around - we expose all properties through the OM, not just the // Browsable ones. However, as a result, we need to cull the non-browsable ones from // consideration. Otherwise, empty categories may appear. protected override bool DoesPropertyMatchFilter(PropertyFilter filter, PropertyEntry property) { property.ApplyFilter(filter); bool isBrowsable = true; ModelPropertyEntry modelPropertyEntry = property as ModelPropertyEntry; if (modelPropertyEntry != null) { //display given property if it is browsable or isBrowsable = modelPropertyEntry.IsBrowsable || // it may not be browsable, but if there is a category editor associated - display it anyway (this.CategoryEditors != null && this.CategoryEditors.Count != 0); } return isBrowsable && property.MatchesFilter; } // <summary> // Sets the Disassociated flag on all contained properties to True // </summary> internal void MarkAllPropertiesDisassociated() { MarkAllPropertiesDisassociated(_basicProperties); MarkAllPropertiesDisassociated(_advancedProperties); } // <summary> // Sets the Disassociated flag on all contained attached properties to True // </summary> internal void MarkAttachedPropertiesDisassociated() { MarkAttachedPropertiesDisassociated(_basicProperties); MarkAttachedPropertiesDisassociated(_advancedProperties); } // <summary> // Removes all properties from this category whose Disassociated flag is set to True // </summary> internal void CullDisassociatedProperties() { bool propertiesCulled = false; propertiesCulled |= CullDisassociatedProperties(_basicProperties); propertiesCulled |= CullDisassociatedProperties(_advancedProperties); if (propertiesCulled) { FirePropertiesChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } private static void MarkAllPropertiesDisassociated(ObservableCollectionWorkaround<PropertyEntry> propertyList) { foreach (ModelPropertyEntry property in propertyList) { property.Disassociated = true; } } private static void MarkAttachedPropertiesDisassociated(ObservableCollectionWorkaround<PropertyEntry> propertyList) { foreach (ModelPropertyEntry property in propertyList) { if (property.IsAttached) { property.Disassociated = true; } } } private static bool CullDisassociatedProperties(ObservableCollectionWorkaround<PropertyEntry> propertyList) { bool propertiesCulled = false; for (int i = propertyList.Count - 1; i >= 0; i--) { ModelPropertyEntry property = (ModelPropertyEntry)propertyList[i]; if (property.Disassociated) { property.Disconnect(); propertyList.RemoveAt(i); propertiesCulled = true; } } return propertiesCulled; } // INotifyCollectionChanged Members private void FirePropertiesChanged(NotifyCollectionChangedEventArgs collectionChangedEventArgs) { // Fire both "Properties" changed events OnPropertyChanged("Properties"); OnPropertyChanged("Item[]"); // as well as the appropriate collection-changed event if (CollectionChanged != null) { CollectionChanged(this, collectionChangedEventArgs); } } } }
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 WebApiControllers.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; } } }
//! \file ImageRCT.cs //! \date Fri Aug 01 11:36:31 2014 //! \brief RCT/RC8 image format implementation. // // Copyright (C) 2014-2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Formats.Properties; using GameRes.Formats.Strings; using GameRes.Utility; namespace GameRes.Formats.Majiro { internal class RctMetaData : ImageMetaData { public int Version; public bool IsEncrypted; public uint DataOffset; public uint DataSize; public uint AddSize; } internal class RctOptions : ResourceOptions { public string Password; } [Serializable] public class RctScheme : ResourceScheme { public Dictionary<string, string> KnownKeys; } [Export(typeof(ImageFormat))] public class RctFormat : ImageFormat { public override string Tag { get { return "RCT"; } } public override string Description { get { return "Majiro game engine RGB image format"; } } public override uint Signature { get { return 0x9a925a98; } } public bool OverlayFrames = true; public static Dictionary<string, string> KnownKeys = new Dictionary<string, string>(); public override ResourceScheme Scheme { get { return new RctScheme { KnownKeys = KnownKeys }; } set { KnownKeys = ((RctScheme)value).KnownKeys; } } public override ImageMetaData ReadMetaData (Stream stream) { stream.Position = 4; int id = stream.ReadByte(); if (0x54 != id) return null; int encryption = stream.ReadByte(); if (encryption != 0x43 && encryption != 0x53) return null; bool is_encrypted = 0x53 == encryption; int version = stream.ReadByte(); if (0x30 != version) return null; version = stream.ReadByte() - 0x30; if (version != 0 && version != 1) return null; using (var reader = new BinaryReader (stream, Encoding.ASCII, true)) { uint width = reader.ReadUInt32(); uint height = reader.ReadUInt32(); uint data_size = reader.ReadUInt32(); uint additional_size = 0; if (1 == version) { additional_size = reader.ReadUInt16(); } if (width > 0x8000 || height > 0x8000) return null; return new RctMetaData { Width = width, Height = height, OffsetX = 0, OffsetY = 0, BPP = 24, Version = version, IsEncrypted = is_encrypted, DataOffset = (uint)stream.Position, DataSize = data_size, AddSize = additional_size, }; } } byte[] Key = null; public override ImageData Read (Stream file, ImageMetaData info) { var meta = info as RctMetaData; if (null == meta) throw new ArgumentException ("RctFormat.Read should be supplied with RctMetaData", "info"); byte[] base_image = null; if (meta.FileName != null && meta.AddSize > 0 && OverlayFrames) base_image = ReadBaseImage (file, meta); var pixels = ReadPixelsData (file, meta); if (base_image != null) pixels = CombineImage (base_image, pixels); return ImageData.Create (meta, PixelFormats.Bgr24, null, pixels, (int)meta.Width*3); } byte[] CombineImage (byte[] base_image, byte[] overlay) { for (int i = 2; i < base_image.Length; i += 3) { if (0 == overlay[i-2] && 0 == overlay[i-1] && 0xff == overlay[i]) { overlay[i-2] = base_image[i-2]; overlay[i-1] = base_image[i-1]; overlay[i] = base_image[i]; } } return overlay; } byte[] ReadPixelsData (Stream file, RctMetaData meta) { file.Position = meta.DataOffset + meta.AddSize; if (meta.IsEncrypted) file = OpenEncryptedStream (file, meta.DataSize); try { using (var reader = new Reader (file, meta)) { reader.Unpack(); return reader.Data; } } catch { if (meta.IsEncrypted) Key = null; // probably incorrect encryption scheme caused exception, reset key throw; } } byte[] ReadBaseImage (Stream file, RctMetaData meta) { file.Position = meta.DataOffset; byte[] name_bin = new byte[meta.AddSize]; if (name_bin.Length != file.Read (name_bin, 0, name_bin.Length)) throw new EndOfStreamException(); try { string name = Encodings.cp932.GetString (name_bin, 0, name_bin.Length-1); string dir_name = Path.GetDirectoryName (meta.FileName); name = VFS.CombinePath (dir_name, name); if (VFS.FileExists (name)) { using (var base_file = VFS.OpenSeekableStream (name)) { var base_info = ReadMetaData (base_file) as RctMetaData; if (null != base_info && 0 == base_info.AddSize && meta.Width == base_info.Width && meta.Height == base_info.Height) { base_info.FileName = name; return ReadPixelsData (base_file, base_info); } } } } catch { /* ignore baseline image read errors */ } return null; } Stream OpenEncryptedStream (Stream file, uint data_size) { if (null == Key) { var password = QueryPassword(); if (string.IsNullOrEmpty (password)) throw new UnknownEncryptionScheme(); Key = InitDecryptionKey (password); } byte[] data = new byte[data_size]; if (data.Length != file.Read (data, 0, data.Length)) throw new EndOfStreamException(); for (int i = 0; i < data.Length; ++i) { data[i] ^= Key[i & 0x3FF]; } return new MemoryStream (data); } private byte[] InitDecryptionKey (string password) { byte[] bin_pass = Encodings.cp932.GetBytes (password); uint crc32 = Crc32.Compute (bin_pass, 0, bin_pass.Length); byte[] key_table = new byte[0x400]; unsafe { fixed (byte* key_ptr = key_table) { uint* key32 = (uint*)key_ptr; for (int i = 0; i < 0x100; ++i) *key32++ = crc32 ^ Crc32.Table[(i + crc32) & 0xFF]; } } return key_table; } private string QueryPassword () { var options = Query<RctOptions> (arcStrings.ArcImageEncrypted); return options.Password; } public override ResourceOptions GetDefaultOptions () { return new RctOptions { Password = Settings.Default.RCTPassword }; } public override ResourceOptions GetOptions (object widget) { var w = widget as GUI.WidgetRCT; if (null != w) Settings.Default.RCTPassword = w.Password.Text; return GetDefaultOptions(); } public override object GetAccessWidget () { return new GUI.WidgetRCT(); } public override void Write (Stream file, ImageData image) { using (var writer = new Writer (file)) writer.Pack (image.Bitmap); } internal class Writer : IDisposable { BinaryWriter m_out; uint[] m_input; int m_width; int m_height; int[] m_shift_table = new int[32]; const int MaxThunkSize = 0xffff + 0x7f; const int MaxMatchSize = 0xffff; struct ChunkPosition { public ushort Offset; public ushort Length; } public Writer (Stream output) { m_out = new BinaryWriter (output, Encoding.ASCII, true); } void PrepareInput (BitmapSource bitmap) { m_width = bitmap.PixelWidth; m_height = bitmap.PixelHeight; int pixels = m_width*m_height; m_input = new uint[pixels]; if (bitmap.Format != PixelFormats.Bgr32) { var converted_bitmap = new FormatConvertedBitmap(); converted_bitmap.BeginInit(); converted_bitmap.Source = bitmap; converted_bitmap.DestinationFormat = PixelFormats.Bgr32; converted_bitmap.EndInit(); bitmap = converted_bitmap; } unsafe { fixed (uint* buffer = m_input) { bitmap.CopyPixels (Int32Rect.Empty, (IntPtr)buffer, pixels*4, m_width*4); } } InitShiftTable (m_width); } void InitShiftTable (int width) { for (int i = 0; i < 32; ++i) { int shift = Reader.ShiftTable[i]; int shift_row = shift & 0x0f; shift >>= 4; shift_row *= width; shift -= shift_row; m_shift_table[i] = shift; } } List<byte> m_buffer = new List<byte>(); int m_buffer_size; public void Pack (BitmapSource bitmap) { PrepareInput (bitmap); long data_offset = 0x14; m_out.BaseStream.Position = data_offset; uint pixel = m_input[0]; m_out.Write ((byte)pixel); m_out.Write ((byte)(pixel >> 8)); m_out.Write ((byte)(pixel >> 16)); m_buffer.Clear(); m_buffer_size = 0; int last = m_input.Length; int current = 1; while (current != last) { var chunk_pos = FindLongest (current, last); if (chunk_pos.Length > 0) { Flush(); WritePos (chunk_pos); current += chunk_pos.Length; } else { WritePixel (m_input[current++]); } } Flush(); var data_size = m_out.BaseStream.Position - data_offset; m_out.BaseStream.Position = 0; WriteHeader ((uint)data_size); } void WriteHeader (uint data_size) { m_out.Write (0x9a925a98u); m_out.Write (0x30304354u); m_out.Write (m_width); m_out.Write (m_height); m_out.Write (data_size); } void WritePixel (uint pixel) { if (MaxThunkSize == m_buffer_size) Flush(); m_buffer.Add ((byte)pixel); m_buffer.Add ((byte)(pixel >> 8)); m_buffer.Add ((byte)(pixel >> 16)); ++m_buffer_size; } void Flush () { if (0 != m_buffer.Count) { if (m_buffer_size > 0x7f) { m_out.Write ((byte)0x7f); m_out.Write ((ushort)(m_buffer_size-0x80)); } else m_out.Write ((byte)(m_buffer_size-1)); foreach (var b in m_buffer) m_out.Write (b); m_buffer.Clear(); m_buffer_size = 0; } } ChunkPosition FindLongest (int buf_begin, int buf_end) { buf_end = Math.Min (buf_begin + MaxMatchSize, buf_end); ChunkPosition pos = new ChunkPosition { Offset = 0, Length = 0 }; for (int i = 0; i < 32; ++i) { int offset = buf_begin + m_shift_table[i]; if (offset < 0) continue; if (m_input[offset] != m_input[buf_begin]) continue; var last = Mismatch (buf_begin+1, buf_end, offset+1); int weight = last - offset; if (weight > pos.Length) { pos.Offset = (ushort)i; pos.Length = (ushort)weight; } } return pos; } int Mismatch (int first1, int last1, int first2) { while (first1 != last1 && m_input[first1] == m_input[first2]) { ++first1; ++first2; } return first2; } void WritePos (ChunkPosition pos) { int code = (pos.Offset << 2) | 0x80; if (pos.Length > 3) code |= 3; else code |= pos.Length - 1; m_out.Write ((byte)code); if (pos.Length > 3) m_out.Write ((ushort)(pos.Length - 4)); } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) { m_out.Dispose(); } disposed = true; } } #endregion } internal class Reader : IDisposable { private BinaryReader m_input; private uint m_width; private byte[] m_data; public byte[] Data { get { return m_data; } } public Reader (Stream file, RctMetaData info) { m_width = info.Width; m_data = new byte[m_width * info.Height * 3]; m_input = new BinaryReader (file, Encoding.ASCII, true); } internal static readonly sbyte[] ShiftTable = new sbyte[] { -16, -32, -48, -64, -80, -96, 49, 33, 17, 1, -15, -31, -47, 50, 34, 18, 2, -14, -30, -46, 51, 35, 19, 3, -13, -29, -45, 36, 20, 4, -12, -28, }; public void Unpack () { int pixels_remaining = m_data.Length; int data_pos = 0; int eax = 0; while (pixels_remaining > 0) { int count = eax*3 + 3; if (count > pixels_remaining) throw new InvalidFormatException(); pixels_remaining -= count; if (count != m_input.Read (m_data, data_pos, count)) throw new InvalidFormatException(); data_pos += count; while (pixels_remaining > 0) { eax = m_input.ReadByte(); if (0 == (eax & 0x80)) { if (0x7f == eax) eax += m_input.ReadUInt16(); break; } int shift_index = eax >> 2; eax &= 3; if (3 == eax) eax += m_input.ReadUInt16(); count = eax*3 + 3; if (pixels_remaining < count) throw new InvalidFormatException(); pixels_remaining -= count; int shift = ShiftTable[shift_index & 0x1f]; int shift_row = shift & 0x0f; shift >>= 4; shift_row *= (int)m_width; shift -= shift_row; shift *= 3; if (shift >= 0 || data_pos+shift < 0) throw new InvalidFormatException(); Binary.CopyOverlapped (m_data, data_pos+shift, data_pos, count); data_pos += count; } } } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) m_input.Dispose(); m_input = null; m_data = null; disposed = true; } } #endregion } } [Export(typeof(ImageFormat))] public class Rc8Format : ImageFormat { public override string Tag { get { return "RC8"; } } public override string Description { get { return "Majiro game engine indexed image format"; } } public override uint Signature { get { return 0x9a925a98; } } public override ImageMetaData ReadMetaData (Stream stream) { stream.Position = 4; int id = stream.ReadByte(); if (0x38 != id) return null; id = stream.ReadByte(); if (0x5f != id) return null; int version = stream.ReadByte(); if (0x30 != version) return null; version = stream.ReadByte() - 0x30; if (version != 0) return null; using (var reader = new BinaryReader (stream, Encoding.ASCII, true)) { uint width = reader.ReadUInt32(); uint height = reader.ReadUInt32(); if (width > 0x8000 || height > 0x8000) return null; return new ImageMetaData { Width = width, Height = height, OffsetX = 0, OffsetY = 0, BPP = 8, }; } } public override ImageData Read (Stream file, ImageMetaData info) { file.Position = 0x14; using (var reader = new Reader (file, info)) { reader.Unpack(); var palette = new BitmapPalette (reader.Palette); return ImageData.Create (info, PixelFormats.Indexed8, palette, reader.Data, (int)info.Width); } } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("Rc8Format.Write is not implemented."); } internal class Reader : IDisposable { private BinaryReader m_input; private uint m_width; private Color[] m_palette; private byte[] m_data; public Color[] Palette { get { return m_palette; } } public byte[] Data { get { return m_data; } } public Reader (Stream file, ImageMetaData info) { m_width = info.Width; var palette_data = new byte[0x300]; if (palette_data.Length != file.Read (palette_data, 0, palette_data.Length)) throw new InvalidFormatException(); m_palette = new Color[0x100]; for (int i = 0; i < 0x100; ++i) { m_palette[i] = Color.FromRgb (palette_data[i*3], palette_data[i*3+1], palette_data[i*3+2]); } m_data = new byte[m_width * info.Height]; m_input = new BinaryReader (file, Encoding.ASCII, true); } private static readonly sbyte[] ShiftTable = new sbyte[] { -16, -32, -48, -64, 49, 33, 17, 1, -15, -31, -47, 34, 18, 2, -14, -30, }; public void Unpack () { int data_pos = 0; int eax = 0; int pixels_remaining = m_data.Length; while (pixels_remaining > 0) { int count = eax + 1; if (count > pixels_remaining) throw new InvalidFormatException(); pixels_remaining -= count; if (count != m_input.Read (m_data, data_pos, count)) throw new InvalidFormatException(); data_pos += count; while (pixels_remaining > 0) { eax = m_input.ReadByte(); if (0 == (eax & 0x80)) { if (0x7f == eax) eax += m_input.ReadUInt16(); break; } int shift_index = eax >> 3; eax &= 7; if (7 == eax) eax += m_input.ReadUInt16(); count = eax + 3; if (pixels_remaining < count) throw new InvalidFormatException(); pixels_remaining -= count; int shift = ShiftTable[shift_index & 0x0f]; int shift_row = shift & 0x0f; shift >>= 4; shift_row *= (int)m_width; shift -= shift_row; if (shift >= 0 || data_pos+shift < 0) throw new InvalidFormatException(); Binary.CopyOverlapped (m_data, data_pos+shift, data_pos, count); data_pos += count; } } } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) m_input.Dispose(); m_input = null; m_data = null; disposed = true; } } #endregion } } }
// 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 applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// VirtualNetworksOperations operations. /// </summary> public partial interface IVirtualNetworksOperations { /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified virtual network by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a virtual network in the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network /// operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Checks whether a private IP address is available for use. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='ipAddress'> /// The private IP address to be verified. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPAddressAvailabilityResult>> CheckIPAddressAvailabilityWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a virtual network in the specified resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network /// operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// // ImportDialog.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2006-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Gtk; using Glade; using Mono.Unix; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Gui; using Banshee.Gui.Dialogs; namespace Banshee.Library.Gui { public class ImportDialog : GladeDialog { private ComboBox source_combo_box; private ListStore source_model; private AccelGroup accel_group; private Button import_button; [Widget] private Gtk.Label choose_label; public ImportDialog () : this (false) { } public ImportDialog (bool doNotShowAgainVisible) : base ("ImportDialog") { accel_group = new AccelGroup (); if (ServiceManager.Contains ("GtkElementsService")) { Dialog.TransientFor = ServiceManager.Get<GtkElementsService> ().PrimaryWindow; } Dialog.WindowPosition = WindowPosition.CenterOnParent; Dialog.AddAccelGroup (accel_group); Dialog.DefaultResponse = ResponseType.Ok; import_button = (Glade["ImportButton"] as Button); DoNotShowAgainVisible = doNotShowAgainVisible; PopulateSourceList (); ServiceManager.SourceManager.SourceAdded += OnSourceAdded; ServiceManager.SourceManager.SourceRemoved += OnSourceRemoved; ServiceManager.SourceManager.SourceUpdated += OnSourceUpdated; Glade["MessageLabel"].Visible = ServiceManager.SourceManager.DefaultSource.Count == 0; import_button.AddAccelerator ("activate", accel_group, (uint)Gdk.Key.Return, 0, AccelFlags.Visible); Dialog.StyleSet += delegate { UpdateIcons (); }; } private void UpdateImportLabel () { string label = ActiveSource == null ? null : ActiveSource.ImportLabel; import_button.Label = label ?? Catalog.GetString ("_Import"); import_button.WidthRequest = Math.Max (import_button.WidthRequest, 140); } private void PopulateSourceList () { source_model = new ListStore (typeof (Gdk.Pixbuf), typeof (string), typeof (IImportSource)); source_combo_box = new ComboBox (); source_combo_box.Changed += delegate { UpdateImportLabel (); }; source_combo_box.Model = source_model; choose_label.MnemonicWidget = source_combo_box; CellRendererPixbuf pixbuf_cr = new CellRendererPixbuf (); CellRendererText text_cr = new CellRendererText (); source_combo_box.PackStart (pixbuf_cr, false); source_combo_box.PackStart (text_cr, true); source_combo_box.SetAttributes (pixbuf_cr, "pixbuf", 0); source_combo_box.SetAttributes (text_cr, "text", 1); TreeIter active_iter = TreeIter.Zero; List<IImportSource> sources = new List<IImportSource> (); // Add the standalone import sources foreach (IImportSource source in ServiceManager.Get<ImportSourceManager> ()) { sources.Add (source); } // Find active sources that implement IImportSource foreach (Source source in ServiceManager.SourceManager.Sources) { if (source is IImportSource) { sources.Add ((IImportSource)source); } } // Sort the sources by their SortOrder properties sources.Sort (import_source_comparer); // And actually add them to the dialog foreach (IImportSource source in sources) { AddSource (source); } if (!active_iter.Equals(TreeIter.Zero) || (active_iter.Equals (TreeIter.Zero) && source_model.GetIterFirst (out active_iter))) { source_combo_box.SetActiveIter (active_iter); } (Glade["ComboVBox"] as Box).PackStart (source_combo_box, false, false, 0); source_combo_box.ShowAll (); } private void UpdateIcons () { for (int i = 0, n = source_model.IterNChildren (); i < n; i++) { TreeIter iter; if (source_model.IterNthChild (out iter, i)) { object o = source_model.GetValue (iter, 0); IImportSource source = (IImportSource)source_model.GetValue (iter, 2); if (o != null) { ((Gdk.Pixbuf)o).Dispose (); } source_model.SetValue (iter, 0, GetIcon (source)); } } } private Gdk.Pixbuf GetIcon (IImportSource source) { return IconThemeUtils.LoadIcon (22, source.IconNames); } private TreeIter AddSource (IImportSource source) { if (source == null) { return TreeIter.Zero; } return source_model.AppendValues (GetIcon (source), source.Name, source); } private void OnSourceAdded (SourceAddedArgs args) { if(args.Source is IImportSource) { Banshee.Base.ThreadAssist.ProxyToMain (delegate { AddSource ((IImportSource)args.Source); }); } } private void OnSourceRemoved (SourceEventArgs args) { if (args.Source is IImportSource) { Banshee.Base.ThreadAssist.ProxyToMain (delegate { TreeIter iter; if (FindSourceIter (out iter, (IImportSource)args.Source)) { source_model.Remove (ref iter); } }); } } private void OnSourceUpdated (SourceEventArgs args) { if (args.Source is IImportSource) { Banshee.Base.ThreadAssist.ProxyToMain (delegate { TreeIter iter; if(FindSourceIter (out iter, (IImportSource)args.Source)) { source_model.SetValue (iter, 1, args.Source.Name); } }); } } private bool FindSourceIter (out TreeIter iter, IImportSource source) { iter = TreeIter.Zero; for (int i = 0, n = source_model.IterNChildren (); i < n; i++) { TreeIter _iter; if (source_model.IterNthChild (out _iter, i)) { if (source == source_model.GetValue (_iter, 2)) { iter = _iter; return true; } } } return false; } public bool DoNotShowAgainVisible { get { return Glade["DoNotShowCheckBox"].Visible; } set { Glade["DoNotShowCheckBox"].Visible = value; } } public bool DoNotShowAgain { get { return (Glade["DoNotShowCheckBox"] as CheckButton).Active; } } public IImportSource ActiveSource { get { TreeIter iter; if (source_combo_box.GetActiveIter (out iter)) { return (IImportSource)source_model.GetValue (iter, 2); } return null; } } private static IComparer<IImportSource> import_source_comparer = new ImportSourceComparer (); private class ImportSourceComparer : IComparer<IImportSource> { public int Compare (IImportSource a, IImportSource b) { int ret = a.SortOrder.CompareTo (b.SortOrder); return ret != 0 ? ret : a.Name.CompareTo (b.Name); } } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.ADF.CATIDs; using System.Runtime.InteropServices; namespace PanZoom { [ClassInterface(ClassInterfaceType.None)] [Guid("B50CB8E7-1CD0-41d3-8C89-4CD8969E802F")] public class FixedZoomOut : ICommand { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Unregister(regKey); } #endregion #endregion [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr hObject); private bool m_enabled; private System.Drawing.Bitmap m_bitmap; private IntPtr m_hBitmap; private IHookHelper m_pHookHelper; public FixedZoomOut() { string[] res = GetType().Assembly.GetManifestResourceNames(); if(res.GetLength(0) > 0) { m_bitmap = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream(GetType(), "zoomoutfxd.bmp")); if(m_bitmap != null) { m_bitmap.MakeTransparent(m_bitmap.GetPixel(1,1)); m_hBitmap = m_bitmap.GetHbitmap(); } } m_pHookHelper = new HookHelperClass (); } ~FixedZoomOut() { if(m_hBitmap.ToInt32() != 0) DeleteObject(m_hBitmap); } #region ICommand Members public void OnClick() { //Get IActiveView interface IActiveView pActiveView = (IActiveView) m_pHookHelper.FocusMap; //Get IEnvelope interface IEnvelope pEnvelope = (IEnvelope) pActiveView.Extent; //Expand envelope and refresh the view pEnvelope.Expand (1.25, 1.25, true); pActiveView.Extent = pEnvelope; pActiveView.Refresh(); } public string Message { get { return "Zoom out from the center of the map"; } } public int Bitmap { get { return m_hBitmap.ToInt32(); } } public void OnCreate(object hook) { m_pHookHelper.Hook = hook; m_enabled = true; } public string Caption { get { return "Fixed Zoom Out"; } } public string Tooltip { get { return "Fixed Zoom Out"; } } public int HelpContextID { get { // TODO: Add FixedZoomOut.HelpContextID getter implementation return 0; } } public string Name { get { return "Sample_Pan/FixedZoomOut"; } } public bool Checked { get { return false; } } public bool Enabled { get { return m_enabled; } } public string HelpFile { get { // TODO: Add FixedZoomOut.HelpFile getter implementation return null; } } public string Category { get { return "Sample_Pan/Zoom"; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Collections.ObjectModel { /// <summary> /// Implementation of a dynamic data collection based on generic Collection&lt;T&gt;, /// implementing INotifyCollectionChanged to notify listeners /// when items get added, removed or the whole list is refreshed. /// </summary> [Serializable] [DebuggerTypeProxy(typeof(CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged { private SimpleMonitor _monitor; // Lazily allocated only when a subclass calls BlockReentrancy() or during serialization. Do not rename (binary serialization) [NonSerialized] private int _blockReentrancyCount; /// <summary> /// Initializes a new instance of ObservableCollection that is empty and has default initial capacity. /// </summary> public ObservableCollection() { } /// <summary> /// Initializes a new instance of the ObservableCollection class that contains /// elements copied from the specified collection and has sufficient capacity /// to accommodate the number of elements copied. /// </summary> /// <param name="collection">The collection whose elements are copied to the new list.</param> /// <remarks> /// The elements are copied onto the ObservableCollection in the /// same order they are read by the enumerator of the collection. /// </remarks> /// <exception cref="ArgumentNullException"> collection is a null reference </exception> public ObservableCollection(IEnumerable<T> collection) : base(CreateCopy(collection, nameof(collection))) { } /// <summary> /// Initializes a new instance of the ObservableCollection class /// that contains elements copied from the specified list /// </summary> /// <param name="list">The list whose elements are copied to the new list.</param> /// <remarks> /// The elements are copied onto the ObservableCollection in the /// same order they are read by the enumerator of the list. /// </remarks> /// <exception cref="ArgumentNullException"> list is a null reference </exception> public ObservableCollection(List<T> list) : base(CreateCopy(list, nameof(list))) { } private static List<T> CreateCopy(IEnumerable<T> collection, string paramName) { if (collection == null) { throw new ArgumentNullException(paramName); } return new List<T>(collection); } /// <summary> /// Move item at oldIndex to newIndex. /// </summary> public void Move(int oldIndex, int newIndex) => MoveItem(oldIndex, newIndex); /// <summary> /// PropertyChanged event (per <see cref="INotifyPropertyChanged" />). /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add => PropertyChanged += value; remove => PropertyChanged -= value; } /// <summary> /// Occurs when the collection changes, either by adding or removing an item. /// </summary> /// <remarks> /// see <seealso cref="INotifyCollectionChanged"/> /// </remarks> [field: NonSerialized] public virtual event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Called by base class Collection&lt;T&gt; when the list is being cleared; /// raises a CollectionChanged event to any listeners. /// </summary> protected override void ClearItems() { CheckReentrancy(); base.ClearItems(); OnCountPropertyChanged(); OnIndexerPropertyChanged(); OnCollectionReset(); } /// <summary> /// Called by base class Collection&lt;T&gt; when an item is removed from list; /// raises a CollectionChanged event to any listeners. /// </summary> protected override void RemoveItem(int index) { CheckReentrancy(); T removedItem = this[index]; base.RemoveItem(index); OnCountPropertyChanged(); OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index); } /// <summary> /// Called by base class Collection&lt;T&gt; when an item is added to list; /// raises a CollectionChanged event to any listeners. /// </summary> protected override void InsertItem(int index, T item) { CheckReentrancy(); base.InsertItem(index, item); OnCountPropertyChanged(); OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index); } /// <summary> /// Called by base class Collection&lt;T&gt; when an item is set in list; /// raises a CollectionChanged event to any listeners. /// </summary> protected override void SetItem(int index, T item) { CheckReentrancy(); T originalItem = this[index]; base.SetItem(index, item); OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index); } /// <summary> /// Called by base class ObservableCollection&lt;T&gt; when an item is to be moved within the list; /// raises a CollectionChanged event to any listeners. /// </summary> protected virtual void MoveItem(int oldIndex, int newIndex) { CheckReentrancy(); T removedItem = this[oldIndex]; base.RemoveItem(oldIndex); base.InsertItem(newIndex, removedItem); OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex); } /// <summary> /// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />). /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } /// <summary> /// PropertyChanged event (per <see cref="INotifyPropertyChanged" />). /// </summary> [field: NonSerialized] protected virtual event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raise CollectionChanged event to any listeners. /// Properties/methods modifying this ObservableCollection will raise /// a collection changed event through this virtual method. /// </summary> /// <remarks> /// When overriding this method, either call its base implementation /// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes. /// </remarks> protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = CollectionChanged; if (handler != null) { // Not calling BlockReentrancy() here to avoid the SimpleMonitor allocation. _blockReentrancyCount++; try { handler(this, e); } finally { _blockReentrancyCount--; } } } /// <summary> /// Disallow reentrant attempts to change this collection. E.g. an event handler /// of the CollectionChanged event is not allowed to make changes to this collection. /// </summary> /// <remarks> /// typical usage is to wrap e.g. a OnCollectionChanged call with a using() scope: /// <code> /// using (BlockReentrancy()) /// { /// CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, item, index)); /// } /// </code> /// </remarks> protected IDisposable BlockReentrancy() { _blockReentrancyCount++; return EnsureMonitorInitialized(); } /// <summary> Check and assert for reentrant attempts to change this collection. </summary> /// <exception cref="InvalidOperationException"> raised when changing the collection /// while another collection change is still being notified to other listeners </exception> protected void CheckReentrancy() { if (_blockReentrancyCount > 0) { // we can allow changes if there's only one listener - the problem // only arises if reentrant changes make the original event args // invalid for later listeners. This keeps existing code working // (e.g. Selector.SelectedItems). if (CollectionChanged?.GetInvocationList().Length > 1) throw new InvalidOperationException(SR.ObservableCollectionReentrancyNotAllowed); } } /// <summary> /// Helper to raise a PropertyChanged event for the Count property /// </summary> private void OnCountPropertyChanged() => OnPropertyChanged(EventArgsCache.CountPropertyChanged); /// <summary> /// Helper to raise a PropertyChanged event for the Indexer property /// </summary> private void OnIndexerPropertyChanged() => OnPropertyChanged(EventArgsCache.IndexerPropertyChanged); /// <summary> /// Helper to raise CollectionChanged event to any listeners /// </summary> private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index)); } /// <summary> /// Helper to raise CollectionChanged event to any listeners /// </summary> private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex)); } /// <summary> /// Helper to raise CollectionChanged event to any listeners /// </summary> private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index)); } /// <summary> /// Helper to raise CollectionChanged event with action == Reset to any listeners /// </summary> private void OnCollectionReset() => OnCollectionChanged(EventArgsCache.ResetCollectionChanged); private SimpleMonitor EnsureMonitorInitialized() { return _monitor ?? (_monitor = new SimpleMonitor(this)); } [OnSerializing] private void OnSerializing(StreamingContext context) { EnsureMonitorInitialized(); _monitor._busyCount = _blockReentrancyCount; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { if (_monitor != null) { _blockReentrancyCount = _monitor._busyCount; _monitor._collection = this; } } // this class helps prevent reentrant calls [Serializable] [TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] private sealed class SimpleMonitor : IDisposable { internal int _busyCount; // Only used during (de)serialization to maintain compatibility with desktop. Do not rename (binary serialization) [NonSerialized] internal ObservableCollection<T> _collection; public SimpleMonitor(ObservableCollection<T> collection) { Debug.Assert(collection != null); _collection = collection; } public void Dispose() => _collection._blockReentrancyCount--; } } internal static class EventArgsCache { internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs("Count"); internal static readonly PropertyChangedEventArgs IndexerPropertyChanged = new PropertyChangedEventArgs("Item[]"); internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset); } }
#region Copyright // // This framework is based on log4j see http://jakarta.apache.org/log4j // Copyright (C) The Apache Software Foundation. All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.txt file. // #endregion using System; using System.Collections; using log4net.Appender; using log4net.helpers; using log4net.spi; #if NUNIT_TESTS using NUnit.Framework; #endif // NUNIT_TESTS namespace log4net.Repository.Hierarchy { /// <summary> /// Internal class used to provide implementation of <see cref="ILog"/> /// interface. Applications should use <see cref="LogManager"/> to get /// logger instances. /// </summary> /// <remarks> /// This is one of the central class' in the log4net implementation. One of the /// distinctive features of log4net are hierarchical loggers and their /// evaluation. /// </remarks> public class Logger : IAppenderAttachable, ILogger { #region Protected Instance Constructors /// <summary> /// This constructor created a new <see cref="Logger" /> instance and /// sets its name. /// </summary> /// <remarks> /// <para> /// Loggers are constructed by <see cref="ILoggerFactory"/> /// objects. See <see cref="DefaultLoggerFactory"/> for the default /// logger creator. /// </para> /// </remarks> /// <param name="name">The name of the <see cref="Logger" />.</param> protected Logger(string name) { #if NETCF // NETCF: String.Intern causes Native Exception m_name = name; #else m_name = string.Intern(name); #endif } #endregion Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the parent logger in the hierarchy. /// </summary> /// <value> /// The parent logger in the hierarchy. /// </value> /// <remarks> /// Part of the Composite pattern that makes the hierarchy. /// </remarks> virtual public Logger Parent { get { return m_parent; } set { m_parent = value; } } /// <summary> /// Gets or sets a value indicating if child loggers inherit their parent's appenders. /// </summary> /// <value> /// <c>true</c> if child loggers inherit their parent's appenders. /// </value> /// <remarks> /// Additivity is set to <c>true</c> by default, that is children inherit /// the appenders of their ancestors by default. If this variable is /// set to <c>false</c> then the appenders found in the /// ancestors of this logger are not used. However, the children /// of this logger will inherit its appenders, unless the children /// have their additivity flag set to <c>false</c> too. See /// the user manual for more details. /// </remarks> virtual public bool Additivity { get { return m_additive; } set { m_additive = value; } } /// <summary> /// Gets the effective level for this logger. /// </summary> /// <remarks> /// <para> /// Starting from this logger, searches the logger hierarchy for a /// non-null level and returns it. Otherwise, returns the level of the /// root logger. /// </para> /// <para>The Logger class is designed so that this method executes as /// quickly as possible.</para> /// </remarks> /// <returns>The nearest level in the logger hierarchy.</returns> virtual public Level EffectiveLevel { get { for(Logger c = this; c != null; c = c.m_parent) { if (c.m_level != null) { return c.m_level; } } return null; // If reached will cause an NullPointerException. } } /// <summary> /// Gets or sets the <see cref="Hierarchy"/> where this /// <c>Logger</c> instance is attached to. /// </summary> /// <value>The hierarchy that this logger belongs to.</value> virtual public Hierarchy Hierarchy { get { return m_hierarchy; } set { m_hierarchy = value; } } /// <summary> /// Gets or sets the assigned <see cref="Level"/>, if any, for this Logger. /// </summary> /// <value> /// The <see cref="Level"/> of this logger. /// </value> /// <remarks> /// The assigned <see cref="Level"/> can be <c>null</c>. /// </remarks> virtual public Level Level { get { return m_level; } set { m_level = value; } } #endregion Public Instance Properties #region Implementation of IAppenderAttachable /// <summary> /// Add <paramref name="newAppender"/> to the list of appenders of this /// Logger instance. /// </summary> /// <param name="newAppender">An appender to add to this logger</param> /// <remarks> /// Add <paramref name="newAppender"/> to the list of appenders of this /// Logger instance. /// <para>If <paramref name="newAppender"/> is already in the list of /// appenders, then it won't be added again.</para> /// </remarks> virtual public void AddAppender(IAppender newAppender) { if (newAppender == null) { throw new ArgumentNullException("newAppender"); } lock(this) { if (m_aai == null) { m_aai = new log4net.helpers.AppenderAttachedImpl(); } m_aai.AddAppender(newAppender); } } /// <summary> /// Get the appenders contained in this logger as an /// <see cref="System.Collections.ICollection"/>. /// </summary> /// <remarks> /// Get the appenders contained in this logger as an /// <see cref="System.Collections.ICollection"/>. If no appenders /// can be found, then a <see cref="EmptyCollection"/> is returned. /// </remarks> /// <returns>A collection of the appenders in this logger</returns> virtual public AppenderCollection Appenders { get { lock(this) { if (m_aai == null) { return AppenderCollection.EmptyCollection; } else { return m_aai.Appenders; } } } } /// <summary> /// Look for the appender named as <c>name</c> /// </summary> /// <param name="name">The name of the appender to lookup</param> /// <returns>The appender with the name specified, or <c>null</c>.</returns> /// <remarks> /// Returns the named appender, or null if the appender is not found. /// </remarks> virtual public IAppender GetAppender(string name) { lock(this) { if (m_aai == null || name == null) { return null; } return m_aai.GetAppender(name); } } /// <summary> /// Remove all previously added appenders from this Logger instance. /// </summary> /// <remarks> /// Remove all previously added appenders from this Logger instance. /// <para>This is useful when re-reading configuration information.</para> /// </remarks> virtual public void RemoveAllAppenders() { lock(this) { if (m_aai != null) { m_aai.RemoveAllAppenders(); m_aai = null; } } } /// <summary> /// Remove the appender passed as parameter form the list of appenders. /// </summary> /// <param name="appender">The appender to remove</param> /// <remarks> /// Remove the appender passed as parameter form the list of appenders. /// </remarks> virtual public void RemoveAppender(IAppender appender) { lock(this) { if (appender != null && m_aai != null) { m_aai.RemoveAppender(appender); } } } /// <summary> /// Remove the appender passed as parameter form the list of appenders. /// </summary> /// <param name="name">The name of the appender to remove</param> /// <remarks> /// Remove the named appender passed as parameter form the list of appenders. /// </remarks> virtual public void RemoveAppender(string name) { lock(this) { if (name != null && m_aai != null) { m_aai.RemoveAppender(name); } } } #endregion #region Implementation of ILogger /// <summary> /// Gets the logger name. /// </summary> /// <value> /// The name of the logger. /// </value> virtual public string Name { get { return m_name; } } /// <summary> /// This generic form is intended to be used by wrappers. /// </summary> /// <param name="callerFullName">The wrapper class' fully qualified class name.</param> /// <param name="level">The level of the message to be logged.</param> /// <param name="message">The message object to log.</param> /// <param name="t">The exception to log, including its stack trace.</param> /// <remarks> /// Generate a logging event for the specified <paramref name="level"/> using /// the <paramref name="message"/> and <paramref name="t"/>. /// </remarks> virtual public void Log(string callerFullName, Level level, object message, Exception t) { if (IsEnabledFor(level)) { ForcedLog((callerFullName != null) ? callerFullName : ThisClassFullName , level, message, t); } } /// <summary> /// This is the most generic printing method. /// This generic form is intended to be used by wrappers /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// Logs the logging event specified. /// </remarks> virtual public void Log(LoggingEvent logEvent) { if (logEvent == null) { throw new ArgumentNullException("logEvent"); } if (IsEnabledFor(logEvent.Level)) { ForcedLog(logEvent); } } /// <summary> /// Checks if this logger is enabled for a given <see cref="Level"/> passed as parameter. /// </summary> /// <param name="level">The level to check.</param> /// <returns> /// <c>true</c> if this logger is enabled for <c>level</c>, otherwise <c>false</c>. /// </returns> virtual public bool IsEnabledFor(Level level) { if (m_hierarchy.IsDisabled(level)) { return false; } return level >= this.EffectiveLevel; } /// <summary> /// Gets the <see cref="ILoggerRepository"/> where this /// <c>Logger</c> instance is attached to. /// </summary> /// <value>The <see cref="ILoggerRepository"/> that this logger belongs to.</value> public ILoggerRepository Repository { get { return m_hierarchy; } } #endregion Implementation of ILogger /// <summary> /// Call the appenders in the hierarchy starting at /// <c>this</c>. If no appenders could be found, emit a /// warning. /// </summary> /// <remarks> /// This method calls all the appenders inherited from the /// hierarchy circumventing any evaluation of whether to log or not /// to log the particular log request. /// </remarks> /// <param name="loggingEvent">The event to log.</param> virtual protected void CallAppenders(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } int writes = 0; for(Logger c=this; c != null; c=c.m_parent) { // Protected against simultaneous call to addAppender, removeAppender,... lock(c) { if (c.m_aai != null) { writes += c.m_aai.AppendLoopOnAppenders(loggingEvent); } if (!c.m_additive) { break; } } } // No appenders in hierarchy, warn user only once. // // Note that by including the AppDomain values for the currently running // thread, it becomes much easier to see which application the warning // is from, which is especially helpful in a multi-AppDomain environment // (like IIS with multiple VDIRS). Without this, it can be difficult // or impossible to determine which .config file is missing appender // definitions. // if (!m_hierarchy.EmittedNoAppenderWarning && writes == 0) { LogLog.Debug("Logger: No appenders could be found for logger [" + Name + "] repository [" + Repository.Name + "]"); LogLog.Debug("Logger: Please initialize the log4net system properly."); try { LogLog.Debug("Logger: Current AppDomain context information: "); LogLog.Debug("Logger: BaseDirectory : " + SystemInfo.ApplicationBaseDirectory); #if !NETCF LogLog.Debug("Logger: FriendlyName : " + AppDomain.CurrentDomain.FriendlyName); LogLog.Debug("Logger: DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory); #endif } catch(System.Security.SecurityException) { // Insufficent permissions to display info from the AppDomain } m_hierarchy.EmittedNoAppenderWarning = true; } } /// <summary> /// Closes all attached appenders implementing the IAppenderAttachable interface. /// </summary> /// <remarks> /// Used to ensure that the appenders are correctly shutdown. /// </remarks> virtual public void CloseNestedAppenders() { lock(this) { foreach(IAppender appender in this.Appenders) { if (appender is IAppenderAttachable) { appender.Close(); } } } } /// <summary> /// This is the most generic printing method. This generic form is intended to be used by wrappers /// </summary> /// <param name="level">The level of the message to be logged.</param> /// <param name="message">The message object to log.</param> /// <param name="t">The exception to log, including its stack trace.</param> /// <remarks> /// Generate a logging event for the specified <paramref name="level"/> using /// the <paramref name="message"/>. /// </remarks> virtual public void Log(Level level, object message, Exception t) { if (IsEnabledFor(level)) { ForcedLog(ThisClassFullName, level, message, t); } } /// <summary> /// Creates a new logging event and logs the event without further checks. /// </summary> /// <param name="callerFullName">The wrapper class' fully qualified class name.</param> /// <param name="level">The level of the message to be logged.</param> /// <param name="message">The message object to log.</param> /// <param name="t">The exception to log, including its stack trace.</param> /// <remarks> /// Generates a logging event and delivers it to the attached /// appenders. /// </remarks> virtual protected void ForcedLog(string callerFullName, Level level, object message, Exception t) { CallAppenders(new LoggingEvent(callerFullName, this.Hierarchy, this.Name, level, message, t)); } /// <summary> /// Creates a new logging event and logs the event without further checks. /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// Delivers the logging event to the attached appenders. /// </remarks> virtual protected void ForcedLog(LoggingEvent logEvent) { CallAppenders(logEvent); } #region Private Static Fields /// <summary> /// The fully qualified name of the Logger class. /// </summary> private readonly static string ThisClassFullName = typeof(Logger).FullName; #endregion Private Static Fields #region Private Instance Fields /// <summary> /// The name of this logger. /// </summary> private readonly string m_name; /// <summary> /// The assigned level of this logger. /// </summary> /// <remarks> /// The <c>level</c> variable need not be /// assigned a value in which case it is inherited /// form the hierarchy. /// </remarks> private Level m_level; /// <summary> /// The parent of this logger. /// </summary> /// <remarks> /// The parent of this logger. All loggers have at least one ancestor which is the root logger. /// </remarks> private Logger m_parent; /// <summary> /// Loggers need to know what Hierarchy they are in. /// </summary> /// <remarks> /// Loggers need to know what Hierarchy they are in. /// The hierarchy that this logger is a member of is stored /// here. /// </remarks> private Hierarchy m_hierarchy; /// <summary> /// Helper implementation of the <see cref="IAppenderAttachable"/> interface /// </summary> private log4net.helpers.AppenderAttachedImpl m_aai; /// <summary> /// Flag indicating if child loggers inherit their parents appenders /// </summary> /// <remarks> /// Additivity is set to true by default, that is children inherit /// the appenders of their ancestors by default. If this variable is /// set to <c>false</c> then the appenders found in the /// ancestors of this logger are not used. However, the children /// of this logger will inherit its appenders, unless the children /// have their additivity flag set to <c>false</c> too. See /// the user manual for more details. /// </remarks> private bool m_additive = true; #endregion #region NUnit Tests #if NUNIT_TESTS /// <summary> /// Used for internal unit testing the <see cref="Logger"/> class. /// </summary> /// <remarks> /// Internal unit test. Uses the NUnit test harness. /// </remarks> [TestFixture] public class LoggerTest { Logger log; // A short message. static string MSG = "M"; /// <summary> /// Any initialization that happens before each test can /// go here /// </summary> [SetUp] public void SetUp() { } /// <summary> /// Any steps that happen after each test go here /// </summary> [TearDown] public void TearDown() { // Regular users should not use the clear method lightly! LogManager.GetLoggerRepository().ResetConfiguration(); LogManager.GetLoggerRepository().Shutdown(); ((Hierarchy)LogManager.GetLoggerRepository()).Clear(); } /// <summary> /// Add an appender and see if it can be retrieved. /// </summary> [Test] public void TestAppender1() { log = LogManager.GetLogger("test").Logger as Logger; CountingAppender a1 = new CountingAppender(); a1.Name = "testAppender1"; log.AddAppender(a1); IEnumerator enumAppenders = log.Appenders.GetEnumerator(); Assertion.Assert( enumAppenders.MoveNext() ); CountingAppender aHat = (CountingAppender) enumAppenders.Current; Assertion.AssertEquals(a1, aHat); } /// <summary> /// Add an appender X, Y, remove X and check if Y is the only /// remaining appender. /// </summary> [Test] public void TestAppender2() { CountingAppender a1 = new CountingAppender(); a1.Name = "testAppender2.1"; CountingAppender a2 = new CountingAppender(); a2.Name = "testAppender2.2"; log = LogManager.GetLogger("test").Logger as Logger; log.AddAppender(a1); log.AddAppender(a2); CountingAppender aHat = (CountingAppender)log.GetAppender(a1.Name); Assertion.AssertEquals(a1, aHat); aHat = (CountingAppender)log.GetAppender(a2.Name); Assertion.AssertEquals(a2, aHat); log.RemoveAppender("testAppender2.1"); IEnumerator enumAppenders = log.Appenders.GetEnumerator(); Assertion.Assert( enumAppenders.MoveNext() ); aHat = (CountingAppender) enumAppenders.Current; Assertion.AssertEquals(a2, aHat); Assertion.Assert(!enumAppenders.MoveNext()); aHat = (CountingAppender)log.GetAppender(a2.Name); Assertion.AssertEquals(a2, aHat); } /// <summary> /// Test if logger a.b inherits its appender from a. /// </summary> [Test] public void TestAdditivity1() { Logger a = LogManager.GetLogger("a").Logger as Logger; Logger ab = LogManager.GetLogger("a.b").Logger as Logger; CountingAppender ca = new CountingAppender(); a.AddAppender(ca); a.Repository.Configured = true; Assertion.AssertEquals(ca.Counter, 0); ab.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(ca.Counter, 1); ab.Log(Level.INFO, MSG, null); Assertion.AssertEquals(ca.Counter, 2); ab.Log(Level.WARN, MSG, null); Assertion.AssertEquals(ca.Counter, 3); ab.Log(Level.ERROR, MSG, null); Assertion.AssertEquals(ca.Counter, 4); } /// <summary> /// Test multiple additivity. /// </summary> [Test] public void TestAdditivity2() { Logger a = LogManager.GetLogger("a").Logger as Logger; Logger ab = LogManager.GetLogger("a.b").Logger as Logger; Logger abc = LogManager.GetLogger("a.b.c").Logger as Logger; Logger x = LogManager.GetLogger("x").Logger as Logger; CountingAppender ca1 = new CountingAppender(); CountingAppender ca2 = new CountingAppender(); a.AddAppender(ca1); abc.AddAppender(ca2); a.Repository.Configured = true; Assertion.AssertEquals(ca1.Counter, 0); Assertion.AssertEquals(ca2.Counter, 0); ab.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(ca1.Counter, 1); Assertion.AssertEquals(ca2.Counter, 0); abc.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(ca1.Counter, 2); Assertion.AssertEquals(ca2.Counter, 1); x.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(ca1.Counter, 2); Assertion.AssertEquals(ca2.Counter, 1); } /// <summary> /// Test additivity flag. /// </summary> [Test] public void TestAdditivity3() { Logger root = ((Hierarchy)LogManager.GetLoggerRepository()).Root; Logger a = LogManager.GetLogger("a").Logger as Logger; Logger ab = LogManager.GetLogger("a.b").Logger as Logger; Logger abc = LogManager.GetLogger("a.b.c").Logger as Logger; Logger x = LogManager.GetLogger("x").Logger as Logger; CountingAppender caRoot = new CountingAppender(); CountingAppender caA = new CountingAppender(); CountingAppender caABC = new CountingAppender(); root.AddAppender(caRoot); a.AddAppender(caA); abc.AddAppender(caABC); a.Repository.Configured = true; Assertion.AssertEquals(caRoot.Counter, 0); Assertion.AssertEquals(caA.Counter, 0); Assertion.AssertEquals(caABC.Counter, 0); ab.Additivity = false; a.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(caRoot.Counter, 1); Assertion.AssertEquals(caA.Counter, 1); Assertion.AssertEquals(caABC.Counter, 0); ab.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(caRoot.Counter, 1); Assertion.AssertEquals(caA.Counter, 1); Assertion.AssertEquals(caABC.Counter, 0); abc.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(caRoot.Counter, 1); Assertion.AssertEquals(caA.Counter, 1); Assertion.AssertEquals(caABC.Counter, 1); } /// <summary> /// Test the ability to disable a level of message /// </summary> [Test] public void TestDisable1() { CountingAppender caRoot = new CountingAppender(); Logger root = ((Hierarchy)LogManager.GetLoggerRepository()).Root; root.AddAppender(caRoot); Hierarchy h = ((Hierarchy)LogManager.GetLoggerRepository()); h.Threshold = Level.INFO; h.Configured = true; Assertion.AssertEquals(caRoot.Counter, 0); root.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(caRoot.Counter, 0); root.Log(Level.INFO, MSG, null); Assertion.AssertEquals(caRoot.Counter, 1); root.Log(Level.WARN, MSG, null); Assertion.AssertEquals(caRoot.Counter, 2); root.Log(Level.WARN, MSG, null); Assertion.AssertEquals(caRoot.Counter, 3); h.Threshold = Level.WARN; root.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(caRoot.Counter, 3); root.Log(Level.INFO, MSG, null); Assertion.AssertEquals(caRoot.Counter, 3); root.Log(Level.WARN, MSG, null); Assertion.AssertEquals(caRoot.Counter, 4); root.Log(Level.ERROR, MSG, null); Assertion.AssertEquals(caRoot.Counter, 5); root.Log(Level.ERROR, MSG, null); Assertion.AssertEquals(caRoot.Counter, 6); h.Threshold = Level.OFF; root.Log(Level.DEBUG, MSG, null); Assertion.AssertEquals(caRoot.Counter, 6); root.Log(Level.INFO, MSG, null); Assertion.AssertEquals(caRoot.Counter, 6); root.Log(Level.WARN, MSG, null); Assertion.AssertEquals(caRoot.Counter, 6); root.Log(Level.ERROR, MSG, null); Assertion.AssertEquals(caRoot.Counter, 6); root.Log(Level.FATAL, MSG, null); Assertion.AssertEquals(caRoot.Counter, 6); root.Log(Level.FATAL, MSG, null); Assertion.AssertEquals(caRoot.Counter, 6); } /// <summary> /// Tests the Exists method of the Logger class /// </summary> [Test] public void TestExists() { object a = LogManager.GetLogger("a"); object a_b = LogManager.GetLogger("a.b"); object a_b_c = LogManager.GetLogger("a.b.c"); object t; t = LogManager.Exists("xx"); Assertion.AssertNull(t); t = LogManager.Exists("a"); Assertion.AssertSame(a, t); t = LogManager.Exists("a.b"); Assertion.AssertSame(a_b, t); t = LogManager.Exists("a.b.c"); Assertion.AssertSame(a_b_c, t); } /// <summary> /// Tests the chained level for a hierarchy /// </summary> [Test] public void TestHierarchy1() { Hierarchy h = new Hierarchy(); h.Root.Level = Level.ERROR; Logger a0 = h.GetLogger("a") as Logger; Assertion.AssertEquals("a", a0.Name); Assertion.AssertNull(a0.Level); Assertion.AssertSame(Level.ERROR, a0.EffectiveLevel); Logger a1 = h.GetLogger("a") as Logger; Assertion.AssertSame(a0, a1); } } #endif // NUNIT_TESTS #endregion } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using SoftLogik.Win.Data; using SoftLogik.Win.Security; using SoftLogik.Win.UI; namespace SoftLogik.Win { namespace Security { public class SecurityManager : IDisposable { public SecurityManager(DockPanel ActiveDockPanel) { m_dockPanel = ActiveDockPanel; } private SecureUser m_objUser; private List<SecureUser> m_objUserList; private SecurityForm m_frmManager; private LoginForm m_frmLoginWnd; private DockPanel m_dockPanel; private SecurityForm ManagerWnd { get { if (m_frmManager == null) { m_frmManager = new SecurityForm(); m_frmManager.DockPanel = m_dockPanel; } else if (m_frmManager.IsDisposed) { m_frmManager.Dispose(); m_frmManager = null; m_frmManager = new SecurityForm(); m_frmManager.DockPanel = m_dockPanel; } return m_frmManager; } } private LoginForm LoginWnd { get { if (m_frmLoginWnd == null) { m_frmLoginWnd = new LoginForm(); } else if (m_frmLoginWnd.IsDisposed) { m_frmLoginWnd.Dispose(); m_frmLoginWnd = null; m_frmLoginWnd = new LoginForm(); } return m_frmLoginWnd; } } public SecureUser MyUser { get { return m_objUser; } } /// <summary> /// MDI Parent, sets or returns the MDI Parent of this Form /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> public Form MdiParent { get { return ManagerWnd.MdiParent; } set { ManagerWnd.MdiParent = value; } } public void ShowManager() { ManagerWnd.Show(); } public void ShowLogin() { LoginWnd.ShowDialog(); } public void ShowPassword() { } public System.Collections.Generic.List<SecureUser> UserList { get { return m_objUserList; } } private bool disposedValue = false; // To detect redundant calls // IDisposable protected virtual void Dispose(bool disposing) { if (! this.disposedValue) { if (disposing) { // TODO: free unmanaged resources when explicitly called m_frmManager.Close(); m_frmManager.Dispose(); } // TODO: free shared unmanaged resources } this.disposedValue = true; } #region IDisposable Support // This code added by Visual Basic to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(true); GC.SuppressFinalize(this); } #endregion } public class SecureUser { #region Private Variables private string m_strName; private string m_strPassword; private List<SPPolicy> m_objPolicies; #endregion public SecureUser(string Name) { m_strName = Name; } public SecureUser(string Name, string Password) { m_strName = Name; m_strPassword = Password; } public SecureUser(string Name, string Password, List<SPPolicy> Policies) { m_strName = Name; m_strPassword = Password; m_objPolicies = Policies; } public SecureUser(List<SPPolicy> Policies) { m_objPolicies = Policies; } public string Name { get { return m_strName; } set { m_strName = value; } } public string Password { get { return m_strPassword; } set { m_strPassword = value; } } public System.Collections.Generic.List<SPPolicy> Policies { get { return m_objPolicies; } } } public class SPCompany : IDisposable { private string m_strName; private CompanyForm m_frmCompany; private CompanyForm CompanyWnd { get { if (m_frmCompany == null) { m_frmCompany = new CompanyForm(); } else if (m_frmCompany.IsDisposed) { m_frmCompany.Dispose(); m_frmCompany = null; m_frmCompany = new CompanyForm(); } return m_frmCompany; } } public string Name { get { return m_strName; } set { m_strName = value; } } /// <summary> /// MDI Parent, sets or returns the MDI Parent of this Form /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> public Form MdiParent { get { return CompanyWnd.MdiParent; } set { CompanyWnd.MdiParent = value; } } public void ShowManager() { CompanyWnd.Show(); } private bool disposedValue = false; // To detect redundant calls // IDisposable protected virtual void Dispose(bool disposing) { if (! this.disposedValue) { if (disposing) { // TODO: free unmanaged resources when explicitly called } // TODO: free shared unmanaged resources } this.disposedValue = true; } #region IDisposable Support // This code added by Visual Basic to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(true); GC.SuppressFinalize(this); } #endregion } sealed class SecuritySupport { public static void BuildSecurity(TreeView SourceTree, dsUserSecurity SourceData, bool ClearTree) { dsUserSecurity.SPApplicationDataTable dvTreeTable; TreeNode rootNode; TreeNode applicationNode; dvTreeTable = SourceData.SPApplication; if (ClearTree == false) //Might be a root node { rootNode = SourceTree.Nodes[0]; } else { SourceTree.Nodes.Clear(); //rootNode = SourceTree.Nodes.Add(TextDictionary("FL_SECURITY")) rootNode = SourceTree.Nodes.Add("Security Explorer"); } SourceTree.BeginUpdate(); foreach (dsUserSecurity.SPApplicationRow drvRow in dvTreeTable) { try { applicationNode = rootNode.Nodes.Add(drvRow("Name").ToString()); BuildRoleNode(applicationNode, drvRow); applicationNode.Expand(); applicationNode.ImageKey = "ApplicationNode"; applicationNode.Tag = "A:" + drvRow("ApplicationID").ToString(); } catch (Exception) { } } rootNode.Expand(); SourceTree.EndUpdate(); Cursor.Current = Cursors.Default; } private static void BuildRoleNode(TreeNode currentNode, dsUserSecurity.SPApplicationRow sourceData) { TreeNode newRoleNode; dsUserSecurity.SPUserRoleRow[] userRoleRows = (dsUserSecurity.SPUserRoleRow[]) (sourceData.GetChildRows("SPApplicationUserRole_FK")); currentNode.TreeView.BeginUpdate(); foreach (dsUserSecurity.SPUserRoleRow drvRow in userRoleRows) { try { TreeNode tempNode = currentNode.Nodes[drvRow.SPRoleRow.RoleName]; if (tempNode == null) { newRoleNode = currentNode.Nodes.Add(drvRow.SPRoleRow.RoleName); newRoleNode.Name = drvRow.SPRoleRow.RoleName; newRoleNode.ImageKey = "RoleNode"; newRoleNode.Tag = "R:" + drvRow.RoleID.ToString(); newRoleNode.NodeFont = new Font(currentNode.TreeView.Font, FontStyle.Bold); BuildUserNode(newRoleNode, drvRow.SPRoleRow); } } catch (Exception) { } } newRoleNode = null; currentNode.TreeView.EndUpdate(); } private static void BuildUserNode(TreeNode currentNode, dsUserSecurity.SPRoleRow sourceData) { dsUserSecurity.SPUserRoleRow[] newUsers = (dsUserSecurity.SPUserRoleRow[]) (sourceData.GetChildRows("SPRoleUserRole_Fk")); TreeNode newUserNode; foreach (dsUserSecurity.SPUserRoleRow drvRow in newUsers) { try { TreeNode tempNode = currentNode.Nodes[drvRow.SPUserRow("UserName").ToString()]; if (tempNode == null) { newUserNode = currentNode.Nodes.Add(drvRow.SPUserRow("UserName").ToString()); newUserNode.Name = drvRow.SPUserRow("UserName").ToString(); newUserNode.ImageKey = "UserNode"; newUserNode.Tag = "U:" + drvRow.SPUserRow("UserID").ToString(); } } catch (Exception) { } } newUserNode = null; } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using UnityEngine; using System.Collections.Generic; using System; namespace HoloToolkit.Unity.Collections { /// <summary> /// An Object Collection is simply a set of child objects organized with some /// layout parameters. The object collection can be used to quickly create /// control panels or sets of prefab/objects. /// </summary> public class ObjectCollection : MonoBehaviour { #region public members /// <summary> /// Action called when collection is updated /// </summary> public Action<ObjectCollection> OnCollectionUpdated; /// <summary> /// List of objects with generated data on the object. /// </summary> [SerializeField] public List<CollectionNode> NodeList = new List<CollectionNode>(); /// <summary> /// Type of surface to map the collection to. /// </summary> [Tooltip("Type of surface to map the collection to")] public SurfaceTypeEnum SurfaceType = SurfaceTypeEnum.Plane; /// <summary> /// Type of sorting to use. /// </summary> [Tooltip("Type of sorting to use")] public SortTypeEnum SortType = SortTypeEnum.None; /// <summary> /// Should the objects in the collection face the origin of the collection /// </summary> [Tooltip("Should the objects in the collection be rotated / how should they be rotated")] public OrientTypeEnum OrientType = OrientTypeEnum.FaceOrigin; /// <summary> /// Whether to sort objects by row first or by column first /// </summary> [Tooltip("Whether to sort objects by row first or by column first")] public LayoutTypeEnum LayoutType = LayoutTypeEnum.ColumnThenRow; /// <summary> /// Whether to treat inactive transforms as 'invisible' /// </summary> public bool IgnoreInactiveTransforms = true; /// <summary> /// This is the radius of either the Cylinder or Sphere mapping and is ignored when using the plane mapping. /// </summary> [Range(0.05f, 5.0f)] [Tooltip("Radius for the sphere or cylinder")] public float Radius = 2f; /// <summary> /// Number of rows per column, column number is automatically determined /// </summary> [Tooltip("Number of rows per column")] public int Rows = 3; /// <summary> /// Width of the cell per object in the collection. /// </summary> [Tooltip("Width of cell per object")] public float CellWidth = 0.5f; /// <summary> /// Height of the cell per object in the collection. /// </summary> [Tooltip("Height of cell per object")] public float CellHeight = 0.5f; /// <summary> /// Reference mesh to use for rendering the sphere layout /// </summary> [HideInInspector] public Mesh SphereMesh; /// <summary> /// Reference mesh to use for rendering the cylinder layout /// </summary> [HideInInspector] public Mesh CylinderMesh; #endregion #region private variables private int _columns; private float _width; private float _height; private float _circumference; private Vector2 _halfCell; #endregion public float Width { get { return _width; } } public float Height { get { return _height; } } /// <summary> /// Update collection is called from the editor button on the inspector. /// This function rebuilds / updates the layout. /// </summary> public void UpdateCollection() { // Check for empty nodes and remove them List<CollectionNode> emptyNodes = new List<CollectionNode>(); for (int i = 0; i < NodeList.Count; i++) { if (NodeList[i].transform == null || (IgnoreInactiveTransforms && !NodeList[i].transform.gameObject.activeSelf)) { emptyNodes.Add(NodeList[i]); } } // Now delete the empty nodes for (int i = 0; i < emptyNodes.Count; i++) { NodeList.Remove(emptyNodes[i]); } emptyNodes.Clear(); // Check when children change and adjust for (int i = 0; i < this.transform.childCount; i++) { Transform child = this.transform.GetChild(i); if (!ContainsNode(child) && (child.gameObject.activeSelf || !IgnoreInactiveTransforms)) { CollectionNode node = new CollectionNode(); node.Name = child.name; node.transform = child; NodeList.Add(node); } } switch (SortType) { case SortTypeEnum.None: break; case SortTypeEnum.Transform: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.transform.GetSiblingIndex().CompareTo(c2.transform.GetSiblingIndex()); }); break; case SortTypeEnum.Alphabetical: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.Name.CompareTo(c2.Name); }); break; case SortTypeEnum.AlphabeticalReversed: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.Name.CompareTo(c2.Name); }); NodeList.Reverse(); break; case SortTypeEnum.TransformReversed: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.transform.GetSiblingIndex().CompareTo(c2.transform.GetSiblingIndex()); }); NodeList.Reverse(); break; } _columns = Mathf.CeilToInt(NodeList.Count / Rows); _width = _columns * CellWidth; _height = Rows * CellHeight; _halfCell = new Vector2(CellWidth / 2f, CellHeight / 2f); _circumference = 2f * Mathf.PI * Radius; LayoutChildren(); if (OnCollectionUpdated != null) { OnCollectionUpdated.Invoke(this); } } /// <summary> /// Internal function for laying out all the children when UpdateCollection is called. /// </summary> private void LayoutChildren() { int cellCounter = 0; float startOffsetX; float startOffsetY; Vector3[] nodeGrid = new Vector3[NodeList.Count]; Vector3 newPos = Vector3.zero; Vector3 newRot = Vector3.zero; // Now lets lay out the grid startOffsetX = (_columns * 0.5f) * CellWidth; startOffsetY = (Rows * 0.5f) * CellHeight; cellCounter = 0; // First start with a grid then project onto surface switch (LayoutType) { case LayoutTypeEnum.ColumnThenRow: default: for (int c = 0; c < _columns; c++) { for (int r = 0; r < Rows; r++) { if (cellCounter < NodeList.Count) { nodeGrid[cellCounter] = new Vector3((c * CellWidth) - startOffsetX + _halfCell.x, -(r * CellHeight) + startOffsetY - _halfCell.y, 0f) + (Vector3)((NodeList[cellCounter])).Offset; } cellCounter++; } } break; case LayoutTypeEnum.RowThenColumn: for (int r = 0; r < Rows; r++) { for (int c = 0; c < _columns; c++) { if (cellCounter < NodeList.Count) { nodeGrid[cellCounter] = new Vector3((c * CellWidth) - startOffsetX + _halfCell.x, -(r * CellHeight) + startOffsetY - _halfCell.y, 0f) + (Vector3)((NodeList[cellCounter])).Offset; } cellCounter++; } } break; } switch (SurfaceType) { case SurfaceTypeEnum.Plane: for (int i = 0; i < NodeList.Count; i++) { newPos = nodeGrid[i]; NodeList[i].transform.localPosition = newPos; switch (OrientType) { case OrientTypeEnum.FaceOrigin: case OrientTypeEnum.FaceFoward: NodeList[i].transform.forward = transform.forward; break; case OrientTypeEnum.FaceOriginReversed: case OrientTypeEnum.FaceForwardReversed: newRot = Vector3.zero; NodeList[i].transform.forward = transform.forward; NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.None: break; default: throw new ArgumentOutOfRangeException(); } } break; case SurfaceTypeEnum.Cylinder: for (int i = 0; i < NodeList.Count; i++) { newPos = CylindricalMapping(nodeGrid[i], Radius); switch (OrientType) { case OrientTypeEnum.FaceOrigin: newRot = new Vector3(newPos.x, 0.0f, newPos.z); NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); break; case OrientTypeEnum.FaceOriginReversed: newRot = new Vector3(newPos.x, 0f, newPos.z); NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.FaceFoward: NodeList[i].transform.forward = transform.forward; break; case OrientTypeEnum.FaceForwardReversed: NodeList[i].transform.forward = transform.forward; NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.None: break; default: throw new ArgumentOutOfRangeException(); } NodeList[i].transform.localPosition = newPos; } break; case SurfaceTypeEnum.Sphere: for (int i = 0; i < NodeList.Count; i++) { newPos = SphericalMapping(nodeGrid[i], Radius); switch (OrientType) { case OrientTypeEnum.FaceOrigin: newRot = newPos; NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); break; case OrientTypeEnum.FaceOriginReversed: newRot = newPos; NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.FaceFoward: NodeList[i].transform.forward = transform.forward; break; case OrientTypeEnum.FaceForwardReversed: NodeList[i].transform.forward = transform.forward; NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.None: break; default: throw new ArgumentOutOfRangeException(); } NodeList[i].transform.localPosition = newPos; } break; case SurfaceTypeEnum.Scatter: // Get randomized planar mapping // Calculate radius of each node while we're here // Then use the packer function to shift them into place for (int i = 0; i < NodeList.Count; i++) { newPos = ScatterMapping (nodeGrid[i], Radius); Collider nodeCollider = NodeList[i].transform.GetComponentInChildren<Collider>(); if (nodeCollider != null) { // Make the radius the largest of the object's dimensions to avoid overlap Bounds bounds = nodeCollider.bounds; NodeList[i].Radius = Mathf.Max (Mathf.Max(bounds.size.x, bounds.size.y), bounds.size.z) / 2; } else { // Make the radius a default value // TODO move this into a public field ? NodeList[i].Radius = 1f; } NodeList[i].transform.localPosition = newPos; switch (OrientType) { case OrientTypeEnum.FaceOrigin: case OrientTypeEnum.FaceFoward: NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); break; case OrientTypeEnum.FaceOriginReversed: case OrientTypeEnum.FaceForwardReversed: NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.None: break; default: throw new ArgumentOutOfRangeException(); } } // Iterate [x] times // TODO move center, iterations and padding into a public field for (int i = 0; i < 100; i++) { IterateScatterPacking (NodeList, Radius); } break; } } /// <summary> /// Internal function for getting the relative mapping based on a source Vec3 and a radius for spherical mapping. /// </summary> /// <param name="source">The source <see cref="Vector3"/> to be mapped to sphere</param> /// <param name="radius">This is a <see cref="float"/> for the radius of the sphere</param> /// <returns></returns> private Vector3 SphericalMapping(Vector3 source, float radius) { Radius = radius >= 0 ? Radius : radius; Vector3 newPos = new Vector3(0f, 0f, Radius); float xAngle = (source.x / _circumference) * 360f; float yAngle = -(source.y / _circumference) * 360f; Quaternion rot = Quaternion.Euler(yAngle, xAngle, 0.0f); newPos = rot * newPos; return newPos; } /// <summary> /// Internal function for getting the relative mapping based on a source Vec3 and a radius for cylinder mapping. /// </summary> /// <param name="source">The source <see cref="Vector3"/> to be mapped to cylinder</param> /// <param name="radius">This is a <see cref="float"/> for the radius of the cylinder</param> /// <returns></returns> private Vector3 CylindricalMapping(Vector3 source, float radius) { Radius = radius >= 0 ? Radius : radius; Vector3 newPos = new Vector3(0f, source.y, Radius); float xAngle = (source.x / _circumference) * 360f; Quaternion rot = Quaternion.Euler(0.0f, xAngle, 0.0f); newPos = rot * newPos; return newPos; } /// <summary> /// Internal function to check if a node exists in the NodeList. /// </summary> /// <param name="node">A <see cref="Transform"/> of the node to see if it's in the NodeList</param> /// <returns></returns> private bool ContainsNode(Transform node) { for (int i = 0; i < NodeList.Count; i++) { if (NodeList[i] != null) { if (NodeList[i].transform == node) { return true; } } } return false; } /// <summary> /// Internal function for randomized mapping based on a source Vec3 and a radius for randomization distance. /// </summary> /// <param name="source">The source <see cref="Vector3"/> to be mapped to cylinder</param> /// <param name="radius">This is a <see cref="float"/> for the radius of the cylinder</param> /// <returns></returns> private Vector3 ScatterMapping(Vector3 source, float radius) { source.x = UnityEngine.Random.Range(-radius, radius); source.y = UnityEngine.Random.Range(-radius, radius); return source; } /// <summary> /// Internal function to pack randomly spaced nodes so they don't overlap /// Usually requires about 25 iterations for decent packing /// </summary> /// <returns></returns> private void IterateScatterPacking(List<CollectionNode> nodes, float radiusPadding) { // Sort by closest to center (don't worry about z axis) // Use the position of the collection as the packing center nodes.Sort(delegate (CollectionNode circle1, CollectionNode circle2) { float distance1 = (circle1.transform.localPosition).sqrMagnitude; float distance2 = (circle2.transform.localPosition).sqrMagnitude; return distance1.CompareTo(distance2); }); Vector3 difference; Vector2 difference2D; // Move them closer together float radiusPaddingSquared = Mathf.Pow(radiusPadding, 2f); for (int i = 0; i < nodes.Count - 1; i++) { for (int j = i + 1; j < nodes.Count; j++) { if (i != j) { difference = nodes[j].transform.localPosition - nodes[i].transform.localPosition; // Ignore Z axis difference2D.x = difference.x; difference2D.y = difference.y; float combinedRadius = nodes[i].Radius + nodes[j].Radius; float distance = difference2D.SqrMagnitude() - radiusPaddingSquared; float minSeparation = Mathf.Min(distance, radiusPaddingSquared); distance -= minSeparation; if (distance < (Mathf.Pow(combinedRadius, 2))) { difference2D.Normalize(); difference *= ((combinedRadius - Mathf.Sqrt(distance)) * 0.5f); nodes[j].transform.localPosition += difference; nodes[i].transform.localPosition -= difference; } } } } } /// <summary> /// Gizmos to draw when the Collection is selected. /// </summary> protected virtual void OnDrawGizmosSelected() { Vector3 scale = (2f * Radius) * Vector3.one; switch (SurfaceType) { case SurfaceTypeEnum.Plane: break; case SurfaceTypeEnum.Cylinder: Gizmos.color = Color.green; Gizmos.DrawWireMesh(CylinderMesh, transform.position, transform.rotation, scale); break; case SurfaceTypeEnum.Sphere: Gizmos.color = Color.green; Gizmos.DrawWireMesh(SphereMesh, transform.position, transform.rotation, scale); break; } } } }
using System; using System.Data; using System.Data.OleDb; using System.Collections; using System.Configuration; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.Admin.DS { public class Sys_VisibleControlDS { public Sys_VisibleControlDS() { } private const string THIS = "PCSComUtils.Admin.DS.Sys_VisibleControlDS"; /// <summary> /// This method uses to add data to Sys_VisibleControl /// </summary> /// <Inputs> /// Sys_VisibleControlVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { Sys_VisibleControlVO objObject = (Sys_VisibleControlVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO Sys_VisibleControl(" + Sys_VisibleControlTable.FORMNAME_FLD + "," + Sys_VisibleControlTable.CONTROLNAME_FLD + "," + Sys_VisibleControlTable.SUBCONTROLNAME_FLD + "," + Sys_VisibleControlTable.CONTROLGROUPID_FLD + ")" + "VALUES(?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.FORMNAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_VisibleControlTable.FORMNAME_FLD].Value = objObject.FormName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.CONTROLNAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_VisibleControlTable.CONTROLNAME_FLD].Value = objObject.ControlName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.SUBCONTROLNAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_VisibleControlTable.SUBCONTROLNAME_FLD].Value = objObject.SubControlName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.CONTROLGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibleControlTable.CONTROLGROUPID_FLD].Value = objObject.ControlGroupID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_VisibleControl /// </summary> /// <Inputs> /// Sys_VisibleControlVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + Sys_VisibleControlTable.TABLE_NAME + " WHERE " + "VisibleControlID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_VisibleControl /// </summary> /// <Inputs> /// Sys_VisibleControlVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_VisibleControlTable.VISIBLECONTROLID_FLD + "," + Sys_VisibleControlTable.FORMNAME_FLD + "," + Sys_VisibleControlTable.CONTROLNAME_FLD + "," + Sys_VisibleControlTable.SUBCONTROLNAME_FLD + "," + Sys_VisibleControlTable.CONTROLGROUPID_FLD + " FROM " + Sys_VisibleControlTable.TABLE_NAME +" WHERE " + Sys_VisibleControlTable.VISIBLECONTROLID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); Sys_VisibleControlVO objObject = new Sys_VisibleControlVO(); while (odrPCS.Read()) { objObject.VisibleControlID = int.Parse(odrPCS[Sys_VisibleControlTable.VISIBLECONTROLID_FLD].ToString().Trim()); objObject.FormName = odrPCS[Sys_VisibleControlTable.FORMNAME_FLD].ToString().Trim(); objObject.ControlName = odrPCS[Sys_VisibleControlTable.CONTROLNAME_FLD].ToString().Trim(); objObject.SubControlName = odrPCS[Sys_VisibleControlTable.SUBCONTROLNAME_FLD].ToString().Trim(); objObject.ControlGroupID = int.Parse(odrPCS[Sys_VisibleControlTable.CONTROLGROUPID_FLD].ToString().Trim()); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_VisibleControl /// </summary> /// <Inputs> /// Sys_VisibleControlVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; Sys_VisibleControlVO objObject = (Sys_VisibleControlVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE Sys_VisibleControl SET " + Sys_VisibleControlTable.FORMNAME_FLD + "= ?" + "," + Sys_VisibleControlTable.CONTROLNAME_FLD + "= ?" + "," + Sys_VisibleControlTable.SUBCONTROLNAME_FLD + "= ?" + "," + Sys_VisibleControlTable.CONTROLGROUPID_FLD + "= ?" +" WHERE " + Sys_VisibleControlTable.VISIBLECONTROLID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.FORMNAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_VisibleControlTable.FORMNAME_FLD].Value = objObject.FormName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.CONTROLNAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_VisibleControlTable.CONTROLNAME_FLD].Value = objObject.ControlName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.SUBCONTROLNAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_VisibleControlTable.SUBCONTROLNAME_FLD].Value = objObject.SubControlName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.CONTROLGROUPID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibleControlTable.CONTROLGROUPID_FLD].Value = objObject.ControlGroupID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_VisibleControlTable.VISIBLECONTROLID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_VisibleControlTable.VISIBLECONTROLID_FLD].Value = objObject.VisibleControlID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_VisibleControl /// </summary> /// <Inputs> /// Sys_VisibleControlVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_VisibleControlTable.VISIBLECONTROLID_FLD + "," + Sys_VisibleControlTable.FORMNAME_FLD + "," + Sys_VisibleControlTable.CONTROLNAME_FLD + "," + Sys_VisibleControlTable.SUBCONTROLNAME_FLD + "," + Sys_VisibleControlTable.CONTROLGROUPID_FLD + " FROM " + Sys_VisibleControlTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,Sys_VisibleControlTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to Sys_VisibleControl /// </summary> /// <Inputs> /// Sys_VisibleControlVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Monday, July 11, 2005 /// </History> public void UpdateDataSet(DataSet pdstData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + Sys_VisibleControlTable.VISIBLECONTROLID_FLD + "," + Sys_VisibleControlTable.FORMNAME_FLD + "," + Sys_VisibleControlTable.CONTROLNAME_FLD + "," + Sys_VisibleControlTable.SUBCONTROLNAME_FLD + "," + Sys_VisibleControlTable.CONTROLGROUPID_FLD + " FROM " + Sys_VisibleControlTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pdstData.EnforceConstraints = false; odadPCS.Update(pdstData,Sys_VisibleControlTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get hidden control /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// sonht /// </Authors> /// <History> /// Wednesday, April 12, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataTable GetVisibleControl(string pstrFormName,string pstrControlName,string pstrSubControl,string[] pstrRoleIDs) { const string METHOD_NAME = THIS + ".GetHiddenControl()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; string strRoleIDs = string.Empty; for(int i = 0; i < pstrRoleIDs.Length; i++) { strRoleIDs += pstrRoleIDs[i] + ","; } strRoleIDs = strRoleIDs.Substring(0,strRoleIDs.Length - 1); strSql= "SELECT VC." + Sys_VisibleControlTable.FORMNAME_FLD + ", VC." + Sys_VisibleControlTable.CONTROLNAME_FLD + ", VC." + Sys_VisibleControlTable.SUBCONTROLNAME_FLD + " FROM " + Sys_Role_ControlGroupTable.TABLE_NAME + " RCG" + " INNER JOIN " + Sys_ControlGroupTable.TABLE_NAME + " CG" + " ON RCG." + Sys_Role_ControlGroupTable.CONTROLGROUPID_FLD + "=" + " CG." + Sys_ControlGroupTable.CONTROLGROUPID_FLD + " INNER JOIN " + Sys_VisibleControlTable.TABLE_NAME + " VC" + " ON CG." + Sys_ControlGroupTable.CONTROLGROUPID_FLD + "=" + " VC." + Sys_ControlGroupTable.CONTROLGROUPID_FLD + " WHERE VC." + Sys_VisibleControlTable.FORMNAME_FLD + "='" + pstrFormName + "'" + " AND RCG." + Sys_Role_ControlGroupTable.ROLEID_FLD + " IN (" + strRoleIDs + ")"; if(pstrControlName != string.Empty) { strSql += " AND VC." + Sys_VisibleControlTable.CONTROLNAME_FLD + "='" + pstrControlName + "'"; } if(pstrSubControl != string.Empty) { strSql += " AND VC." + Sys_VisibleControlTable.SUBCONTROLNAME_FLD + "='" + pstrSubControl + "'"; } strSql += " GROUP BY " + Sys_VisibleControlTable.FORMNAME_FLD + "," + Sys_VisibleControlTable.CONTROLNAME_FLD + "," + Sys_VisibleControlTable.SUBCONTROLNAME_FLD; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,Sys_VisibleControlTable.TABLE_NAME); return dstPCS.Tables[0]; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
//using UnityEngine; using System; using System.Threading; public class SQLiteAsync { #region Public public SQLiteAsync() { } public delegate void OpenCallback(bool succeed, object state); public ThreadQueue.TaskControl Open(string filename, OpenCallback callback, object state) { return ThreadQueue.QueueUserWorkItem(new ThreadQueue.WorkCallback(OpenDatabase), new WaitCallback(OpenDatabaseComplete), new OpenState(filename,callback,state)); } public delegate void CloseCallback(object state); public ThreadQueue.TaskControl Close(CloseCallback callback, object state) { return ThreadQueue.QueueUserWorkItem(new ThreadQueue.WorkCallback(CloseDatabase), new WaitCallback(CloseDatabaseComplete), new CloseState(callback,state)); } public delegate void QueryCallback(SQLiteQuery qr, object state); public ThreadQueue.TaskControl Query(string query, QueryCallback callback, object state) { return ThreadQueue.QueueUserWorkItem(new ThreadQueue.WorkCallback(CreateQuery), new WaitCallback(CreateQueryComplete), new QueryState(query,callback,state)); } public delegate void StepCallback(SQLiteQuery qr, bool rv, object state); public ThreadQueue.TaskControl Step(SQLiteQuery qr, StepCallback callback, object state) { return ThreadQueue.QueueUserWorkItem(new ThreadQueue.WorkCallback(StepQuery), new WaitCallback(StepQueryComplete), new StepState(qr,callback,state)); } public delegate void ReleaseCallback(object state); public ThreadQueue.TaskControl Release(SQLiteQuery qr, ReleaseCallback callback, object state) { return ThreadQueue.QueueUserWorkItem(new ThreadQueue.WorkCallback(ReleaseQuery), new WaitCallback(ReleaseQueryComplete), new ReleaseState(qr,callback,state)); } #endregion #region Implementation // // members // SQLiteDB db = null; // // internal classes // class OpenState { string filename; OpenCallback callback; object state; bool succeed; public string Filename { get { return filename; } } public OpenCallback Callback { get { return callback; } } public object State { get { return state; } } public bool Succeed { get { return succeed; } set { succeed = value; } } public OpenState(string filename, OpenCallback callback, object state){ this.filename = filename; this.callback = callback; this.state = state; } } class CloseState { CloseCallback callback; object state; public CloseCallback Callback { get { return callback; } } public object State { get { return state; } } public CloseState(CloseCallback callback, object state){ this.callback = callback; this.state = state; } } class QueryState { string sql; QueryCallback callback; object state; SQLiteQuery query; public string Sql { get { return sql; } } public SQLiteQuery Query { get { return query; } set { query = value; } } public QueryCallback Callback { get { return callback; } } public object State { get { return state; } } public QueryState(string sql, QueryCallback callback, object state){ this.sql = sql; this.callback = callback; this.state = state; } } class StepState { SQLiteQuery query; StepCallback callback; object state; bool step; public SQLiteQuery Query { get { return query; } } public StepCallback Callback { get { return callback; } } public object State { get { return state; } } public bool Step { get { return step; } set { step = value; } } public StepState(SQLiteQuery query, StepCallback callback, object state){ this.query = query; this.callback = callback; this.state = state; } } class ReleaseState { SQLiteQuery query; ReleaseCallback callback; object state; public SQLiteQuery Query { get { return query; } } public ReleaseCallback Callback { get { return callback; } } public object State { get { return state; } } public ReleaseState(SQLiteQuery query, ReleaseCallback callback, object state){ this.query = query; this.callback = callback; this.state = state; } } // // functions // private void OpenDatabase(ThreadQueue.TaskControl control, object state) { OpenState opState = state as OpenState; try { db = new SQLiteDB(); db.Open(opState.Filename); opState.Succeed = true; } catch (Exception ex) { opState.Succeed = false; //Debug.LogError("SQLiteAsync : OpenDatabase : Exception : " + ex.Message); } } private void OpenDatabaseComplete(object state) { OpenState opState = state as OpenState; if( opState.Callback!=null ) opState.Callback(opState.Succeed, opState.State); } private void CloseDatabase(ThreadQueue.TaskControl control, object state) { try { if( db != null ) { db.Close(); db = null; } else { throw new Exception( "Database not ready!" ); } } catch (Exception ex) { //Debug.LogError("SQLiteAsync : Exception : " + ex.Message); } } private void CloseDatabaseComplete(object state) { CloseState clState = state as CloseState; if( clState.Callback!=null ) clState.Callback(clState.State); } private void CreateQuery(ThreadQueue.TaskControl control, object state) { try { if( db != null ) { QueryState qrState = state as QueryState; qrState.Query = new SQLiteQuery(db,qrState.Sql); } else { throw new Exception( "Database not ready!" ); }/**/ } catch (Exception ex) { //Debug.LogError("SQLiteAsync : CreateQuery : Exception : " + ex.Message); } } private void CreateQueryComplete(object state) { QueryState qrState = state as QueryState; qrState.Callback(qrState.Query, qrState.State); } private void StepQuery(ThreadQueue.TaskControl control, object state) { try { if( db != null ) { StepState stState = state as StepState; stState.Step = stState.Query.Step(); } else { throw new Exception( "Database not ready!" ); } } catch (Exception ex) { //Debug.LogError("SQLiteAsync : Exception : " + ex.Message); } } private void StepQueryComplete(object state) { StepState stState = state as StepState; stState.Callback(stState.Query,stState.Step,stState.State); } private void ReleaseQuery(ThreadQueue.TaskControl control, object state) { try { if( db != null ) { ReleaseState rlState = state as ReleaseState; rlState.Query.Release(); } else { throw new Exception( "Database not ready!" ); } } catch (Exception ex) { //Debug.LogError("SQLiteAsync : Exception : " + ex.Message); } } private void ReleaseQueryComplete(object state) { ReleaseState rlState = state as ReleaseState; rlState.Callback(rlState.State); } private void EmptyCallback(object obj) { // nothing to do here } #endregion }
//http://www.whydoidoit.com //Copyright (C) 2012 Mike Talbot // //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. //#define US_LOGGING using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; using System; using System.Linq; using System.Collections.Generic; using Serialization; using System.Reflection; using System.IO; using Object = UnityEngine.Object; using System.Net; /// <summary> /// Declares a class that serializes a derivation of Component /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ComponentSerializerFor : Attribute { public Type SerializesType; public ComponentSerializerFor(Type serializesType) { SerializesType = serializesType; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class SerializerPlugIn : Attribute { } [AttributeUsage(AttributeTargets.Class)] public class SuspendLevelSerialization : Attribute { } public interface IComponentSerializer { /// <summary> /// Serialize the specified component to a byte array /// </summary> /// <param name='component'> Component to be serialized </param> byte[] Serialize(Component component); /// <summary> /// Deserialize the specified data into the instance. /// </summary> /// <param name='data'> The data that represents the component, produced by Serialize </param> /// <param name='instance'> The instance to target </param> void Deserialize(byte[] data, Component instance); } public interface IControlSerialization { bool ShouldSave(); } public interface IControlSerializationEx : IControlSerialization { bool ShouldSaveWholeObject(); } /// <summary> /// Level serializer - this class is the main interaction point for /// saving and loading Unity objects and whole scenes. /// </summary> public static class LevelSerializer { #region Delegates /// <summary> /// Used when querying if an item should be stored. /// </summary> public delegate void StoreQuery(GameObject go, ref bool store); public delegate void StoreComponentQuery(Component component, ref bool store); #endregion #region SerializationModes enum /// <summary> /// Serialization modes. /// </summary> public enum SerializationModes { /// <summary> /// Serialize when suspended /// </summary> SerializeWhenFree, /// <summary> /// Ensure that there is serialization data /// when suspending /// </summary> CacheSerialization } #endregion private static Dictionary<string, GameObject> allPrefabs = new Dictionary<string, GameObject>(); /// <summary> /// The types which should be ignored for serialization /// </summary> public static HashSet<string> IgnoreTypes = new HashSet<string>(); internal static Dictionary<Type, IComponentSerializer> CustomSerializers = new Dictionary<Type, IComponentSerializer>(); internal static int lastFrame; /// <summary> /// The name of the player. /// </summary> public static string PlayerName = string.Empty; /// <summary> /// Whether resume information should be saved when saving the level /// </summary> public static bool SaveResumeInformation = true; private static int _suspensionCount; private static SaveEntry _cachedState; /// <summary> /// The serialization caching mode /// </summary> public static SerializationModes SerializationMode = SerializationModes.CacheSerialization; /// <summary> /// The max games that will be stored. /// </summary> public static int MaxGames = 20; /// <summary> /// The saved games. /// </summary> public static Lookup<string, List<SaveEntry>> SavedGames = new Index<string, List<SaveEntry>>(); //Stop cases private static readonly List<Type> _stopCases = new List<Type>(); /// <summary> /// Indicates whether the system is deserializing a level /// </summary> public static bool IsDeserializing; private static readonly List<object> createdPlugins = new List<object>(); /// <summary> /// Should the system use compression /// </summary> public static bool useCompression = false; static WebClient webClient = new WebClient(); #region Extended methods static void HandleWebClientUploadStringCompleted (object sender, UploadStringCompletedEventArgs e) { lock(Guard) { uploadCount--; } Loom.QueueOnMainThread(()=>{ if(e.UserState is Action<Exception>) (e.UserState as Action<Exception>)(e.Error); }); } static void HandleWebClientUploadDataCompleted (object sender, UploadDataCompletedEventArgs e) { lock(Guard) { uploadCount--; } Loom.QueueOnMainThread(()=>{ if(e.UserState is Action<Exception>) (e.UserState as Action<Exception>)(e.Error); }); } /// <summary> /// Saves a particular object tree to a file. The file will be /// saved beneath Application.persistentDataPath /// </summary> /// <param name='filename'> /// The filename to save the object tree into /// </param> /// <param name='rootOfTree'> /// The root of the tree /// </param> public static void SaveObjectTreeToFile(string filename, GameObject rootOfTree) { var data = SaveObjectTree(rootOfTree); data.WriteToFile(Application.persistentDataPath + "/" + filename); } /// <summary> /// Loads an object tree into the current scene from a file /// </summary> /// <param name='filename'> /// The file that should be loaded (from within Application.persistentDataPath) /// </param> /// <param name='onComplete'> /// A method call to make when loading is complete /// </param> public static void LoadObjectTreeFromFile(string filename, Action<LevelLoader> onComplete = null) { var x= File.Open(Application.persistentDataPath + "/" + filename, FileMode.Open); var data = new byte[x.Length]; x.Read(data, 0, (int)x.Length); x.Close(); LoadObjectTree(data, onComplete); } /// <summary> /// Serializes the level to a file /// </summary> /// <param name='filename'> /// The filename to use /// </param> /// <param name="usePersistentDataPath"> /// Is filename just a filename in Application.persistentDataPath or a whole path? /// </param> public static void SerializeLevelToFile(string filename, bool usePersistentDataPath = true) { var data = SerializeLevel(); if (usePersistentDataPath) { data.WriteToFile(Application.persistentDataPath + "/" + filename); } else { #if US_LOGGING Debug.LogFormat("Trying to write file to {0}", filename); #endif data.WriteToFile(filename); #if US_LOGGING Debug.LogErrorFormat("ERROR: {0} cannot be open for saving!", filename); #endif } } /// <summary> /// Loads a level from a file /// </summary> /// <param name='filename'> /// The filename to use /// </param> /// <param name="usePersistentDataPath"> /// Is filename just a filename in Application.persistentDataPath or a whole path? /// </param> public static void LoadSavedLevelFromFile(string filename, bool usePersistentDataPath = true) { StreamReader reader; string data = null; if (usePersistentDataPath) { reader = File.OpenText(Application.persistentDataPath + "/" + filename); data = reader.ReadToEnd(); reader.Close(); } else { #if US_LOGGING Debug.LogFormat("Trying to write file to {0}", filename); #endif reader = File.OpenText(filename); data = reader.ReadToEnd(); reader.Close(); #if US_LOGGING Debug.LogErrorFormat("ERROR: {0} cannot be open for loading!", filename); #endif } if (data != null) { LoadSavedLevel(data); } else { Debug.LogErrorFormat("No data was loaded from {0}", filename); } } static readonly object Guard = new object(); /// <summary> /// Saves an object tree to a server using POST or STOR /// </summary> /// <param name='uri'> /// The url to save the tree to e.g. ftp://whydoidoit.net/Downloads/someFile.txt /// </param> /// <param name='rootOfTree'> /// The object to be saved /// </param> /// <param name='userName'> /// The user name (if required) /// </param> /// <param name='password'> /// The password (if required) /// </param> /// <param name='onComplete'> /// A function to call when the upload is complete /// </param> public static void SaveObjectTreeToServer(string uri, GameObject rootOfTree, string userName = "", string password = "", Action<Exception> onComplete =null) { onComplete = onComplete ?? delegate {}; Action execute = ()=>{ var data = SaveObjectTree(rootOfTree); Action doIt = ()=> { uploadCount++; webClient.Credentials = new NetworkCredential(userName, password); webClient.UploadDataAsync(new Uri(uri), null, data, onComplete); }; DoWhenReady(doIt); }; execute(); } static void DoWhenReady(Action upload) { lock(Guard) { if(uploadCount > 0) { Loom.QueueOnMainThread(()=>DoWhenReady(upload), 0.4f); } else { upload(); } } } /// <summary> /// Loads an object tree from a server /// </summary> /// <param name='uri'> /// The url to load the object tree from /// </param> /// <param name='onComplete'> /// A method to call when the load is complete /// </param> public static void LoadObjectTreeFromServer(string uri, Action<LevelLoader> onComplete = null) { onComplete = onComplete ?? delegate {}; RadicalRoutineHelper.Current.StartCoroutine(DownloadFromServer(uri, onComplete)); } static int uploadCount; /// <summary> /// Serializes the level to a server. /// </summary> /// <param name='uri'> /// The url of the location for the stored data. ftp://whydoidoit.net/Downloads/someFile.dat /// </param> /// <param name='userName'> /// User name if required /// </param> /// <param name='password'> /// Password if required /// </param> /// <param name='onComplete'> /// A method to call when the serialization is complete /// </param> public static void SerializeLevelToServer(string uri, string userName = "", string password = "", Action<Exception> onComplete = null) { lock(Guard) { if(uploadCount > 0) { Loom.QueueOnMainThread(()=>SerializeLevelToServer(uri, userName, password, onComplete), 0.5f); return; } uploadCount++; onComplete = onComplete ?? delegate {}; var data = SerializeLevel(); webClient.Credentials = new NetworkCredential(userName, password); webClient.UploadStringAsync(new Uri(uri), null, data, onComplete); } } /// <summary> /// Loads the saved level from a server url. /// </summary> /// <param name='uri'> /// The url of the server to load the data from /// </param> public static void LoadSavedLevelFromServer(string uri) { RadicalRoutineHelper.Current.StartCoroutine(DownloadLevelFromServer(uri)); } static IEnumerator DownloadFromServer(string uri, Action<LevelLoader> onComplete) { var www = new WWW(uri); yield return www; LoadObjectTree(www.bytes, onComplete); } static IEnumerator DownloadLevelFromServer(string uri) { var www = new WWW(uri); yield return www; LoadSavedLevel(www.text); } #endregion static LevelSerializer() { webClient.UploadDataCompleted += HandleWebClientUploadDataCompleted; webClient.UploadStringCompleted += HandleWebClientUploadStringCompleted; //Basic plug in configuration and special cases _stopCases.Add(typeof (PrefabIdentifier)); UnitySerializer.AddPrivateType(typeof (AnimationClip)); //Other initialization foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { UnitySerializer.ScanAllTypesForAttribute( (tp, attr) => createdPlugins.Add(Activator.CreateInstance(tp)), asm, typeof (SerializerPlugIn)); UnitySerializer.ScanAllTypesForAttribute( (tp, attr) => { CustomSerializers[((ComponentSerializerFor) attr).SerializesType] = Activator.CreateInstance(tp) as IComponentSerializer; }, asm, typeof (ComponentSerializerFor)); } AllPrefabs = Resources.FindObjectsOfTypeAll(typeof (GameObject)).Cast<GameObject>() .Where(go => { var pf = go.GetComponent<PrefabIdentifier>(); return pf != null && !pf.IsInScene(); }) .Distinct(CompareGameObjects.Instance) .ToDictionary(go => go.GetComponent<PrefabIdentifier>().ClassId, go => go); try { var stored = FilePrefs.GetString("_Save_Game_Data_"); if (!string.IsNullOrEmpty(stored)) { try { SavedGames = UnitySerializer.Deserialize<Lookup<string, List<SaveEntry>>>(Convert.FromBase64String(stored)); } catch { SavedGames = null; } } if (SavedGames == null) { SavedGames = new Index<string, List<SaveEntry>>(); SaveDataToFilePrefs(); } } catch { SavedGames = new Index<string, List<SaveEntry>>(); } } internal static Dictionary<string, GameObject> AllPrefabs { get { if (Time.frameCount != lastFrame) { allPrefabs = allPrefabs.Where(p => p.Value).ToDictionary(p => p.Key, p => p.Value); lastFrame = Time.frameCount; } return allPrefabs; } set { allPrefabs = value; } } /// <summary> /// Gets a value indicating whether this instance can resume (there is resume data) /// </summary> /// <value> /// <c>true</c> if this instance can resume; otherwise, <c>false</c>. /// </value> public static bool CanResume { get { return !string.IsNullOrEmpty(FilePrefs.GetString(PlayerName + "__RESUME__")); } } /// <summary> /// Gets a value indicating whether this instance is suspended. /// </summary> /// <value> <c>true</c> if this instance is suspended; otherwise, <c>false</c> . </value> public static bool IsSuspended { get { return _suspensionCount > 0; } } /// <summary> /// Gets the serialization suspension count. /// </summary> /// <value> The suspension count. </value> public static int SuspensionCount { get { return _suspensionCount; } } /// <summary> /// Occurs when the level was deserialized /// </summary> public static event Action Deserialized = delegate { }; /// <summary> /// Occurs when the level was serialized. /// </summary> public static event Action GameSaved = delegate { }; /// <summary> /// Occurs when suspending serialization. /// </summary> public static event Action SuspendingSerialization = delegate { }; /// <summary> /// Occurs when resuming serialization. /// </summary> public static event Action ResumingSerialization = delegate { }; internal static void InvokeDeserialized() { _suspensionCount = 0; if (Deserialized != null) { Deserialized(); } foreach (var go in Object.FindObjectsOfType(typeof (GameObject)).Cast<GameObject>()) { go.SendMessage("OnDeserialized", null, SendMessageOptions.DontRequireReceiver); } } /// <summary> /// Raised to check whehter a particular item should be stored /// </summary> public static event StoreQuery Store; public static event StoreComponentQuery StoreComponent = delegate {}; /// <summary> /// Resume for a stored game state that wasn't directly saved /// </summary> public static void Resume() { var data = FilePrefs.GetString(PlayerName + "__RESUME__"); if (!string.IsNullOrEmpty(data)) { var se = UnitySerializer.Deserialize<SaveEntry>(Convert.FromBase64String(data)); se.Load(); } } /// <summary> /// Create a resumption checkpoint /// </summary> public static void Checkpoint() { SaveGame("Resume", false, PerformSaveCheckPoint); } private static void PerformSaveCheckPoint(string name, bool urgent) { var newGame = CreateSaveEntry(name, urgent); FilePrefs.SetString(PlayerName + "__RESUME__", Convert.ToBase64String(UnitySerializer.Serialize(newGame))); FilePrefs.Save(); } public static void ClearCheckpoint() { ClearCheckpoint(true); } public static void ClearCheckpoint(bool store) { FilePrefs.DeleteKey(PlayerName + "__RESUME__"); if (store) { FilePrefs.Save(); } } /// <summary> /// Suspends the serialization. Must resume as many times as you suspend /// </summary> public static void SuspendSerialization() { if (_suspensionCount == 0) { SuspendingSerialization(); if (SerializationMode == SerializationModes.CacheSerialization) { _cachedState = CreateSaveEntry("resume", true); if (SaveResumeInformation) { FilePrefs.SetString(PlayerName + "__RESUME__", Convert.ToBase64String(UnitySerializer.Serialize(_cachedState))); FilePrefs.Save(); } } } _suspensionCount++; } /// <summary> /// Resumes the serialization. Must be balanced with calls to SuspendSerialization /// </summary> public static void ResumeSerialization() { _suspensionCount--; if (_suspensionCount == 0) { ResumingSerialization(); } } /// <summary> /// Ignores the type of component when saving games. /// </summary> /// <param name='typename'> Typename of the component to ignore </param> public static void IgnoreType(string typename) { IgnoreTypes.Add(typename); } /// <summary> /// Remove a type from the ignore list /// </summary> /// <param name='typename'> /// Typename to remove /// </param> public static void UnIgnoreType(string typename) { IgnoreTypes.Remove(typename); } /// <summary> /// Ignores the type of component when saving games. /// </summary> /// <param name='tp'> The type of the component to ignore </param> public static void IgnoreType(Type tp) { if (tp.FullName != null) { IgnoreTypes.Add(tp.FullName); } } /// <summary> /// Creates a saved game for the current position /// </summary> /// <returns> The new save entry. </returns> /// <param name='name'> A name for the save entry </param> /// <param name='urgent'> An urgent save will store the current state, even if suspended. In this case it is likely that clean up will be necessary by handing Deserialized messages or responding to the LevelSerializer.Deserialized event </param> public static SaveEntry CreateSaveEntry(string name, bool urgent) { return new SaveEntry() { Name = name, When = DateTime.Now, Level = SceneManager.GetActiveScene().name, Data = SerializeLevel(urgent) }; } /// <summary> /// Saves the game. /// </summary> /// <param name='name'> The name to use for the game </param> public static void SaveGame(string name) { SaveGame(name, false, null); } public static void SaveGame(string name, bool urgent, Action<string, bool> perform) { perform = perform ?? PerformSave; //See if we need to serialize later if (!urgent && (IsSuspended && SerializationMode == SerializationModes.SerializeWhenFree)) { //Are we already waiting for serialization to occur if (GameObject.Find("/SerializationHelper") != null) { return; } //Create a helper var go = new GameObject("SerializationHelper"); var helper = go.AddComponent(typeof (SerializationHelper)) as SerializationHelper; helper.gameName = name; helper.perform = perform; return; } perform(name, urgent); } private static void PerformSave(string name, bool urgent) { var newGame = CreateSaveEntry(name, urgent); SavedGames[PlayerName].Insert(0, newGame); while (SavedGames[PlayerName].Count > MaxGames) { SavedGames[PlayerName].RemoveAt(SavedGames.Count - 1); } SaveDataToFilePrefs(); FilePrefs.SetString(PlayerName + "__RESUME__", Convert.ToBase64String(UnitySerializer.Serialize(newGame))); FilePrefs.Save(); GameSaved(); } /// <summary> /// Saves the stored game data to player prefs. /// </summary> public static void SaveDataToFilePrefs() { FilePrefs.SetString("_Save_Game_Data_", Convert.ToBase64String(UnitySerializer.Serialize(SavedGames))); FilePrefs.Save(); } /// <summary> /// Registers the calling assembly as one providing serialization extensions. /// </summary> public static void RegisterAssembly() { UnitySerializer.ScanAllTypesForAttribute( (tp, attr) => { CustomSerializers[((ComponentSerializerFor) attr).SerializesType] = Activator.CreateInstance(tp) as IComponentSerializer; }, Assembly.GetCallingAssembly(), typeof (ComponentSerializerFor)); } /// <summary> /// Adds the prefab path. /// </summary> /// <param name='path'> A resource path that contains prefabs to be created for the game </param> public static void AddPrefabPath(string path) { foreach (var pair in Resources.LoadAll(path, typeof (GameObject)) .Cast<GameObject>() .Where(go => go.GetComponent<UniqueIdentifier>() != null) .ToDictionary(go => go.GetComponent<UniqueIdentifier>().ClassId, go => go).Where( pair => !AllPrefabs.ContainsKey(pair.Key))) { AllPrefabs.Add(pair.Key, pair.Value); } } /// <summary> /// Dont garbage collect during deserialization /// </summary> public static void DontCollect() { _collectionCount++; } /// <summary> /// Enable garbage collection during deserialization /// </summary> public static void Collect() { _collectionCount--; } static int _collectionCount = 0; /// <summary> /// Gets a value indicating whether this <see cref="LevelSerializer"/> should garbage collect. /// </summary> /// <value> /// <c>true</c> if should collect; otherwise, <c>false</c>. /// </value> public static bool ShouldCollect { get { return _collectionCount <= 0; } } /// <summary> /// Serializes the level to a string /// </summary> /// <returns> The level data as a string </returns> /// <exception>Is thrown when the serization was suspended /// <cref>SerizationSuspendedException</cref> /// </exception> public static string SerializeLevel() { return SerializeLevel(false); } /// <summary> /// Serializes the level. /// </summary> /// <returns> The level stored as a string. </returns> /// <param name='urgent'> Whether to ignore an suspension of serialization </param> /// <exception cref='SerializationSuspendedException'>Is thrown when the serialization was suspended and urgent was not specified</exception> public static string SerializeLevel(bool urgent) { //using(new Timing("Save Level")) { if (IsSuspended && !urgent) { if (SerializationMode == SerializationModes.CacheSerialization) { return _cachedState.Data; } else { throw new SerializationSuspendedException(); } } //Try to get as much memory as possible Resources.UnloadUnusedAssets(); if(ShouldCollect) GC.Collect(); var data = SerializeLevel(false, null); //Free up memory that has been used during serialization if(ShouldCollect) GC.Collect(); if (useCompression) { return CompressionHelper.Compress(data); } else { return "NOCOMPRESSION" + Convert.ToBase64String(data); } } } internal static void RaiseProgress(string section, float complete) { Progress(section, complete); } internal static bool HasParent(UniqueIdentifier i, string id) { var scan = UniqueIdentifier.GetByName(i.Id).transform; while (scan != null) { UniqueIdentifier ui; if ((ui = scan.GetComponent<UniqueIdentifier>()) != null) { if (id == ui.Id) { return true; } } scan = scan.parent; } return false; } private static void GetComponentsInChildrenWithClause(Transform t, List<StoreInformation> components) { foreach (var c in t.Cast<Transform>()) { var s = c.GetComponent<StoreInformation>(); if (s != null) { if (!(s is PrefabIdentifier)) { components.Add(s); GetComponentsInChildrenWithClause(c, components); } } else { GetComponentsInChildrenWithClause(c, components); } } } /// <summary> /// Internal function /// </summary> public static List<StoreInformation> GetComponentsInChildrenWithClause(GameObject go) { var components = new List<StoreInformation>(); GetComponentsInChildrenWithClause(go.transform, components); return components; } /// <summary> /// Occurs when progress occurs during the deserialization/serialization process /// </summary> public static event Action<string, float> Progress = delegate { }; /// <summary> /// Save an objects tree so it can be reloaded later /// </summary> /// <param name="rootOfTree">The object at the root of the tree</param> /// <returns></returns> public static byte[] SaveObjectTree(this GameObject rootOfTree) { if (!rootOfTree.GetComponent<UniqueIdentifier>()) { EmptyObjectIdentifier.FlagAll(rootOfTree); } return SerializeLevel(false, rootOfTree.GetComponent<UniqueIdentifier>().Id); } /// <summary> /// Occurs before any loading is done. /// </summary> public static event Action BeginLoad = delegate { }; /// <summary> /// Serializes the level to a byte array, with an optional root item. The root item /// and its children, if specified, will be the only things saved /// </summary> /// <returns> The level data as a byte array </returns> /// <param name='urgent'> Whether to save even if serialization is suspended </param> /// <param name='id'> Identifier (or null) of an object to be the root of the data serialization </param> public static byte[] SerializeLevel(bool urgent, string id) { LevelData ld; using (new Radical.Logging()) { //First we need to know the name of the last level loaded using (new UnitySerializer.SerializationScope()) { ld = new LevelData() { //The level to reload Name = SceneManager.GetActiveScene().name, rootObject = string.IsNullOrEmpty(id) ? null : id }; //All of the currently active uniquely identified objects ld.StoredObjectNames = UniqueIdentifier .AllIdentifiers .Where(i => string.IsNullOrEmpty(id) || i.Id == id || HasParent(i, id)) .Select(i => i.gameObject) .Where(go => go != null) .Where(go => { var shouldSerialize = go.FindInterface<IControlSerializationEx>(); return shouldSerialize == null || shouldSerialize.ShouldSaveWholeObject(); }) .Where(go => { if (Store == null) { return true; } var result = true; Store(go, ref result); return result; }) .Select(n => { try { var si = new StoredItem() { createEmptyObject = n.GetComponent<EmptyObjectIdentifier>() != null, layer = n.layer, tag = n.tag, setExtraData = true, Active = n.activeSelf, Components = n.GetComponents<Component>().Where(c=>c!=null).Select( c => c.GetType().FullName).Distinct() .ToDictionary(v => v, v => true), Name = n.GetComponent<UniqueIdentifier>().Id, GameObjectName = n.name, ParentName = (n.transform.parent == null || n.transform.parent.GetComponent<UniqueIdentifier>() == null) ? null : (n.transform.parent.GetComponent<UniqueIdentifier>(). Id), ClassId = n.GetComponent<PrefabIdentifier>() != null ? n.GetComponent<PrefabIdentifier>().ClassId : string.Empty }; if (n.GetComponent<StoreInformation>()) { n.SendMessage("OnSerializing", SendMessageOptions.DontRequireReceiver); } var pf = n.GetComponent<PrefabIdentifier>(); if (pf != null) { var components = GetComponentsInChildrenWithClause(n); si.Children = components.GroupBy(c => c.ClassId).ToDictionary(c => c.Key, c => c.Select( i => i.Id) .ToList()); } return si; } catch (Exception e) { Debug.LogWarning("Failed to serialize status of " + n.name + " with error " + e.ToString()); return null; } }) .Where(si => si != null) .ToList(); //All of the data for the items to be stored var toBeProcessed = UniqueIdentifier .AllIdentifiers .Where(o => o.GetComponent<StoreInformation>() != null || o.GetComponent<PrefabIdentifier>() != null) .Where(i => string.IsNullOrEmpty(id) || i.Id == id || HasParent(i, id)) .Where(i => i != null) .Select(i => i.gameObject) .Where(i => i != null) .Where(go => { var shouldSerialize = go.FindInterface<IControlSerializationEx>(); return shouldSerialize == null || shouldSerialize.ShouldSaveWholeObject(); }) .Distinct() .Where(go => { if (Store == null) { return true; } var result = true; Store(go, ref result); return result; }) .SelectMany(o => o.GetComponents<Component>()) .Where(c => { if (c == null) { return false; } var tp = c.GetType(); var store = true; StoreComponent(c, ref store); return store && (!(c is IControlSerialization) || (c as IControlSerialization).ShouldSave()) && !tp.IsDefined(typeof (DontStoreAttribute), true) && !IgnoreTypes.Contains(tp.FullName); }) .Select(c => new { Identifier = (StoreInformation) c.gameObject.GetComponent(typeof (StoreInformation)), Component = c }) .Where(cp => (cp.Identifier.StoreAllComponents || cp.Identifier.Components.Contains(cp.Component.GetType().FullName))) .OrderBy(cp => cp.Identifier.Id) .ThenBy(cp => cp.Component.GetType().FullName).ToList(); var processed = 0; ld.StoredItems = toBeProcessed .Select(cp => { try { if (Radical.IsLogging()) { Radical.Log("<{0} : {1} - {2}>", cp.Component.gameObject.GetFullName(), cp.Component.GetType().Name, cp.Component.GetComponent<UniqueIdentifier>().Id); Radical.IndentLog(); } var sd = new StoredData() { Type = cp.Component.GetType().FullName, ClassId = cp.Identifier.ClassId, Name = cp.Component.GetComponent<UniqueIdentifier>().Id }; if (CustomSerializers.ContainsKey(cp.Component.GetType())) { sd.Data = CustomSerializers[cp.Component.GetType()].Serialize(cp.Component); } else { sd.Data = UnitySerializer.SerializeForDeserializeInto(cp.Component); } if (Radical.IsLogging()) { Radical.OutdentLog(); Radical.Log("</{0} : {1}>", cp.Component.gameObject.GetFullName(), cp.Component.GetType().Name); } processed++; Progress("Storing", (float) processed/(float) toBeProcessed.Count); return sd; } catch (Exception e) { processed++; Debug.LogWarning("Failed to serialize data (" + cp.Component.GetType().AssemblyQualifiedName + ") of " + cp.Component.name + " with error " + e.ToString()); return null; } }) .Where(s => s != null) .ToList(); } } var data = UnitySerializer.Serialize(ld); return data; } /// <summary> /// Reload an object tree /// </summary> /// <param name="data">The data for the tree to be loaded</param> /// <param name="onComplete">A function to call when the load is complete</param> public static void LoadObjectTree(this byte[] data, Action<LevelLoader> onComplete = null) { onComplete = onComplete ?? delegate { }; LoadNow(data, true, false, onComplete); } public static void LoadNow(object data) { LoadNow(data, false, true, null); } public static void LoadNow(object data, bool dontDeleteExistingItems) { LoadNow(data, dontDeleteExistingItems, true, null); } public static void LoadNow(object data, bool dontDeleteExistingItems, bool showLoadingGUI) { LoadNow(data, dontDeleteExistingItems, showLoadingGUI, null); } public static void LoadNow(object data, bool dontDeleteExistingItems, bool showLoadingGUI, Action<LevelLoader> complete) { if(BeginLoad != null) { BeginLoad(); } byte[] levelData = null; if(data is byte[]) { levelData = (byte[])data; } if(data is string) { var str = (string)data; if (str.StartsWith("NOCOMPRESSION")) { levelData = Convert.FromBase64String(str.Substring(13)); } else { levelData = CompressionHelper.Decompress(str); } } if(levelData == null) { throw new ArgumentException("data parameter must be either a byte[] or a base64 encoded string"); } //Create a level loader var l = new GameObject(); var loader = l.AddComponent<LevelLoader>(); loader.showGUI = showLoadingGUI; var ld = UnitySerializer.Deserialize<LevelSerializer.LevelData> (levelData); loader.Data = ld; loader.DontDelete = dontDeleteExistingItems; //Get the loader to do its job loader.StartCoroutine(PerformLoad(loader, complete)); } static IEnumerator PerformLoad(LevelLoader loader, Action<LevelLoader> complete) { yield return loader.StartCoroutine(loader.Load(0,Time.timeScale)); if(complete != null) complete(loader); } /// <summary> /// Loads the saved level. /// </summary> /// <param name='data'> The data describing the level to load </param> public static LevelLoader LoadSavedLevel(string data) { if(BeginLoad != null) { BeginLoad(); } LevelData ld; IsDeserializing = true; if (data.StartsWith("NOCOMPRESSION")) { ld = UnitySerializer.Deserialize<LevelData>(Convert.FromBase64String(data.Substring(13))); } else { ld = UnitySerializer.Deserialize<LevelData>(CompressionHelper.Decompress(data)); } SaveGameManager.Loaded(); var go = new GameObject(); Object.DontDestroyOnLoad(go); var loader = go.AddComponent<LevelLoader>(); loader.Data = ld; SceneManager.LoadScene(ld.Name); return loader; } #region Nested type: CompareGameObjects private class CompareGameObjects : IEqualityComparer<GameObject> { #region IEqualityComparer[GameObject] implementation public bool Equals(GameObject x, GameObject y) { return System.String.Compare(x.GetComponent<PrefabIdentifier>().ClassId, y.GetComponent<PrefabIdentifier>().ClassId, System.StringComparison.Ordinal) == 0; } public int GetHashCode(GameObject obj) { return obj.GetComponent<PrefabIdentifier>().ClassId.GetHashCode(); } #endregion public static readonly CompareGameObjects Instance = new CompareGameObjects(); } #endregion #region Nested type: LevelData /// <summary> /// The data stored for a level /// </summary> public class LevelData { /// <summary> /// The name of the level that was saved /// </summary> public string Name; /// <summary> /// All of the items that were saved /// </summary> public List<StoredData> StoredItems; /// <summary> /// All of the names of items saved /// </summary> public List<StoredItem> StoredObjectNames; public string rootObject; } #endregion #region Nested type: ProgressHelper private class ProgressHelper { #region ICodeProgress implementation public void SetProgress(long inSize, long outSize) { RaiseProgress("Compression", 05f); } #endregion } #endregion #region Nested type: SaveEntry /// <summary> /// A saved game entry /// </summary> public class SaveEntry { /// <summary> /// The data about the saved game /// </summary> public string Data; /// <summary> /// The name of the unity scene /// </summary> public string Level; /// <summary> /// The name provided for the saved game. /// </summary> public string Name; /// <summary> /// The time that the game was saved /// </summary> public DateTime When; /// <summary> /// Initializes a new instance of the <see cref="LevelSerializer.SaveEntry" /> class. /// </summary> /// <param name='contents'> The string representing the data of the saved game (use .ToString()) </param> public SaveEntry(string contents) { UnitySerializer.DeserializeInto(Convert.FromBase64String(contents), this); } public SaveEntry() { } /// <summary> /// Gets the caption. /// </summary> /// <value> The caption which is a combination of the name, the level and the time that the game was saved </value> public string Caption { get { return string.Format("{0} - {1} - {2:g}", Name, Level, When); } } /// <summary> /// Load this saved game /// </summary> public void Load() { LoadSavedLevel(Data); } /// <summary> /// Delete this saved game /// </summary> public void Delete() { var owner = SavedGames.FirstOrDefault(p => p.Value.Contains(this)); if (owner.Value != null) { owner.Value.Remove(this); SaveDataToFilePrefs(); } } /// <summary> /// Returns a <see cref="System.String" /> that represents the current <see cref="LevelSerializer.SaveEntry" />. /// </summary> /// <returns> A <see cref="System.String" /> that represents the current <see cref="LevelSerializer.SaveEntry" /> . </returns> public override string ToString() { return Convert.ToBase64String(UnitySerializer.Serialize(this)); } } #endregion #region Nested type: SerializationHelper /// <summary> /// Checks for the ability to serialize /// </summary> public class SerializationHelper : MonoBehaviour { public string gameName; public Action<string, bool> perform; private void Update() { //Check to see if we are still suspended if (IsSuspended == false) { if (perform != null) { perform(gameName, false); } DestroyImmediate(gameObject); } } } #endregion #region Nested type: SerializationSuspendedException public class SerializationSuspendedException : Exception { public SerializationSuspendedException() : base("Serialization was suspended: " + _suspensionCount + " times") { } } #endregion #region Nested type: StoredData public class StoredData { public string ClassId; public byte[] Data; public string Name; public string Type; } #endregion #region Nested type: StoredItem public class StoredItem { public bool Active; public int layer; public string tag; public bool setExtraData; public readonly List<string> ChildIds = new List<string>(); public Dictionary<string, List<string>> Children = new Dictionary<string, List<string>>(); public string ClassId; public Dictionary<string, bool> Components; [DoNotSerialize] public GameObject GameObject; public string GameObjectName; public string Name; public string ParentName; public bool createEmptyObject; public override string ToString() { return string.Format("{0} child of {2} - ({1})", Name, ClassId, ParentName); } } #endregion } [ComponentSerializerFor(typeof (Animation))] public class SerializeAnimations : IComponentSerializer { #region Nested type: StoredState public class StoredState { public byte[] data; public string name; public SaveGameManager.AssetReference asset; } #endregion #region IComponentSerializer implementation public byte[] Serialize(Component component) { return UnitySerializer.Serialize( ((Animation) component).Cast<AnimationState>().Select( a => new StoredState() {data = UnitySerializer.SerializeForDeserializeInto(a), name = a.name, asset = SaveGameManager.Instance.GetAssetId(a.clip)}). ToList()); } public void Deserialize(byte[] data, Component instance) { UnitySerializer.AddFinalAction(()=>{ var animation = (Animation) instance; animation.Stop(); var current = animation.Cast<AnimationState>().ToDictionary(a=>a.name); var list = UnitySerializer.Deserialize<List<StoredState>>(data); foreach (var entry in list) { if(entry.asset != null && !current.ContainsKey(entry.name)) { animation.AddClip(SaveGameManager.Instance.GetAsset(entry.asset) as AnimationClip, entry.name); } if (entry.name.Contains(" - Queued Clone")) { var newState = animation.PlayQueued(entry.name.Replace(" - Queued Clone", "")); UnitySerializer.DeserializeInto(entry.data, newState); } else { UnitySerializer.DeserializeInto(entry.data, animation[entry.name]); } } }); } #endregion } public static class FieldSerializer { public static void SerializeFields(Dictionary<string, object> storage, object obj, params string[] names) { var tp = obj.GetType(); foreach (var name in names) { var fld = tp.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField); if (fld != null) { storage[name] = fld.GetValue(obj); } } } public static void DeserializeFields(Dictionary<string, object> storage, object obj) { var tp = obj.GetType(); foreach (var p in storage) { var fld = tp.GetField(p.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField); if (fld != null) { fld.SetValue(obj, p.Value); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Security; using System.Security.Cryptography; using System.Net.Security; using System.Security.Principal; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace System.Net { internal static partial class CertificateValidationPal { private static readonly object s_syncObject = new object(); private static volatile X509Store s_myCertStoreEx; private static volatile X509Store s_myMachineCertStoreEx; internal static SslPolicyErrors VerifyCertificateProperties( X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string hostName) { SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; if (!chain.Build(remoteCertificate) // Build failed on handle or on policy. && chain.SafeHandle.DangerousGetHandle() == IntPtr.Zero) // Build failed to generate a valid handle. { throw new CryptographicException(Marshal.GetLastWin32Error()); } if (checkCertName) { unsafe { uint status = 0; var eppStruct = new Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA() { cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA>(), dwAuthType = isServer ? Interop.Crypt32.AuthType.AUTHTYPE_SERVER : Interop.Crypt32.AuthType.AUTHTYPE_CLIENT, fdwChecks = 0, pwszServerName = null }; var cppStruct = new Interop.Crypt32.CERT_CHAIN_POLICY_PARA() { cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CHAIN_POLICY_PARA>(), dwFlags = 0, pvExtraPolicyPara = &eppStruct }; fixed (char* namePtr = hostName) { eppStruct.pwszServerName = namePtr; cppStruct.dwFlags |= (Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL & ~Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG); SafeX509ChainHandle chainContext = chain.SafeHandle; status = Verify(chainContext, ref cppStruct); if (status == Interop.Crypt32.CertChainPolicyErrors.CERT_E_CN_NO_MATCH) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; } } } } X509ChainStatus[] chainStatusArray = chain.ChainStatus; if (chainStatusArray != null && chainStatusArray.Length != 0) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } return sslPolicyErrors; } // // Extracts a remote certificate upon request. // internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateCollection) { remoteCertificateCollection = null; if (securityContext == null) { return null; } GlobalLog.Enter("CertificateValidationPal.Windows SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()"); X509Certificate2 result = null; SafeFreeCertContext remoteContext = null; try { remoteContext = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.RemoteCertificate) as SafeFreeCertContext; if (remoteContext != null && !remoteContext.IsInvalid) { result = new X509Certificate2(remoteContext.DangerousGetHandle()); } } finally { if (remoteContext != null && !remoteContext.IsInvalid) { remoteCertificateCollection = UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(remoteContext); remoteContext.Dispose(); } } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.RemoteCertificate(result == null ? "null" : result.ToString(true)); } GlobalLog.Leave("CertificateValidationPal.Windows SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()", (result == null ? "null" : result.Subject)); return result; } // // Used only by client SSL code, never returns null. // internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext) { Interop.SspiCli.IssuerListInfoEx issuerList = (Interop.SspiCli.IssuerListInfoEx)SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.IssuerListInfoEx); string[] issuers = Array.Empty<string>(); try { if (issuerList.cIssuers > 0) { unsafe { uint count = issuerList.cIssuers; issuers = new string[issuerList.cIssuers]; Interop.SspiCli._CERT_CHAIN_ELEMENT* pIL = (Interop.SspiCli._CERT_CHAIN_ELEMENT*)issuerList.aIssuers.DangerousGetHandle(); for (int i = 0; i < count; ++i) { Interop.SspiCli._CERT_CHAIN_ELEMENT* pIL2 = pIL + i; if (GlobalLog.IsEnabled && pIL2->cbSize <= 0) { GlobalLog.Assert("SecureChannel::GetIssuers()", "Interop.SspiCli._CERT_CHAIN_ELEMENT size is not positive: " + pIL2->cbSize.ToString()); } if (pIL2->cbSize > 0) { uint size = pIL2->cbSize; byte* ptr = (byte*)(pIL2->pCertContext); byte[] x = new byte[size]; for (int j = 0; j < size; j++) { x[j] = *(ptr + j); } X500DistinguishedName x500DistinguishedName = new X500DistinguishedName(x); issuers[i] = x500DistinguishedName.Name; GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetIssuers() IssuerListEx[" + i + "]:" + issuers[i]); } } } } } finally { if (issuerList.aIssuers != null) { issuerList.aIssuers.Dispose(); } } return issuers; } // // Security: We temporarily reset thread token to open the cert store under process account. // internal static X509Store EnsureStoreOpened(bool isMachineStore) { X509Store store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; // TODO #3862 Investigate if this can be switched to either the static or Lazy<T> patterns. if (Volatile.Read(ref store) == null) { lock (s_syncObject) { store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; if (Volatile.Read(ref store) == null) { // NOTE: that if this call fails we won't keep track and the next time we enter we will try to open the store again. StoreLocation storeLocation = isMachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; store = new X509Store(StoreName.My, storeLocation); try { // For app-compat We want to ensure the store is opened under the **process** account. try { WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () => { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); GlobalLog.Print("SecureChannel::EnsureStoreOpened() storeLocation:" + storeLocation + " returned store:" + store.GetHashCode().ToString("x")); }); } catch { throw; } if (isMachineStore) { s_myMachineCertStoreEx = store; } else { s_myCertStoreEx = store; } return store; } catch (Exception exception) { if (exception is CryptographicException || exception is SecurityException) { GlobalLog.Assert("SecureChannel::EnsureStoreOpened()", "Failed to open cert store, location:" + storeLocation + " exception:" + exception); return null; } if (NetEventSource.Log.IsEnabled()) { NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_open_store_failed, storeLocation, exception)); } throw; } } } } return store; } private static uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp) { GlobalLog.Enter("SecureChannel::VerifyChainPolicy", "chainContext=" + chainContext + ", options=" + String.Format("0x{0:x}", cpp.dwFlags)); var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS(); status.cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CHAIN_POLICY_STATUS>(); bool errorCode = Interop.Crypt32.CertVerifyCertificateChainPolicy( (IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL, chainContext, ref cpp, ref status); GlobalLog.Print("SecureChannel::VerifyChainPolicy() CertVerifyCertificateChainPolicy returned: " + errorCode); #if TRACE_VERBOSE GlobalLog.Print("SecureChannel::VerifyChainPolicy() error code: " + status.dwError + String.Format(" [0x{0:x8}", status.dwError) + " " + Interop.MapSecurityStatus(status.dwError) + "]"); #endif GlobalLog.Leave("SecureChannel::VerifyChainPolicy", status.dwError.ToString()); return status.dwError; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; namespace System.Net { /// <summary> /// <para>Acts as countdown timer, used to measure elapsed time over a sync operation.</para> /// </summary> internal static class TimerThread { /// <summary> /// <para>Represents a queue of timers, which all have the same duration.</para> /// </summary> internal abstract class Queue { private readonly int _durationMilliseconds; internal Queue(int durationMilliseconds) { _durationMilliseconds = durationMilliseconds; } /// <summary> /// <para>The duration in milliseconds of timers in this queue.</para> /// </summary> internal int Duration { get { return _durationMilliseconds; } } /// <summary> /// <para>Creates and returns a handle to a new polled timer.</para> /// </summary> internal Timer CreateTimer() { return CreateTimer(null, null); } /// <summary> /// <para>Creates and returns a handle to a new timer with attached context.</para> /// </summary> internal abstract Timer CreateTimer(Callback callback, object context); } /// <summary> /// <para>Represents a timer and provides a mechanism to cancel.</para> /// </summary> internal abstract class Timer : IDisposable { private readonly int _startTimeMilliseconds; private readonly int _durationMilliseconds; internal Timer(int durationMilliseconds) { _durationMilliseconds = durationMilliseconds; _startTimeMilliseconds = Environment.TickCount; } /// <summary> /// <para>The duration in milliseconds of timer.</para> /// </summary> internal int Duration { get { return _durationMilliseconds; } } /// <summary> /// <para>The time (relative to Environment.TickCount) when the timer started.</para> /// </summary> internal int StartTime { get { return _startTimeMilliseconds; } } /// <summary> /// <para>The time (relative to Environment.TickCount) when the timer will expire.</para> /// </summary> internal int Expiration { get { return unchecked(_startTimeMilliseconds + _durationMilliseconds); } } /// <summary> /// <para>The amount of time left on the timer. 0 means it has fired. 1 means it has expired but /// not yet fired. -1 means infinite. Int32.MaxValue is the ceiling - the actual value could be longer.</para> /// </summary> internal int TimeRemaining { get { if (HasExpired) { return 0; } if (Duration == Timeout.Infinite) { return Timeout.Infinite; } int now = Environment.TickCount; int remaining = IsTickBetween(StartTime, Expiration, now) ? (int)(Math.Min((uint)unchecked(Expiration - now), (uint)Int32.MaxValue)) : 0; return remaining < 2 ? remaining + 1 : remaining; } } /// <summary> /// <para>Cancels the timer. Returns true if the timer hasn't and won't fire; false if it has or will.</para> /// </summary> internal abstract bool Cancel(); /// <summary> /// <para>Whether or not the timer has expired.</para> /// </summary> internal abstract bool HasExpired { get; } public void Dispose() { Cancel(); } } /// <summary> /// <para>Prototype for the callback that is called when a timer expires.</para> /// </summary> internal delegate void Callback(Timer timer, int timeNoticed, object context); private const int c_ThreadIdleTimeoutMilliseconds = 30 * 1000; private const int c_CacheScanPerIterations = 32; private const int c_TickCountResolution = 15; private static LinkedList<WeakReference> s_Queues = new LinkedList<WeakReference>(); private static LinkedList<WeakReference> s_NewQueues = new LinkedList<WeakReference>(); private static int s_ThreadState = (int)TimerThreadState.Idle; // Really a TimerThreadState, but need an int for Interlocked. private static AutoResetEvent s_ThreadReadyEvent = new AutoResetEvent(false); private static ManualResetEvent s_ThreadShutdownEvent = new ManualResetEvent(false); private static WaitHandle[] s_ThreadEvents; private static int s_CacheScanIteration; private static Hashtable s_QueuesCache = new Hashtable(); static TimerThread() { s_ThreadEvents = new WaitHandle[] { s_ThreadShutdownEvent, s_ThreadReadyEvent }; } /// <summary> /// <para>The possible states of the timer thread.</para> /// </summary> private enum TimerThreadState { Idle, Running, Stopped } /// <summary> /// <para>Queue factory. Always synchronized.</para> /// </summary> internal static Queue GetOrCreateQueue(int durationMilliseconds) { if (durationMilliseconds == Timeout.Infinite) { return new InfiniteTimerQueue(); } if (durationMilliseconds < 0) { throw new ArgumentOutOfRangeException(nameof(durationMilliseconds)); } TimerQueue queue; WeakReference weakQueue = (WeakReference)s_QueuesCache[durationMilliseconds]; if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null) { lock (s_NewQueues) { weakQueue = (WeakReference)s_QueuesCache[durationMilliseconds]; if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null) { queue = new TimerQueue(durationMilliseconds); weakQueue = new WeakReference(queue); s_NewQueues.AddLast(weakQueue); s_QueuesCache[durationMilliseconds] = weakQueue; // Take advantage of this lock to periodically scan the table for garbage. if (++s_CacheScanIteration % c_CacheScanPerIterations == 0) { List<int> garbage = new List<int>(); foreach (DictionaryEntry pair in s_QueuesCache) { if (((WeakReference)pair.Value).Target == null) { garbage.Add((int)pair.Key); } } for (int i = 0; i < garbage.Count; i++) { s_QueuesCache.Remove(garbage[i]); } } } } } return queue; } /// <summary> /// <para>Represents a queue of timers of fixed duration.</para> /// </summary> private class TimerQueue : Queue { // This is a GCHandle that holds onto the TimerQueue when active timers are in it. // The TimerThread only holds WeakReferences to it so that it can be collected when the user lets go of it. // But we don't want the user to HAVE to keep a reference to it when timers are active in it. // It gets created when the first timer gets added, and cleaned up when the TimerThread notices it's empty. // The TimerThread will always notice it's empty eventually, since the TimerThread will always wake up and // try to fire the timer, even if it was cancelled and removed prematurely. private IntPtr _thisHandle; // This sentinel TimerNode acts as both the head and the tail, allowing nodes to go in and out of the list without updating // any TimerQueue members. _timers.Next is the true head, and .Prev the true tail. This also serves as the list's lock. private readonly TimerNode _timers; /// <summary> /// <para>Create a new TimerQueue. TimerQueues must be created while s_NewQueues is locked in /// order to synchronize with Shutdown().</para> /// </summary> /// <param name="durationMilliseconds"></param> internal TimerQueue(int durationMilliseconds) : base(durationMilliseconds) { // Create the doubly-linked list with a sentinel head and tail so that this member never needs updating. _timers = new TimerNode(); _timers.Next = _timers; _timers.Prev = _timers; } /// <summary> /// <para>Creates new timers. This method is thread-safe.</para> /// </summary> internal override Timer CreateTimer(Callback callback, object context) { TimerNode timer = new TimerNode(callback, context, Duration, _timers); // Add this on the tail. (Actually, one before the tail - _timers is the sentinel tail.) bool needProd = false; lock (_timers) { if (!(_timers.Prev.Next == _timers)) { NetEventSource.Fail(this, $"Tail corruption."); } // If this is the first timer in the list, we need to create a queue handle and prod the timer thread. if (_timers.Next == _timers) { if (_thisHandle == IntPtr.Zero) { _thisHandle = (IntPtr)GCHandle.Alloc(this); } needProd = true; } timer.Next = _timers; timer.Prev = _timers.Prev; _timers.Prev.Next = timer; _timers.Prev = timer; } // If, after we add the new tail, there is a chance that the tail is the next // node to be processed, we need to wake up the timer thread. if (needProd) { TimerThread.Prod(); } return timer; } /// <summary> /// <para>Called by the timer thread to fire the expired timers. Returns true if there are future timers /// in the queue, and if so, also sets nextExpiration.</para> /// </summary> internal bool Fire(out int nextExpiration) { while (true) { // Check if we got to the end. If so, free the handle. TimerNode timer = _timers.Next; if (timer == _timers) { lock (_timers) { timer = _timers.Next; if (timer == _timers) { if (_thisHandle != IntPtr.Zero) { ((GCHandle)_thisHandle).Free(); _thisHandle = IntPtr.Zero; } nextExpiration = 0; return false; } } } if (!timer.Fire()) { nextExpiration = timer.Expiration; return true; } } } } /// <summary> /// <para>A special dummy implementation for a queue of timers of infinite duration.</para> /// </summary> private class InfiniteTimerQueue : Queue { internal InfiniteTimerQueue() : base(Timeout.Infinite) { } /// <summary> /// <para>Always returns a dummy infinite timer.</para> /// </summary> internal override Timer CreateTimer(Callback callback, object context) { return new InfiniteTimer(); } } /// <summary> /// <para>Internal representation of an individual timer.</para> /// </summary> private class TimerNode : Timer { private TimerState _timerState; private Callback _callback; private object _context; private object _queueLock; private TimerNode _next; private TimerNode _prev; /// <summary> /// <para>Status of the timer.</para> /// </summary> private enum TimerState { Ready, Fired, Cancelled, Sentinel } internal TimerNode(Callback callback, object context, int durationMilliseconds, object queueLock) : base(durationMilliseconds) { if (callback != null) { _callback = callback; _context = context; } _timerState = TimerState.Ready; _queueLock = queueLock; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}"); } // A sentinel node - both the head and tail are one, which prevent the head and tail from ever having to be updated. internal TimerNode() : base(0) { _timerState = TimerState.Sentinel; } internal override bool HasExpired { get { return _timerState == TimerState.Fired; } } internal TimerNode Next { get { return _next; } set { _next = value; } } internal TimerNode Prev { get { return _prev; } set { _prev = value; } } /// <summary> /// <para>Cancels the timer. Returns true if it hasn't and won't fire; false if it has or will, or has already been cancelled.</para> /// </summary> internal override bool Cancel() { if (_timerState == TimerState.Ready) { lock (_queueLock) { if (_timerState == TimerState.Ready) { // Remove it from the list. This keeps the list from getting too big when there are a lot of rapid creations // and cancellations. This is done before setting it to Cancelled to try to prevent the Fire() loop from // seeing it, or if it does, of having to take a lock to synchronize with the state of the list. Next.Prev = Prev; Prev.Next = Next; // Just cleanup. Doesn't need to be in the lock but is easier to have here. Next = null; Prev = null; _callback = null; _context = null; _timerState = TimerState.Cancelled; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (success)"); return true; } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime} Cancel (failure)"); return false; } /// <summary> /// <para>Fires the timer if it is still active and has expired. Returns /// true if it can be deleted, or false if it is still timing.</para> /// </summary> internal bool Fire() { if (_timerState == TimerState.Sentinel) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "TimerQueue tried to Fire a Sentinel."); } if (_timerState != TimerState.Ready) { return true; } // Must get the current tick count within this method so it is guaranteed not to be before // StartTime, which is set in the constructor. int nowMilliseconds = Environment.TickCount; if (IsTickBetween(StartTime, Expiration, nowMilliseconds)) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Not firing ({StartTime} <= {nowMilliseconds} < {Expiration})"); return false; } bool needCallback = false; lock (_queueLock) { if (_timerState == TimerState.Ready) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"TimerThreadTimer#{StartTime}::Fire() Firing ({StartTime} <= {nowMilliseconds} >= " + Expiration + ")"); _timerState = TimerState.Fired; // Remove it from the list. Next.Prev = Prev; Prev.Next = Next; Next = null; Prev = null; needCallback = _callback != null; } } if (needCallback) { try { Callback callback = _callback; object context = _context; _callback = null; _context = null; callback(this, nowMilliseconds, context); } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) throw; if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"exception in callback: {exception}"); // This thread is not allowed to go into user code, so we should never get an exception here. // So, in debug, throw it up, killing the AppDomain. In release, we'll just ignore it. #if DEBUG throw; #endif } } return true; } } /// <summary> /// <para>A dummy infinite timer.</para> /// </summary> private class InfiniteTimer : Timer { internal InfiniteTimer() : base(Timeout.Infinite) { } private int _cancelled; internal override bool HasExpired { get { return false; } } /// <summary> /// <para>Cancels the timer. Returns true the first time, false after that.</para> /// </summary> internal override bool Cancel() { return Interlocked.Exchange(ref _cancelled, 1) == 0; } } /// <summary> /// <para>Internal mechanism used when timers are added to wake up / create the thread.</para> /// </summary> private static void Prod() { s_ThreadReadyEvent.Set(); TimerThreadState oldState = (TimerThreadState)Interlocked.CompareExchange( ref s_ThreadState, (int)TimerThreadState.Running, (int)TimerThreadState.Idle); if (oldState == TimerThreadState.Idle) { new Thread(new ThreadStart(ThreadProc)).Start(); } } /// <summary> /// <para>Thread for the timer. Ignores all exceptions. If no activity occurs for a while, /// the thread will shut down.</para> /// </summary> private static void ThreadProc() { if (NetEventSource.IsEnabled) NetEventSource.Enter(null); #if DEBUG DebugThreadTracking.SetThreadSource(ThreadKinds.Timer); using (DebugThreadTracking.SetThreadKind(ThreadKinds.System | ThreadKinds.Async)) { #endif // Set this thread as a background thread. On AppDomain/Process shutdown, the thread will just be killed. Thread.CurrentThread.IsBackground = true; // Keep a permanent lock on s_Queues. This lets for example Shutdown() know when this thread isn't running. lock (s_Queues) { // If shutdown was recently called, abort here. if (Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Running, (int)TimerThreadState.Running) != (int)TimerThreadState.Running) { return; } bool running = true; while (running) { try { s_ThreadReadyEvent.Reset(); while (true) { // Copy all the new queues to the real queues. Since only this thread modifies the real queues, it doesn't have to lock it. if (s_NewQueues.Count > 0) { lock (s_NewQueues) { for (LinkedListNode<WeakReference> node = s_NewQueues.First; node != null; node = s_NewQueues.First) { s_NewQueues.Remove(node); s_Queues.AddLast(node); } } } int now = Environment.TickCount; int nextTick = 0; bool haveNextTick = false; for (LinkedListNode<WeakReference> node = s_Queues.First; node != null; /* node = node.Next must be done in the body */) { TimerQueue queue = (TimerQueue)node.Value.Target; if (queue == null) { LinkedListNode<WeakReference> next = node.Next; s_Queues.Remove(node); node = next; continue; } // Fire() will always return values that should be interpreted as later than 'now' (that is, even if 'now' is // returned, it is 0x100000000 milliseconds in the future). There's also a chance that Fire() will return a value // intended as > 0x100000000 milliseconds from 'now'. Either case will just cause an extra scan through the timers. int nextTickInstance; if (queue.Fire(out nextTickInstance) && (!haveNextTick || IsTickBetween(now, nextTick, nextTickInstance))) { nextTick = nextTickInstance; haveNextTick = true; } node = node.Next; } // Figure out how long to wait, taking into account how long the loop took. // Add 15 ms to compensate for poor TickCount resolution (want to guarantee a firing). int newNow = Environment.TickCount; int waitDuration = haveNextTick ? (int)(IsTickBetween(now, nextTick, newNow) ? Math.Min(unchecked((uint)(nextTick - newNow)), (uint)(Int32.MaxValue - c_TickCountResolution)) + c_TickCountResolution : 0) : c_ThreadIdleTimeoutMilliseconds; if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Waiting for {waitDuration}ms"); int waitResult = WaitHandle.WaitAny(s_ThreadEvents, waitDuration, false); // 0 is s_ThreadShutdownEvent - die. if (waitResult == 0) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Awoke, cause: Shutdown"); running = false; break; } if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Awoke, cause {(waitResult == WaitHandle.WaitTimeout ? "Timeout" : "Prod")}"); // If we timed out with nothing to do, shut down. if (waitResult == WaitHandle.WaitTimeout && !haveNextTick) { Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Idle, (int)TimerThreadState.Running); // There could have been one more prod between the wait and the exchange. Check, and abort if necessary. if (s_ThreadReadyEvent.WaitOne(0, false)) { if (Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Running, (int)TimerThreadState.Idle) == (int)TimerThreadState.Idle) { continue; } } running = false; break; } } } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) throw; if (NetEventSource.IsEnabled) NetEventSource.Error(null, exception); // The only options are to continue processing and likely enter an error-loop, // shut down timers for this AppDomain, or shut down the AppDomain. Go with shutting // down the AppDomain in debug, and going into a loop in retail, but try to make the // loop somewhat slow. Note that in retail, this can only be triggered by OutOfMemory or StackOverflow, // or an exception thrown within TimerThread - the rest are caught in Fire(). #if !DEBUG Thread.Sleep(1000); #else throw; #endif } } } if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Stop"); #if DEBUG } #endif } /// <summary> /// <para>Helper for deciding whether a given TickCount is before or after a given expiration /// tick count assuming that it can't be before a given starting TickCount.</para> /// </summary> private static bool IsTickBetween(int start, int end, int comparand) { // Assumes that if start and end are equal, they are the same time. // Assumes that if the comparand and start are equal, no time has passed, // and that if the comparand and end are equal, end has occurred. return ((start <= comparand) == (end <= comparand)) != (start <= end); } } }
namespace System.Workflow.ComponentModel { using System; using System.Collections.Generic; using System.Workflow.ComponentModel.Design; internal class CompensationHandlingFilter : ActivityExecutionFilter, IActivityEventListener<ActivityExecutionStatusChangedEventArgs> { public static DependencyProperty CompensateProcessedProperty = DependencyProperty.RegisterAttached("CompensateProcessed", typeof(bool), typeof(CompensationHandlingFilter), new PropertyMetadata(false)); internal static DependencyProperty LastCompensatedOrderIdProperty = DependencyProperty.RegisterAttached("LastCompensatedOrderId", typeof(int), typeof(CompensationHandlingFilter), new PropertyMetadata(false)); #region Compensate Signal public override ActivityExecutionStatus Compensate(Activity activity, ActivityExecutionContext executionContext) { if (activity == null) throw new ArgumentNullException("activity"); if (executionContext == null) throw new ArgumentNullException("executionContext"); executionContext.Activity.HoldLockOnStatusChange(this); return NextActivityExecutorInChain(activity).Compensate(activity, executionContext); } #endregion #region IActivityEventListener<ActivityExecutionStatusChangedEventArgs> Members void IActivityEventListener<ActivityExecutionStatusChangedEventArgs>.OnEvent(object sender, ActivityExecutionStatusChangedEventArgs e) { ActivityExecutionContext context = sender as ActivityExecutionContext; if (context == null) throw new ArgumentException("sender"); if (e.Activity == context.Activity) { if (context.Activity.HasPrimaryClosed && !(bool)context.Activity.GetValue(CompensateProcessedProperty)) { context.Activity.SetValue(CompensateProcessedProperty, true); if (context.Activity.ExecutionResult == ActivityExecutionResult.Compensated) { // run compensation handler or do default compensation handling Activity compensationHandler = GetCompensationHandler(context.Activity); if (compensationHandler != null) { // subscribe for status change on compensation handler compensationHandler.RegisterForStatusChange(Activity.ClosedEvent, this); // execute compensation handler context.ExecuteActivity(compensationHandler); } else { // do default compensation if (!CompensationUtils.TryCompensateLastCompletedChildActivity(context, context.Activity, this)) { // let activity get into closed state context.Activity.ReleaseLockOnStatusChange(this); } } } else { // let activity get into closed state context.Activity.ReleaseLockOnStatusChange(this); } } } else if (e.Activity is CompensationHandlerActivity && e.ExecutionStatus == ActivityExecutionStatus.Closed) { // remove subscriber for status change on compensation handler e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this); // release lock on the primary activity context.Activity.ReleaseLockOnStatusChange(this); } else if (e.ExecutionStatus == ActivityExecutionStatus.Closed) { // remove subscriber for status change on compensated activity e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this); if (!CompensationUtils.TryCompensateLastCompletedChildActivity(context, context.Activity, this)) { // release lock on the primary activity context.Activity.ReleaseLockOnStatusChange(this); } } } #endregion #region Helper Methods internal static Activity GetCompensationHandler(Activity activityWithCompensation) { Activity compensationHandler = null; CompositeActivity compositeActivity = activityWithCompensation as CompositeActivity; if (compositeActivity != null) { foreach (Activity activity in ((ISupportAlternateFlow)compositeActivity).AlternateFlowActivities) { if (activity is CompensationHandlerActivity) { compensationHandler = activity; break; } } } return compensationHandler; } #endregion } #region CompensationUtils internal static class CompensationUtils { internal static bool TryCompensateLastCompletedChildActivity(ActivityExecutionContext context, Activity targetActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs> statusChangeHandler) { try { return TryCompensateLastCompletedChildActivity(context, targetActivity, statusChangeHandler, true); } catch (Exception) { //If root compensation failed. then flush Execution Contexts, which we opened //up now. if (targetActivity.Parent == null) CompleteRevokedExecutionContext(targetActivity, context); throw; } } private static bool TryCompensateLastCompletedChildActivity(ActivityExecutionContext context, Activity targetActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs> statusChangeHandler, bool isimmediateCompensation) { SortedDictionary<int, CompensationInfo> sortedListOfCompensatableTargets = new SortedDictionary<int, CompensationInfo>(); if (!(targetActivity is CompositeActivity)) return false; //Walk through all of the direct children which are compensatable and add them in the sorted order of their completion //bail out if any of the compensatable children is currently compensating/faulting or canceling if (CollectCompensatableTargetActivities(targetActivity as CompositeActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) return true; // walk through active contexts that contain compensatable child, add them in the sorted order of the completion // this also, walks through the completed contexts which are compensatable and are nested directly within the active contexts and adds them in the order of their completion // bail out if any activity is currently compensating/faulting or cancelling if (CollectCompensatableActiveContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) return true; // walk through all completed execution contexts which are compensatable and are directly nested under the target activity, //and add them to our sorted list CollectCompensatableCompletedContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation); //if there were no compensatable targets found, bail out if (sortedListOfCompensatableTargets.Count == 0) { CompleteRevokedExecutionContext(targetActivity, context); return false; } int? lastCompletedOrderId = targetActivity.GetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty) as Nullable<int>; int nextLastCompletedOrderId = -1; //get the last compensatable target - this could be an activity, contextInfo or a Context CompensationInfo lastCompensatableTarget = null; foreach (int completedOrderId in sortedListOfCompensatableTargets.Keys) { if (lastCompletedOrderId.HasValue && lastCompletedOrderId < completedOrderId) break; lastCompensatableTarget = sortedListOfCompensatableTargets[completedOrderId]; nextLastCompletedOrderId = completedOrderId; } //We are done with compensation on entire branch, now complete execution contexts //recursilvely which we might have opened up. if (lastCompensatableTarget == null) { CompleteRevokedExecutionContext(targetActivity, context); return false; } targetActivity.SetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty, nextLastCompletedOrderId); //the last compensatable target could be an activity if (lastCompensatableTarget.TargetActivity != null && lastCompensatableTarget.TargetActivity is ICompensatableActivity) { lastCompensatableTarget.TargetActivity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context.CompensateActivity(lastCompensatableTarget.TargetActivity); return true; } //or get the last compensatable "completed" context else if (lastCompensatableTarget.TargetExecutionInfo != null && lastCompensatableTarget.TargetExecutionContextManager != null) { ActivityExecutionContext revokedExecutionContext = lastCompensatableTarget.TargetExecutionContextManager.DiscardPersistedExecutionContext(lastCompensatableTarget.TargetExecutionInfo); //get the "first" compensatable child and compensate it if (revokedExecutionContext.Activity is ICompensatableActivity) { revokedExecutionContext.Activity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); revokedExecutionContext.CompensateActivity(revokedExecutionContext.Activity); return true; } else if (revokedExecutionContext.Activity is CompositeActivity) { //get the last compensatable child of the revoked context Activity compensatableChild = GetLastCompensatableChild(revokedExecutionContext.Activity as CompositeActivity); if (compensatableChild != null) { compensatableChild.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); revokedExecutionContext.CompensateActivity(compensatableChild); return true; } else// recursively, walk the context tree and keep revoking the compensatable contexts return TryCompensateLastCompletedChildActivity(revokedExecutionContext, revokedExecutionContext.Activity, statusChangeHandler, false); } } else if (lastCompensatableTarget.TargetExecutionContext != null) //or get the last compensatable "active" context { if (lastCompensatableTarget.TargetExecutionContext.Activity is CompositeActivity) { //get the last compensatable child of the active context Activity compensatableChild = GetLastCompensatableChild(lastCompensatableTarget.TargetExecutionContext.Activity as CompositeActivity); if (compensatableChild != null) { compensatableChild.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); lastCompensatableTarget.TargetExecutionContext.CompensateActivity(compensatableChild); return true; } else // recursively, walk the context tree and keep revoking the compensatable contexts return TryCompensateLastCompletedChildActivity(lastCompensatableTarget.TargetExecutionContext, lastCompensatableTarget.TargetExecutionContext.Activity, statusChangeHandler, false); } } return false; } private static void CompleteRevokedExecutionContext(Activity targetActivity, ActivityExecutionContext context) { ActivityExecutionContext[] activeContextsClone = new ActivityExecutionContext[context.ExecutionContextManager.ExecutionContexts.Count]; context.ExecutionContextManager.ExecutionContexts.CopyTo(activeContextsClone, 0); foreach (ActivityExecutionContext childContext in activeContextsClone) { if (targetActivity.GetActivityByName(childContext.Activity.QualifiedName, true) != null) { if (childContext.Activity.ExecutionStatus == ActivityExecutionStatus.Closed) CompleteRevokedExecutionContext(childContext.Activity, childContext); context.ExecutionContextManager.CompleteExecutionContext(childContext); } } } #region helpers private sealed class CompensationInfo { private Activity targetActivity = null; private ActivityExecutionContext targetExecutionContext = null; private ActivityExecutionContextInfo targetExecutionInfo = null; private ActivityExecutionContextManager targetExecutionContextManager = null; internal CompensationInfo(ActivityExecutionContextInfo targetExecutionInfo, ActivityExecutionContextManager targetExecutionContextManager) { this.targetExecutionInfo = targetExecutionInfo; this.targetExecutionContextManager = targetExecutionContextManager; } internal CompensationInfo(Activity targetActivity) { this.targetActivity = targetActivity; } internal CompensationInfo(ActivityExecutionContext targetExecutionContext) { this.targetExecutionContext = targetExecutionContext; } internal Activity TargetActivity { get { return targetActivity; } } internal ActivityExecutionContext TargetExecutionContext { get { return targetExecutionContext; } } internal ActivityExecutionContextInfo TargetExecutionInfo { get { return targetExecutionInfo; } } internal ActivityExecutionContextManager TargetExecutionContextManager { get { return targetExecutionContextManager; } } } //Walk through all of the direct children which are compensatable and add them in the sorted order of their completion //bail out if any of the compensatable children is currently compensating/faulting or canceling private static bool CollectCompensatableTargetActivities(CompositeActivity compositeActivity, SortedDictionary<int, CompensationInfo> sortedListOfCompensatableTargets, bool immediateCompensation) { // walk through all compensatable children and compensate them Queue<Activity> completedActivities = new Queue<Activity>(Helpers.GetAllEnabledActivities(compositeActivity)); while (completedActivities.Count > 0) { Activity completedChild = completedActivities.Dequeue(); if (completedChild.ExecutionStatus == ActivityExecutionStatus.Compensating || completedChild.ExecutionStatus == ActivityExecutionStatus.Faulting || completedChild.ExecutionStatus == ActivityExecutionStatus.Canceling) return true; //Don't walk activities which are part of reverse work of target activity. if (immediateCompensation && IsActivityInBackWorkBranch(compositeActivity, completedChild)) continue; if (completedChild is ICompensatableActivity && completedChild.ExecutionStatus == ActivityExecutionStatus.Closed && completedChild.ExecutionResult == ActivityExecutionResult.Succeeded) sortedListOfCompensatableTargets.Add((int)completedChild.GetValue(Activity.CompletedOrderIdProperty), new CompensationInfo(completedChild)); else if (completedChild is CompositeActivity) { foreach (Activity nestedCompletedActivity in Helpers.GetAllEnabledActivities((CompositeActivity)completedChild)) completedActivities.Enqueue(nestedCompletedActivity); } } return false; } // walk through active contexts that contain compensatable child, add them in the sorted order of the completion // this also, walks through the completed contexts which are compensatable and are nested directly within the active contexts and adds them in the order of their completion // bail out if any activity is currently compensating/faulting or cancelling private static bool CollectCompensatableActiveContexts(ActivityExecutionContext context, Activity targetActivity, SortedDictionary<int, CompensationInfo> sortedListOfCompensatableTargets, bool immediateCompensation) { ActivityExecutionContextManager contextManager = context.ExecutionContextManager; foreach (ActivityExecutionContext activeContext in contextManager.ExecutionContexts) { if (targetActivity.GetActivityByName(activeContext.Activity.QualifiedName, true) != null) { //Dont walk context which are part of reverse work. if (immediateCompensation && IsActivityInBackWorkBranch(targetActivity, activeContext.Activity)) continue; if (activeContext.Activity is ICompensatableActivity && (activeContext.Activity.ExecutionStatus == ActivityExecutionStatus.Compensating || activeContext.Activity.ExecutionStatus == ActivityExecutionStatus.Faulting || activeContext.Activity.ExecutionStatus == ActivityExecutionStatus.Canceling)) return true; else if (activeContext.Activity is CompositeActivity) { Activity[] activities = GetCompensatableChildren(activeContext.Activity as CompositeActivity); if (activities != null) { int lastcompletedContextOrderId = 0; foreach (Activity childActivity in activities) { int completedOrderId = (int)childActivity.GetValue(Activity.CompletedOrderIdProperty); if (lastcompletedContextOrderId < completedOrderId) lastcompletedContextOrderId = completedOrderId; } if (lastcompletedContextOrderId != 0) sortedListOfCompensatableTargets.Add(lastcompletedContextOrderId, new CompensationInfo(activeContext)); } CollectCompensatableActiveContexts(activeContext, targetActivity, sortedListOfCompensatableTargets, immediateCompensation); CollectCompensatableCompletedContexts(activeContext, targetActivity, sortedListOfCompensatableTargets, immediateCompensation); } } } return false; } private static bool IsActivityInBackWorkBranch(Activity targetParent, Activity childActivity) { //Find immediate child in targetParent, which is in path to childActivity. Activity immediateChild = childActivity; while (immediateChild.Parent != targetParent) immediateChild = immediateChild.Parent; return Helpers.IsFrameworkActivity(immediateChild); } // walk through all completed execution contexts which are compensatable and are directly nested under the target activity, //and add them to our sorted list private static void CollectCompensatableCompletedContexts(ActivityExecutionContext context, Activity targetActivity, SortedDictionary<int, CompensationInfo> sortedListOfCompensatableTargets, bool immediateCompensation) { // walk through all completed execution contexts, add them to our sorted list ActivityExecutionContextManager contextManager = context.ExecutionContextManager; for (int index = contextManager.CompletedExecutionContexts.Count - 1; index >= 0; index--) { //if the context does not have any compensatable children, continue ActivityExecutionContextInfo completedActivityInfo = contextManager.CompletedExecutionContexts[index]; if ((completedActivityInfo.Flags & PersistFlags.NeedsCompensation) == 0) continue; //ok, found a compensatable child. Activity completedActivity = targetActivity.GetActivityByName(completedActivityInfo.ActivityQualifiedName, true); if (completedActivity != null && !(immediateCompensation && IsActivityInBackWorkBranch(targetActivity, completedActivity))) sortedListOfCompensatableTargets.Add(completedActivityInfo.CompletedOrderId, new CompensationInfo(completedActivityInfo, contextManager)); } } internal static Activity[] GetCompensatableChildren(CompositeActivity compositeActivity) { SortedDictionary<int, Activity> sortedListOfCompensatableTargets = new SortedDictionary<int, Activity>(); Queue<Activity> completedActivities = new Queue<Activity>(Helpers.GetAllEnabledActivities(compositeActivity)); while (completedActivities.Count > 0) { Activity completedChild = completedActivities.Dequeue(); if (completedChild is ICompensatableActivity && completedChild.ExecutionStatus == ActivityExecutionStatus.Closed && completedChild.ExecutionResult == ActivityExecutionResult.Succeeded) sortedListOfCompensatableTargets.Add((int)completedChild.GetValue(Activity.CompletedOrderIdProperty), completedChild); else if (completedChild is CompositeActivity) { foreach (Activity nestedCompletedActivity in Helpers.GetAllEnabledActivities((CompositeActivity)completedChild)) completedActivities.Enqueue(nestedCompletedActivity); } } Activity[] ar = new Activity[sortedListOfCompensatableTargets.Count]; sortedListOfCompensatableTargets.Values.CopyTo(ar, 0); return ar; } internal static Activity GetLastCompensatableChild(CompositeActivity compositeActivity) { Activity[] activities = CompensationUtils.GetCompensatableChildren(compositeActivity); if (activities != null && activities.Length > 0 && activities[activities.Length - 1] != null) return activities[activities.Length - 1]; return null; } #endregion helpers } #endregion CompensationUtils }
using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using BitDiffer.Core; using BitDiffer.Common.Model; using BitDiffer.Common.Utility; using BitDiffer.Common.Misc; using BitDiffer.Common.Interfaces; using BitDiffer.Common.Configuration; namespace BitDiffer.Tests { public class TestBase { private static Dictionary<string, AssemblyDetail> _infCache = new Dictionary<string, AssemblyDetail>(); protected AssemblyDetail ExtractAll(string assemblyFile) { return ExtractAll(assemblyFile, DiffConfig.Default); } protected AssemblyDetail ExtractAll(string assemblyFile, DiffConfig config) { string cacheKey = assemblyFile + "|" + config.ToString(); if (config.IsolationLevel == AppDomainIsolationLevel.AutoDetect) { config.IsolationLevel = AppDomainIsolationLevel.Medium; } if (!_infCache.ContainsKey(cacheKey)) { lock (typeof(TestBase)) { if (!_infCache.ContainsKey(cacheKey)) { if (!File.Exists(assemblyFile)) { Assert.Inconclusive("Unable to locate subject assembly"); } AssemblyManager am = AssemblyManagerFactory.Create(config.IsolationLevel); AssemblyDetail inf = am.ExtractAssemblyInf(assemblyFile, config); _infCache.Add(cacheKey, inf); } } } return (AssemblyDetail)_infCache[cacheKey].Clone(); } protected AttributeDetail ExtractAttribute(string assemblyFile, string typeName) { return ExtractAttribute(assemblyFile, typeName, DiffConfig.Default); } protected AttributeDetail ExtractAttribute(string assemblyFile, string typeName, DiffConfig config) { return ExtractItem<AttributeDetail>(assemblyFile, "Attributes", typeName, config); } protected EnumDetail ExtractEnum(string assemblyFile, string typeName) { return ExtractEnum(assemblyFile, typeName, DiffConfig.Default); } protected EnumDetail ExtractEnum(string assemblyFile, string typeName, DiffConfig config) { return ExtractItem<EnumDetail>(assemblyFile, Subjects.NamespaceOne, typeName, config); } protected ReferenceDetail ExtractReference(string assemblyFile, string typeName) { return ExtractReference(assemblyFile, typeName, DiffConfig.Default); } protected ReferenceDetail ExtractReference(string assemblyFile, string typeName, DiffConfig config) { return ExtractItem<ReferenceDetail>(assemblyFile, "References", typeName, config); } protected ResourceDetail ExtractResource(string assemblyFile, string typeName) { return ExtractResource(assemblyFile, typeName, DiffConfig.Default); } protected ResourceDetail ExtractResource(string assemblyFile, string typeName, DiffConfig config) { return ExtractItem<ResourceDetail>(assemblyFile, "Resources", typeName, config); } protected InterfaceDetail ExtractInterface(string assemblyFile, string typeName) { return ExtractInterface(assemblyFile, typeName, DiffConfig.Default); } protected InterfaceDetail ExtractInterface(string assemblyFile, string typeName, DiffConfig config) { return ExtractItem<InterfaceDetail>(assemblyFile, Subjects.NamespaceOne, typeName, config); } protected ClassDetail ExtractClass(string assemblyFile, string typeName) { return ExtractClass(assemblyFile, typeName, DiffConfig.Default); } protected ClassDetail ExtractClass(string assemblyFile, string typeName, DiffConfig config) { return ExtractItem<ClassDetail>(assemblyFile, Subjects.NamespaceOne, typeName, config); } protected NamespaceDetail ExtractNamespace(string assemblyFile, string namespaceName) { return ExtractNamespace(assemblyFile, namespaceName, DiffConfig.Default); } protected NamespaceDetail ExtractNamespace(string assemblyFile, string namespaceName, DiffConfig config) { return ExtractItem<NamespaceDetail>(assemblyFile, namespaceName, config); } protected MethodDetail ExtractMethod(string assemblyFile, string typeName, string methodName) { return ExtractMethod(assemblyFile, typeName, methodName, DiffConfig.Default); } protected MethodDetail ExtractMethod(string assemblyFile, string typeName, string methodName, DiffConfig config) { ClassDetail ci = ExtractClass(assemblyFile, typeName, config); MethodDetail value = ListOperations.FindOrReturnMissing(ci.FilterChildren<MethodDetail>(), methodName); Log.Verbose("Extracted method : {0}", value); return value; } protected MethodDetail ExtractOperator(string assemblyFile, string typeName, string OperatorName) { return ExtractOperator(assemblyFile, typeName, OperatorName, DiffConfig.Default); } protected MethodDetail ExtractOperator(string assemblyFile, string typeName, string OperatorName, DiffConfig config) { ClassDetail ci = ExtractClass(assemblyFile, typeName, config); MethodDetail value = ListOperations.FindOrReturnMissing(ci.FilterChildren<OperatorDetail>(), OperatorName); Log.Verbose("Extracted Operator : {0}", value); return value; } protected FieldDetail ExtractField(string assemblyFile, string typeName, string fieldName) { return ExtractField(assemblyFile, typeName, fieldName, DiffConfig.Default); } protected FieldDetail ExtractField(string assemblyFile, string typeName, string fieldName, DiffConfig config) { ClassDetail ci = ExtractClass(assemblyFile, typeName, config); FieldDetail value = ListOperations.FindOrReturnMissing(ci.FilterChildren<FieldDetail>(), fieldName); Log.Verbose("Extracted field : {0}", value); return value; } protected PropertyDetail ExtractProperty(string assemblyFile, string typeName, string propertyName) { return ExtractProperty(assemblyFile, typeName, propertyName, DiffConfig.Default); } protected PropertyDetail ExtractProperty(string assemblyFile, string typeName, string propertyName, DiffConfig config) { ClassDetail ci = ExtractClass(assemblyFile, typeName, config); PropertyDetail value = ListOperations.FindOrReturnMissing(ci.FilterChildren<PropertyDetail>(), propertyName); Log.Verbose("Extracted property : {0}", value); return value; } protected EventDetail ExtractEvent(string assemblyFile, string typeName, string eventName) { return ExtractEvent(assemblyFile, typeName, eventName, DiffConfig.Default); } protected EventDetail ExtractEvent(string assemblyFile, string typeName, string eventName, DiffConfig config) { ClassDetail ci = ExtractClass(assemblyFile, typeName, config); EventDetail value = ListOperations.FindOrReturnMissing(ci.FilterChildren<EventDetail>(), eventName); Log.Verbose("Extracted event : {0}", value); return value; } protected T ExtractItem<T>(string assemblyFile, string parentName, string typeName) where T : ICanAlign, new() { return ExtractItem<T>(assemblyFile, parentName, typeName, DiffConfig.Default); } protected T ExtractItem<T>(string assemblyFile, string parentName, string typeName, DiffConfig config) where T : ICanAlign, new() { AssemblyDetail all = ExtractAll(assemblyFile, config); foreach (ICanCompare parent in all.Children) { if (parent.Name == parentName) { T t = ListOperations.FindOrReturnMissing(parent.FilterChildren<T>(), typeName); Log.Verbose("Extracted Item {0} : {1}", t.GetType().Name, t.ToString()); return t; } } Assert.Inconclusive("Specified parent {0} was not found", parentName); return default(T); } protected T ExtractItem<T>(string assemblyFile, string name, DiffConfig config) where T : ICanAlign, new() { AssemblyDetail all = ExtractAll(assemblyFile, config); T t = ListOperations.FindOrReturnMissing(all.FilterChildren<T>(), name); Log.Verbose("Extracted Item {0} : {1}", t.GetType().Name, t.ToString()); return t; } protected void Align(RootDetail t1, RootDetail t2) { List<List<ICanAlign>> lists = new List<List<ICanAlign>>(); lists.Add(new List<ICanAlign>()); lists.Add(new List<ICanAlign>()); lists[0].Add(t1); lists[1].Add(t2); ListOperations.AlignListsNoParent(lists.ToArray()); } protected void CheckForAttribute(RootDetail rd) { IEnumerator<AttributeDetail> ie = rd.FilterChildren<AttributeDetail>().GetEnumerator(); Assert.IsTrue(ie.MoveNext()); Log.Verbose("An attribute extracted: {0}", ie.Current.ToString()); Assert.IsFalse(ie.MoveNext()); } } }
using System; using SharpVectors.Dom.Events; namespace SharpVectors.Dom.Events { /// <summary> /// Summary description for EventListenerMap. /// </summary> public struct EventListenerMap { #region Private Fields private const int GrowthBuffer = 8; private const int GrowthFactor = 2; private EventListenerMapEntry[] entries; private int count; private bool locked; #endregion #region Private Helpers private EventListenerMapEntry[] GrowBy( int growth) { if (entries == null) { entries = new EventListenerMapEntry[ growth * GrowthFactor + GrowthBuffer]; this.count = 0; this.locked = false; return entries; } int newCount = count + growth; if (newCount > entries.Length) { newCount = newCount * GrowthFactor + GrowthBuffer; EventListenerMapEntry[] newEntries = new EventListenerMapEntry[newCount]; Array.Copy(entries, 0, newEntries, 0, entries.Length); entries = newEntries; } return entries; } #endregion #region Public Methods public void AddEventListener( string namespaceUri, string eventType, object eventGroup, EventListener listener) { EventListenerMapEntry[] entries = GrowBy(1); for (int i = 0; i < count; i++) { if (namespaceUri != entries[i].NamespaceUri) { continue; } if (eventType != entries[i].Type) { continue; } if (listener == entries[i].Listener) { return; } } entries[count] = new EventListenerMapEntry( namespaceUri, eventType, eventGroup, listener, locked); count++; } public void RemoveEventListener( string namespaceUri, string eventType, EventListener listener) { if (entries == null) { return; } for (int i = 0; i < count; i++) { if (namespaceUri != entries[i].NamespaceUri) { continue; } if (eventType != entries[i].Type) { continue; } if (listener == entries[i].Listener) { count--; entries[i] = entries[count]; entries[count] = new EventListenerMapEntry(); return; } } } public void FireEvent( IEvent @event) { string namespaceUri = @event.NamespaceUri; string eventType = @event.Type; for (int i = 0; i < count; i++) { // Check if the entry was added during this phase if (entries[i].Locked) continue; string entryNamespaceUri = entries[i].NamespaceUri; string entryEventType = entries[i].Type; if (entryNamespaceUri != null && namespaceUri != null) { if (entryNamespaceUri != namespaceUri) { continue; } } if (entryEventType != eventType) { continue; } entries[i].Listener(@event); } } public bool HasEventListenerNs( string namespaceUri, string eventType) { if (entries == null) { return false; } for (int i = 0; i < count; i++) { if (namespaceUri != entries[i].NamespaceUri) { continue; } if (eventType != entries[i].Type) { continue; } return true; } return false; } public void Lock() { locked = true; } public void Unlock() { // Unlock the map locked = false; // Unlock pending entries for (int i = 0; i < count; i++) { entries[i].Locked = false; } } #endregion } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// EmailTemplate /// </summary> [DataContract] public partial class EmailTemplate : IEquatable<EmailTemplate> { /// <summary> /// Initializes a new instance of the <see cref="EmailTemplate" /> class. /// </summary> [JsonConstructorAttribute] protected EmailTemplate() { } /// <summary> /// Initializes a new instance of the <see cref="EmailTemplate" /> class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="SubjectText">SubjectText.</param> /// <param name="Name">Name (required).</param> /// <param name="FromName">FromName (required).</param> /// <param name="FromAddress">FromAddress (required).</param> /// <param name="EmailTemplateType">EmailTemplateType (required).</param> public EmailTemplate(int? LobId = null, string SubjectText = null, string Name = null, string FromName = null, string FromAddress = null, string EmailTemplateType = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for EmailTemplate and cannot be null"); } else { this.LobId = LobId; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for EmailTemplate and cannot be null"); } else { this.Name = Name; } // to ensure "FromName" is required (not null) if (FromName == null) { throw new InvalidDataException("FromName is a required property for EmailTemplate and cannot be null"); } else { this.FromName = FromName; } // to ensure "FromAddress" is required (not null) if (FromAddress == null) { throw new InvalidDataException("FromAddress is a required property for EmailTemplate and cannot be null"); } else { this.FromAddress = FromAddress; } // to ensure "EmailTemplateType" is required (not null) if (EmailTemplateType == null) { throw new InvalidDataException("EmailTemplateType is a required property for EmailTemplate and cannot be null"); } else { this.EmailTemplateType = EmailTemplateType; } this.SubjectText = SubjectText; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets SubjectText /// </summary> [DataMember(Name="subjectText", EmitDefaultValue=false)] public string SubjectText { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets FromName /// </summary> [DataMember(Name="fromName", EmitDefaultValue=false)] public string FromName { get; set; } /// <summary> /// Gets or Sets FromAddress /// </summary> [DataMember(Name="fromAddress", EmitDefaultValue=false)] public string FromAddress { get; set; } /// <summary> /// Gets or Sets EmailTemplateType /// </summary> [DataMember(Name="emailTemplateType", EmitDefaultValue=false)] public string EmailTemplateType { get; set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class EmailTemplate {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" SubjectText: ").Append(SubjectText).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" FromName: ").Append(FromName).Append("\n"); sb.Append(" FromAddress: ").Append(FromAddress).Append("\n"); sb.Append(" EmailTemplateType: ").Append(EmailTemplateType).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as EmailTemplate); } /// <summary> /// Returns true if EmailTemplate instances are equal /// </summary> /// <param name="other">Instance of EmailTemplate to be compared</param> /// <returns>Boolean</returns> public bool Equals(EmailTemplate other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.SubjectText == other.SubjectText || this.SubjectText != null && this.SubjectText.Equals(other.SubjectText) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.FromName == other.FromName || this.FromName != null && this.FromName.Equals(other.FromName) ) && ( this.FromAddress == other.FromAddress || this.FromAddress != null && this.FromAddress.Equals(other.FromAddress) ) && ( this.EmailTemplateType == other.EmailTemplateType || this.EmailTemplateType != null && this.EmailTemplateType.Equals(other.EmailTemplateType) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.SubjectText != null) hash = hash * 59 + this.SubjectText.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.FromName != null) hash = hash * 59 + this.FromName.GetHashCode(); if (this.FromAddress != null) hash = hash * 59 + this.FromAddress.GetHashCode(); if (this.EmailTemplateType != null) hash = hash * 59 + this.EmailTemplateType.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); return hash; } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. 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. #endregion namespace MoreLinq { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; static partial class MoreEnumerable { /// <summary> /// Groups the adjacent elements of a sequence according to a /// specified key selector function. /// </summary> /// <typeparam name="TSource">The type of the elements of /// <paramref name="source"/>.</typeparam> /// <typeparam name="TKey">The type of the key returned by /// <paramref name="keySelector"/>.</typeparam> /// <param name="source">A sequence whose elements to group.</param> /// <param name="keySelector">A function to extract the key for each /// element.</param> /// <returns>A sequence of groupings where each grouping /// (<see cref="IGrouping{TKey,TElement}"/>) contains the key /// and the adjacent elements in the same order as found in the /// source sequence.</returns> /// <remarks> /// This method is implemented by using deferred execution and /// streams the groupings. The grouping elements, however, are /// buffered. Each grouping is therefore yielded as soon as it /// is complete and before the next grouping occurs. /// </remarks> public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return GroupAdjacent(source, keySelector, null); } /// <summary> /// Groups the adjacent elements of a sequence according to a /// specified key selector function and compares the keys by using a /// specified comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of /// <paramref name="source"/>.</typeparam> /// <typeparam name="TKey">The type of the key returned by /// <paramref name="keySelector"/>.</typeparam> /// <param name="source">A sequence whose elements to group.</param> /// <param name="keySelector">A function to extract the key for each /// element.</param> /// <param name="comparer">An <see cref="IEqualityComparer{T}"/> to /// compare keys.</param> /// <returns>A sequence of groupings where each grouping /// (<see cref="IGrouping{TKey,TElement}"/>) contains the key /// and the adjacent elements in the same order as found in the /// source sequence.</returns> /// <remarks> /// This method is implemented by using deferred execution and /// streams the groupings. The grouping elements, however, are /// buffered. Each grouping is therefore yielded as soon as it /// is complete and before the next grouping occurs. /// </remarks> public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { if (source == null) throw new ArgumentNullException("source"); if (keySelector == null) throw new ArgumentNullException("keySelector"); return GroupAdjacent(source, keySelector, e => e, comparer); } /// <summary> /// Groups the adjacent elements of a sequence according to a /// specified key selector function and projects the elements for /// each group by using a specified function. /// </summary> /// <typeparam name="TSource">The type of the elements of /// <paramref name="source"/>.</typeparam> /// <typeparam name="TKey">The type of the key returned by /// <paramref name="keySelector"/>.</typeparam> /// <typeparam name="TElement">The type of the elements in the /// resulting groupings.</typeparam> /// <param name="source">A sequence whose elements to group.</param> /// <param name="keySelector">A function to extract the key for each /// element.</param> /// <param name="elementSelector">A function to map each source /// element to an element in the resulting grouping.</param> /// <returns>A sequence of groupings where each grouping /// (<see cref="IGrouping{TKey,TElement}"/>) contains the key /// and the adjacent elements (of type <typeparamref name="TElement"/>) /// in the same order as found in the source sequence.</returns> /// <remarks> /// This method is implemented by using deferred execution and /// streams the groupings. The grouping elements, however, are /// buffered. Each grouping is therefore yielded as soon as it /// is complete and before the next grouping occurs. /// </remarks> public static IEnumerable<IGrouping<TKey, TElement>> GroupAdjacent<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) { return GroupAdjacent(source, keySelector, elementSelector, null); } /// <summary> /// Groups the adjacent elements of a sequence according to a /// specified key selector function. The keys are compared by using /// a comparer and each group's elements are projected by using a /// specified function. /// </summary> /// <typeparam name="TSource">The type of the elements of /// <paramref name="source"/>.</typeparam> /// <typeparam name="TKey">The type of the key returned by /// <paramref name="keySelector"/>.</typeparam> /// <typeparam name="TElement">The type of the elements in the /// resulting groupings.</typeparam> /// <param name="source">A sequence whose elements to group.</param> /// <param name="keySelector">A function to extract the key for each /// element.</param> /// <param name="elementSelector">A function to map each source /// element to an element in the resulting grouping.</param> /// <param name="comparer">An <see cref="IEqualityComparer{T}"/> to /// compare keys.</param> /// <returns>A sequence of groupings where each grouping /// (<see cref="IGrouping{TKey,TElement}"/>) contains the key /// and the adjacent elements (of type <typeparamref name="TElement"/>) /// in the same order as found in the source sequence.</returns> /// <remarks> /// This method is implemented by using deferred execution and /// streams the groupings. The grouping elements, however, are /// buffered. Each grouping is therefore yielded as soon as it /// is complete and before the next grouping occurs. /// </remarks> public static IEnumerable<IGrouping<TKey, TElement>> GroupAdjacent<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { if (source == null) throw new ArgumentNullException("source"); if (keySelector == null) throw new ArgumentNullException("keySelector"); if (elementSelector == null) throw new ArgumentNullException("elementSelector"); return GroupAdjacentImpl(source, keySelector, elementSelector, comparer ?? EqualityComparer<TKey>.Default); } private static IEnumerable<IGrouping<TKey, TElement>> GroupAdjacentImpl<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { Debug.Assert(source != null); Debug.Assert(keySelector != null); Debug.Assert(elementSelector != null); Debug.Assert(comparer != null); using (var iterator = source.GetEnumerator()) { var group = default(TKey); var members = (List<TElement>) null; while (iterator.MoveNext()) { var key = keySelector(iterator.Current); var element = elementSelector(iterator.Current); if (members != null && comparer.Equals(group, key)) { members.Add(element); } else { if (members != null) yield return CreateGroupAdjacentGrouping(group, members); group = key; members = new List<TElement> { element }; } } if (members != null) yield return CreateGroupAdjacentGrouping(group, members); } } private static Grouping<TKey, TElement> CreateGroupAdjacentGrouping<TKey, TElement>(TKey key, IList<TElement> members) { Debug.Assert(members != null); return Grouping.Create(key, members.IsReadOnly ? members : new ReadOnlyCollection<TElement>(members)); } static class Grouping { public static Grouping<TKey, TElement> Create<TKey, TElement>(TKey key, IEnumerable<TElement> members) { return new Grouping<TKey, TElement>(key, members); } } #if !NO_SERIALIZATION_ATTRIBUTES [Serializable] #endif private sealed class Grouping<TKey, TElement> : IGrouping<TKey, TElement> { private readonly IEnumerable<TElement> _members; public Grouping(TKey key, IEnumerable<TElement> members) { Debug.Assert(members != null); Key = key; _members = members; } public TKey Key { get; private set; } public IEnumerator<TElement> GetEnumerator() { return _members.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Linq; using System.Threading.Tasks; using IdentityServer4.Configuration; using IdentityServer4.Events; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace IdentityServer.Device { [Authorize] [SecurityHeaders] public class DeviceController : Controller { private readonly IDeviceFlowInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IResourceStore _resourceStore; private readonly IEventService _events; private readonly IOptions<IdentityServerOptions> _options; private readonly ILogger<DeviceController> _logger; public DeviceController( IDeviceFlowInteractionService interaction, IClientStore clientStore, IResourceStore resourceStore, IEventService eventService, IOptions<IdentityServerOptions> options, ILogger<DeviceController> logger) { _interaction = interaction; _clientStore = clientStore; _resourceStore = resourceStore; _events = eventService; _options = options; _logger = logger; } [HttpGet] public async Task<IActionResult> Index() { string userCodeParamName = _options.Value.UserInteraction.DeviceVerificationUserCodeParameter; string userCode = Request.Query[userCodeParamName]; if (string.IsNullOrWhiteSpace(userCode)) return View("UserCodeCapture"); var vm = await BuildViewModelAsync(userCode); if (vm == null) return View("Error"); vm.ConfirmUserCode = true; return View("UserCodeConfirmation", vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> UserCodeCapture(string userCode) { var vm = await BuildViewModelAsync(userCode); if (vm == null) return View("Error"); return View("UserCodeConfirmation", vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Callback(DeviceAuthorizationInputModel model) { if (model == null) throw new ArgumentNullException(nameof(model)); var result = await ProcessConsent(model); if (result.HasValidationError) return View("Error"); return View("Success"); } private async Task<ProcessConsentResult> ProcessConsent(DeviceAuthorizationInputModel model) { var result = new ProcessConsentResult(); var request = await _interaction.GetAuthorizationContextAsync(model.UserCode); if (request == null) return result; ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (model.Button == "no") { grantedConsent = ConsentResponse.Denied; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested)); } // user clicked 'yes' - validate the data else if (model.Button == "yes") { // if the user consented to some scope, build the response model if (model.ScopesConsented != null && model.ScopesConsented.Any()) { var scopes = model.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesConsented = scopes.ToArray() }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent)); } else { result.ValidationError = ConsentOptions.MustChooseOneErrorMessage; } } else { result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage; } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.HandleRequestAsync(model.UserCode, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint result.RedirectUri = model.ReturnUrl; result.ClientId = request.ClientId; } else { // we need to redisplay the consent UI result.ViewModel = await BuildViewModelAsync(model.UserCode, model); } return result; } private async Task<DeviceAuthorizationViewModel> BuildViewModelAsync(string userCode, DeviceAuthorizationInputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(userCode); if (request != null) { var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId); if (client != null) { var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested); if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any())) { return CreateConsentViewModel(userCode, model, client, resources); } else { _logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y)); } } else { _logger.LogError("Invalid client id: {0}", request.ClientId); } } return null; } private DeviceAuthorizationViewModel CreateConsentViewModel(string userCode, DeviceAuthorizationInputModel model, Client client, Resources resources) { var vm = new DeviceAuthorizationViewModel { UserCode = userCode, RememberConsent = model?.RememberConsent ?? true, ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(), ClientName = client.ClientName ?? client.ClientId, ClientUrl = client.ClientUri, ClientLogoUrl = client.LogoUri, AllowRememberConsent = client.AllowRememberConsent }; vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess) { vm.ResourceScopes = vm.ResourceScopes.Union(new[] { GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null) }); } return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Name = identity.Name, DisplayName = identity.DisplayName, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(Scope scope, bool check) { return new ScopeViewModel { Name = scope.Name, DisplayName = scope.DisplayName, Description = scope.Description, Emphasize = scope.Emphasize, Required = scope.Required, Checked = check || scope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = ConsentOptions.OfflineAccessDisplayName, Description = ConsentOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } } }
// (c) Copyright HutongGames, LLC 2010-2012. All rights reserved. using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Play maker photon variable types. Simply for better code and being able to reference conveniently the variables types to stream. /// Used in PlayMakerPhotonFsmVariableDefinition /// TODO: expand to support all possible types. /// </summary> using HutongGames.PlayMaker; public enum PlayMakerPhotonVarTypes { Bool, Int, Float, String, Vector2, Vector3, Quaternion, Rect, Color, } /// <summary> /// PlayMaker photon synch proxy. /// This behavior implements the underlying data serialization necessary to synchronize data for a given Fsm Component having some of its variables checked for network synching. /// This behavior is also observed by a PhotonView. This is mandatory for the serialization over the photon network to happen. /// the required set up described above is NOT YET checked. /// TODO: implement runtime or editor time verification that the set up is right. The problem is I can't find a way to get notified about instanciation so I can't run a check on /// a gameObject created by an instanciating from the network. /// </summary> public class PlayMakerPhotonView : MonoBehaviour { /// <summary> /// The fsm Component being observed. /// We implement the setter to set up FsmVariable as soon as possible, /// else the photonView will miss it and create errors as we start streaming the fsm vars too late ( we have to do it before the Start() ) /// </summary> public PlayMakerFSM observed { set{ _observed = value; SetUpFsmVariableToSynch(); } get{ return _observed; } } private PlayMakerFSM _observed; /// <summary> /// Holds all the variables references to read from and write to during serialization. /// </summary> private ArrayList variableLOT; /// <summary> /// call base /// </summary> private void Awake() { variableLOT = new ArrayList(); }// Awake /// <summary> /// Sets up fsm variable caching for synch. /// It scans the observed Fsm for all variable checked for network synching, and store the required info about them using PlayMakerPhotonFsmVariableDefinition /// It store all these variables in variableLOT to be iterated during stream read and write. /// TODO: implement all possible variables to synch. /// </summary> private void SetUpFsmVariableToSynch() { // fill the variableLOT with all the networksynched Fsmvariables. // bool foreach(FsmBool fsmBool in observed.FsmVariables.BoolVariables) { if (fsmBool.NetworkSync){ Debug.Log ("network synched FsmBool: '"+fsmBool.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmBool.Name; varDef.type = PlayMakerPhotonVarTypes.Bool; varDef.FsmBoolPointer = fsmBool; variableLOT.Add(varDef); } } // int foreach(FsmInt fsmInt in observed.FsmVariables.IntVariables) { if (fsmInt.NetworkSync){ Debug.Log ("network synched fsmInt: '"+fsmInt.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmInt.Name; varDef.type = PlayMakerPhotonVarTypes.Int; varDef.FsmIntPointer = fsmInt; variableLOT.Add(varDef); } } // float foreach(FsmFloat fsmFloat in observed.FsmVariables.FloatVariables) { if (fsmFloat.NetworkSync){ Debug.Log ("network synched FsmFloat: '"+fsmFloat.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmFloat.Name; varDef.type = PlayMakerPhotonVarTypes.Float; varDef.FsmFloatPointer = fsmFloat; variableLOT.Add(varDef); } } // string foreach(FsmString fsmString in observed.FsmVariables.StringVariables) { if (fsmString.NetworkSync){ Debug.Log ("network synched FsmString: '"+fsmString.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmString.Name; varDef.type = PlayMakerPhotonVarTypes.String; varDef.FsmStringPointer = fsmString; variableLOT.Add(varDef); } } // vector2 foreach(FsmVector2 fsmVector2 in observed.FsmVariables.Vector2Variables) { if (fsmVector2.NetworkSync){ Debug.Log ("network synched fsmVector2: '"+fsmVector2.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmVector2.Name; varDef.type = PlayMakerPhotonVarTypes.Vector2; varDef.FsmVector2Pointer = fsmVector2; variableLOT.Add(varDef); } } // vector3 foreach(FsmVector3 fsmVector3 in observed.FsmVariables.Vector3Variables) { if (fsmVector3.NetworkSync){ Debug.Log ("network synched fsmVector3: '"+fsmVector3.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmVector3.Name; varDef.type = PlayMakerPhotonVarTypes.Vector3; varDef.FsmVector3Pointer = fsmVector3; variableLOT.Add(varDef); } } // quaternion foreach(FsmQuaternion fsmQuaternion in observed.FsmVariables.QuaternionVariables) { if (fsmQuaternion.NetworkSync){ Debug.Log ("network synched fsmQuaternion: '"+fsmQuaternion.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmQuaternion.Name; varDef.type = PlayMakerPhotonVarTypes.Quaternion; varDef.FsmQuaternionPointer = fsmQuaternion; variableLOT.Add(varDef); } } // rect foreach(FsmRect fsmRect in observed.FsmVariables.RectVariables) { if (fsmRect.NetworkSync){ Debug.Log ("network synched fsmRect: '"+fsmRect.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmRect.Name; varDef.type = PlayMakerPhotonVarTypes.Rect; varDef.FsmRectPointer = fsmRect; variableLOT.Add(varDef); } } // color foreach(FsmColor fsmColor in observed.FsmVariables.ColorVariables) { if (fsmColor.NetworkSync){ Debug.Log ("network synched fsmColor: '"+fsmColor.Name +"' in fsm:'" +observed.Fsm.Name+"' in gameObject:'"+observed.gameObject.name+"'"); PlayMakerPhotonFsmVariableDefinition varDef = new PlayMakerPhotonFsmVariableDefinition(); varDef.name = fsmColor.Name; varDef.type = PlayMakerPhotonVarTypes.Color; varDef.FsmColorPointer = fsmColor; variableLOT.Add(varDef); } } }// SetUpFsmVariableToSynch #region serialization /// <summary> /// The serialization required for playmaker integration. This is transparent for the user. /// 1: Add the "PlaymakerPhotonView" component to observe this fsm, /// 2: Add a "photonView" component to observe that "PlaymakerPhotonView" component /// 3: Check "network synch" in the Fsm variables you want to synch over the network, /// /// This setup is required For each Fsm. So if on one GameObject , several Fsm wants to sync variables, /// you need a "PlaymakerPhotonView" and "PhotonView" setup for each. /// /// TODO: this might very well need improvment or reconsideration. AT least some editor or runtime check and helpers. /// I am thinking of letting the user only add a "photonView" observing the fsm, and at runtime insert the "PlaymakerPhotonView" in between. /// But I can't run this check when an instanciation occurs as I have no notifications of this. /// /// </summary> /// <param name='stream'> /// Stream of data /// </param> /// <param name='info'> /// Info. /// </param> void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { if (stream.isWriting) { // go through the Look up table and send in order. foreach( PlayMakerPhotonFsmVariableDefinition varDef in variableLOT ) { switch (varDef.type) { case PlayMakerPhotonVarTypes.Bool: stream.SendNext(varDef.FsmBoolPointer.Value); break; case PlayMakerPhotonVarTypes.Int: stream.SendNext(varDef.FsmIntPointer.Value); break; case PlayMakerPhotonVarTypes.Float: stream.SendNext(varDef.FsmFloatPointer.Value); break; case PlayMakerPhotonVarTypes.String: stream.SendNext(varDef.FsmStringPointer.Value); break; case PlayMakerPhotonVarTypes.Vector2: stream.SendNext(varDef.FsmVector2Pointer.Value); break; case PlayMakerPhotonVarTypes.Vector3: stream.SendNext(varDef.FsmVector3Pointer.Value); break; case PlayMakerPhotonVarTypes.Quaternion: stream.SendNext(varDef.FsmQuaternionPointer.Value); break; case PlayMakerPhotonVarTypes.Rect: stream.SendNext(varDef.FsmRectPointer.Value); break; case PlayMakerPhotonVarTypes.Color: stream.SendNext(varDef.FsmColorPointer.Value); break; } } }else{ // go through the Look up table and read in order. foreach( PlayMakerPhotonFsmVariableDefinition varDef in variableLOT ) { switch (varDef.type) { case PlayMakerPhotonVarTypes.Bool: varDef.FsmBoolPointer.Value = (bool)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.Int: varDef.FsmIntPointer.Value = (int)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.Float: varDef.FsmFloatPointer.Value = (float)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.String: varDef.FsmStringPointer.Value = (string)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.Vector2: varDef.FsmVector2Pointer.Value = (Vector2)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.Vector3: varDef.FsmVector3Pointer.Value = (Vector3)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.Quaternion: varDef.FsmQuaternionPointer.Value = (Quaternion)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.Rect: varDef.FsmRectPointer.Value = (Rect)stream.ReceiveNext(); break; case PlayMakerPhotonVarTypes.Color: varDef.FsmColorPointer.Value = (Color)stream.ReceiveNext(); break; } } }// reading or writing } #endregion } /// <summary> /// Allow a convenient description of the Fsm variable that needs streaming. /// Also let the reference be cached instead of accessed everytime. Make the stream function easier to script and potenitaly help performances hopefully. /// </summary> public class PlayMakerPhotonFsmVariableDefinition { /// <summary> /// The name of the Fsm Variable. Within a given Fsm, variables names have to be unique, so we are ok. /// </summary> public string name; /// <summary> /// Store the type conviniently instead of messing with type during the streaming. /// </summary> public PlayMakerPhotonVarTypes type; /// <summary> /// The fsm bool pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmBool FsmBoolPointer; /// <summary> /// The fsm int pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmInt FsmIntPointer; /// <summary> /// The fsm float pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmFloat FsmFloatPointer; /// <summary> /// The fsm string pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmString FsmStringPointer; /// <summary> /// The fsm vector3 pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmVector2 FsmVector2Pointer; /// <summary> /// The fsm vector3 pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmVector3 FsmVector3Pointer; /// <summary> /// The fsm quaternion pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmQuaternion FsmQuaternionPointer; /// <summary> /// The fsm rect pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmRect FsmRectPointer; /// <summary> /// The fsm color pointer. Set Only if type correspond. This is for convenient caching without loosing the type. /// </summary> public FsmColor FsmColorPointer; }
using System; using System.Collections; using System.Globalization; namespace ClosedXML.Excel { public enum XLScope { Workbook, Worksheet } public interface IXLRangeBase { IXLWorksheet Worksheet { get; } /// <summary> /// Gets an object with the boundaries of this range. /// </summary> IXLRangeAddress RangeAddress { get; } /// <summary> /// Sets a value to every cell in this range. /// <para>If the object is an IEnumerable ClosedXML will copy the collection's data into a table starting from each cell.</para> /// <para>If the object is a range ClosedXML will copy the range starting from each cell.</para> /// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para> /// <para>ClosedXML will try to translate it to the corresponding type, if it can't then the value will be left as a string.</para> /// </summary> /// <value> /// The object containing the value(s) to set. /// </value> Object Value { set; } /// <summary> /// Sets the type of the cells' data. /// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para> /// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para> /// </summary> /// <value> /// The type of the cell's data. /// </value> /// <exception cref = "ArgumentException"></exception> XLDataType DataType { set; } /// <summary> /// Sets the cells' formula with A1 references. /// </summary> /// <value>The formula with A1 references.</value> String FormulaA1 { set; } /// <summary> /// Sets the cells' formula with R1C1 references. /// </summary> /// <value>The formula with R1C1 references.</value> String FormulaR1C1 { set; } IXLStyle Style { get; set; } /// <summary> /// Gets or sets a value indicating whether this cell's text should be shared or not. /// </summary> /// <value> /// If false the cell's text will not be shared and stored as an inline value. /// </value> Boolean ShareString { set; } IXLHyperlinks Hyperlinks { get; } /// <summary> /// Returns the collection of cells. /// </summary> IXLCells Cells(); IXLCells Cells(Boolean usedCellsOnly); IXLCells Cells(Boolean usedCellsOnly, Boolean includeFormats); IXLCells Cells(String cells); IXLCells Cells(Func<IXLCell, Boolean> predicate); /// <summary> /// Returns the collection of cells that have a value. Formats are ignored. /// </summary> IXLCells CellsUsed(); /// <summary> /// Returns the collection of cells that have a value. /// </summary> /// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param> IXLCells CellsUsed(Boolean includeFormats); IXLCells CellsUsed(Func<IXLCell, Boolean> predicate); IXLCells CellsUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate); /// <summary> /// Searches the cells' contents for a given piece of text /// </summary> /// <param name="searchText">The search text.</param> /// <param name="compareOptions">The compare options.</param> /// <param name="searchFormulae">if set to <c>true</c> search formulae instead of cell values.</param> /// <returns></returns> IXLCells Search(String searchText, CompareOptions compareOptions = CompareOptions.Ordinal, Boolean searchFormulae = false); /// <summary> /// Returns the first cell of this range. /// </summary> IXLCell FirstCell(); /// <summary> /// Returns the first cell with a value of this range. Formats are ignored. /// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para> /// </summary> IXLCell FirstCellUsed(); /// <summary> /// Returns the first cell with a value of this range. /// </summary> /// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para> /// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param> IXLCell FirstCellUsed(Boolean includeFormats); IXLCell FirstCellUsed(Func<IXLCell, Boolean> predicate); IXLCell FirstCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate); /// <summary> /// Returns the last cell of this range. /// </summary> IXLCell LastCell(); /// <summary> /// Returns the last cell with a value of this range. Formats are ignored. /// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para> /// </summary> IXLCell LastCellUsed(); /// <summary> /// Returns the last cell with a value of this range. /// </summary> /// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para> /// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param> IXLCell LastCellUsed(Boolean includeFormats); IXLCell LastCellUsed(Func<IXLCell, Boolean> predicate); IXLCell LastCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate); /// <summary> /// Determines whether this range contains the specified range (completely). /// <para>For partial matches use the range.Intersects method.</para> /// </summary> /// <param name = "rangeAddress">The range address.</param> /// <returns> /// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>. /// </returns> Boolean Contains(String rangeAddress); /// <summary> /// Determines whether this range contains the specified range (completely). /// <para>For partial matches use the range.Intersects method.</para> /// </summary> /// <param name = "range">The range to match.</param> /// <returns> /// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>. /// </returns> Boolean Contains(IXLRangeBase range); Boolean Contains(IXLCell cell); /// <summary> /// Determines whether this range intersects the specified range. /// <para>For whole matches use the range.Contains method.</para> /// </summary> /// <param name = "rangeAddress">The range address.</param> /// <returns> /// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>. /// </returns> Boolean Intersects(String rangeAddress); /// <summary> /// Determines whether this range contains the specified range. /// <para>For whole matches use the range.Contains method.</para> /// </summary> /// <param name = "range">The range to match.</param> /// <returns> /// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>. /// </returns> Boolean Intersects(IXLRangeBase range); /// <summary> /// Unmerges this range. /// </summary> IXLRange Unmerge(); /// <summary> /// Merges this range. /// <para>The contents and style of the merged cells will be equal to the first cell.</para> /// </summary> IXLRange Merge(); IXLRange Merge(Boolean checkIntersect); /// <summary> /// Creates a named range out of this range. /// <para>If the named range exists, it will add this range to that named range.</para> /// <para>The default scope for the named range is Workbook.</para> /// </summary> /// <param name = "rangeName">Name of the range.</param> IXLRange AddToNamed(String rangeName); /// <summary> /// Creates a named range out of this range. /// <para>If the named range exists, it will add this range to that named range.</para> /// <param name = "rangeName">Name of the range.</param> /// <param name = "scope">The scope for the named range.</param> /// </summary> IXLRange AddToNamed(String rangeName, XLScope scope); /// <summary> /// Creates a named range out of this range. /// <para>If the named range exists, it will add this range to that named range.</para> /// <param name = "rangeName">Name of the range.</param> /// <param name = "scope">The scope for the named range.</param> /// <param name = "comment">The comments for the named range.</param> /// </summary> IXLRange AddToNamed(String rangeName, XLScope scope, String comment); /// <summary> /// Clears the contents of this range. /// </summary> /// <param name="clearOptions">Specify what you want to clear.</param> IXLRangeBase Clear(XLClearOptions clearOptions = XLClearOptions.All); /// <summary> /// Deletes the cell comments from this range. /// </summary> void DeleteComments(); IXLRangeBase SetValue<T>(T value); /// <summary> /// Converts this object to a range. /// </summary> IXLRange AsRange(); Boolean IsMerged(); Boolean IsEmpty(); Boolean IsEmpty(Boolean includeFormats); Boolean IsEntireRow(); Boolean IsEntireColumn(); IXLPivotTable CreatePivotTable(IXLCell targetCell, String name); //IXLChart CreateChart(Int32 firstRow, Int32 firstColumn, Int32 lastRow, Int32 lastColumn); IXLAutoFilter SetAutoFilter(); IXLAutoFilter SetAutoFilter(Boolean value); IXLDataValidation SetDataValidation(); IXLConditionalFormat AddConditionalFormat(); void Select(); /// <summary> /// Grows this the current range by one cell to each side /// </summary> IXLRangeBase Grow(); /// <summary> /// Grows this the current range by the specified number of cells to each side. /// </summary> /// <param name="growCount">The grow count.</param> /// <returns></returns> IXLRangeBase Grow(Int32 growCount); /// <summary> /// Shrinks this current range by one cell. /// </summary> IXLRangeBase Shrink(); /// <summary> /// Shrinks the current range by the specified number of cells from each side. /// </summary> /// <param name="shrinkCount">The shrink count.</param> /// <returns></returns> IXLRangeBase Shrink(Int32 shrinkCount); /// <summary> /// Returns the intersection of this range with another range on the same worksheet. /// </summary> /// <param name="otherRange">The other range.</param> /// <param name="thisRangePredicate">Predicate applied to this range's cells.</param> /// <param name="otherRangePredicate">Predicate applied to the other range's cells.</param> /// <returns></returns> IXLRangeBase Intersection(IXLRangeBase otherRange, Func<IXLCell, Boolean> thisRangePredicate = null, Func<IXLCell, Boolean> otherRangePredicate = null); /// <summary> /// Returns the set of cells surrounding the current range. /// </summary> /// <param name="predicate">The predicate to apply on the resulting set of cells.</param> IXLCells SurroundingCells(Func<IXLCell, Boolean> predicate = null); /// <summary> /// Calculates the union of two ranges on the same worksheet. /// </summary> /// <param name="otherRange">The other range.</param> /// <param name="thisRangePredicate">Predicate applied to this range's cells.</param> /// <param name="otherRangePredicate">Predicate applied to the other range's cells.</param> /// <returns> /// The union /// </returns> IXLCells Union(IXLRangeBase otherRange, Func<IXLCell, Boolean> thisRangePredicate = null, Func<IXLCell, Boolean> otherRangePredicate = null); /// <summary> /// Returns all cells in the current range that are not in the other range. /// </summary> /// <param name="otherRange">The other range.</param> /// <param name="thisRangePredicate">Predicate applied to this range's cells.</param> /// <param name="otherRangePredicate">Predicate applied to the other range's cells.</param> /// <returns></returns> IXLCells Difference(IXLRangeBase otherRange, Func<IXLCell, Boolean> thisRangePredicate = null, Func<IXLCell, Boolean> otherRangePredicate = null); } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GraphServiceSubscribedSkusCollectionRequest. /// </summary> public partial class GraphServiceSubscribedSkusCollectionRequest : BaseRequest, IGraphServiceSubscribedSkusCollectionRequest { /// <summary> /// Constructs a new GraphServiceSubscribedSkusCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public GraphServiceSubscribedSkusCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified SubscribedSku to the collection via POST. /// </summary> /// <param name="subscribedSku">The SubscribedSku to add.</param> /// <returns>The created SubscribedSku.</returns> public System.Threading.Tasks.Task<SubscribedSku> AddAsync(SubscribedSku subscribedSku) { return this.AddAsync(subscribedSku, CancellationToken.None); } /// <summary> /// Adds the specified SubscribedSku to the collection via POST. /// </summary> /// <param name="subscribedSku">The SubscribedSku to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created SubscribedSku.</returns> public System.Threading.Tasks.Task<SubscribedSku> AddAsync(SubscribedSku subscribedSku, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<SubscribedSku>(subscribedSku, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IGraphServiceSubscribedSkusCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IGraphServiceSubscribedSkusCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<GraphServiceSubscribedSkusCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest Expand(Expression<Func<SubscribedSku, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest Select(Expression<Func<SubscribedSku, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscribedSkusCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
#region copyright // VZF // Copyright (C) 2014-2016 Vladimir Zakharov // // http://www.code.coolhobby.ru/ // File vzffirebirdmembershipprovider.cs created on 2.6.2015 in 6:31 AM. // Last changed on 5.21.2016 in 1:10 PM. // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion using System.Web; namespace YAF.Providers.Membership { using System; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web.Security; using YAF.Classes; using YAF.Core; using YAF.Types.Interfaces; using YAF.Types.Constants; using VZF.Utils; using YAF.Providers.Utils; using VZF.Data.DAL; /// <summary> /// The yaf membership provider. /// </summary> public class VzfFirebirdMembershipProvider : MembershipProvider { #region Constants and Fields /// <summary> /// The conn str app key name. /// </summary> public static string ConnStrAppKeyName = "YafMembershipConnectionString"; public static string _connectionString; /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnectionString { get { return _connectionString; } set { _connectionString = value; } } /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnectionStringName { get; set; } /// <summary> /// The _passwordsize. /// </summary> private const int _passwordsize = 14; // Instance Variables /// <summary> /// The _app name. /// </summary> private string _appName; /// <summary> /// The _conn str name. /// </summary> private string _connStrName; /// <summary> /// The _enable password reset. /// </summary> private bool _enablePasswordReset; /// <summary> /// The _enable password retrieval. /// </summary> private bool _enablePasswordRetrieval; /// <summary> /// The _hash case. /// </summary> private string _hashCase; /// <summary> /// The _hash hex. /// </summary> private bool _hashHex; /// <summary> /// The _hash remove chars. /// </summary> private string _hashRemoveChars; /// <summary> /// The _max invalid password attempts. /// </summary> private int _maxInvalidPasswordAttempts; /// <summary> /// The _minimum required password length. /// </summary> private int _minimumRequiredPasswordLength; /// <summary> /// The _min required non alphanumeric characters. /// </summary> private int _minRequiredNonAlphanumericCharacters; /// <summary> /// The _ms compliant. /// </summary> private bool _msCompliant; /// <summary> /// The _password attempt window. /// </summary> private int _passwordAttemptWindow; /// <summary> /// The _password format. /// </summary> private MembershipPasswordFormat _passwordFormat; /// <summary> /// The _password strength regular expression. /// </summary> private string _passwordStrengthRegularExpression; /// <summary> /// The _requires question and answer. /// </summary> private bool _requiresQuestionAndAnswer; /// <summary> /// The _requires unique email. /// </summary> private bool _requiresUniqueEmail; /// <summary> /// The _use salt. /// </summary> private bool _useSalt; #endregion #region Properties /// <summary> /// Gets or sets ApplicationName. /// </summary> public override string ApplicationName { get { return this._appName; } set { if (value != this._appName) { this._appName = value; } } } /// <summary> /// Gets or sets provider Description. /// </summary> public override string Description { get { return "YAF Native Membership Provider"; } } /// <summary> /// Gets a value indicating whether EnablePasswordReset. /// </summary> public override bool EnablePasswordReset { get { return this._enablePasswordReset; } } /// <summary> /// Gets a value indicating whether EnablePasswordRetrieval. /// </summary> public override bool EnablePasswordRetrieval { get { return this._enablePasswordRetrieval; } } /// <summary> /// Gets MaxInvalidPasswordAttempts. /// </summary> public override int MaxInvalidPasswordAttempts { get { return this._maxInvalidPasswordAttempts; } } /// <summary> /// Gets MinRequiredNonAlphanumericCharacters. /// </summary> public override int MinRequiredNonAlphanumericCharacters { get { return this._minRequiredNonAlphanumericCharacters; } } /// <summary> /// Gets MinRequiredPasswordLength. /// </summary> public override int MinRequiredPasswordLength { get { return this._minimumRequiredPasswordLength; } } /// <summary> /// Gets PasswordAttemptWindow. /// </summary> public override int PasswordAttemptWindow { get { return this._passwordAttemptWindow; } } /// <summary> /// Gets PasswordFormat. /// </summary> public override MembershipPasswordFormat PasswordFormat { get { return this._passwordFormat; } } /// <summary> /// Gets PasswordStrengthRegularExpression. /// </summary> public override string PasswordStrengthRegularExpression { get { return this._passwordStrengthRegularExpression; } } /// <summary> /// Gets a value indicating whether RequiresQuestionAndAnswer. /// </summary> public override bool RequiresQuestionAndAnswer { get { return this._requiresQuestionAndAnswer; } } /// <summary> /// Gets a value indicating whether RequiresUniqueEmail. /// </summary> public override bool RequiresUniqueEmail { get { return this._requiresUniqueEmail; } } /// <summary> /// Gets HashCase. /// </summary> internal string HashCase { get { return this._hashCase; } } /// <summary> /// Gets a value indicating whether HashHex. /// </summary> internal bool HashHex { get { return this._hashHex; } } /// <summary> /// Gets HashRemoveChars. /// </summary> internal string HashRemoveChars { get { return this._hashRemoveChars; } } /// <summary> /// Gets a value indicating whether MSCompliant. /// </summary> internal bool MSCompliant { get { return this._msCompliant; } } /// <summary> /// Gets a value indicating whether UseSalt. /// </summary> internal bool UseSalt { get { return this._useSalt; } } #endregion #region Public Methods /// <summary> /// Creates a password buffer from salt and password ready for hashing/encrypting /// </summary> /// <param name="salt"> /// Salt to be applied to hashing algorithm /// </param> /// <param name="clearString"> /// Clear string to hash /// </param> /// <param name="standardComp"> /// Use Standard asp.net membership method of creating the buffer /// </param> /// <returns> /// Salted Password as Byte Array /// </returns> public static byte[] GeneratePassworFbMemebershipDBuffer(string salt, string clearString, bool standardComp) { byte[] unencodeFbMemebershipDBytes = Encoding.Unicode.GetBytes(clearString); byte[] saltBytes = Convert.FromBase64String(salt); var buffer = new byte[unencodeFbMemebershipDBytes.Length + saltBytes.Length]; if (standardComp) { // Compliant with ASP.NET Membership method of hash/salt Buffer.BlockCopy(saltBytes, 0, buffer, 0, saltBytes.Length); Buffer.BlockCopy(unencodeFbMemebershipDBytes, 0, buffer, saltBytes.Length, unencodeFbMemebershipDBytes.Length); } else { Buffer.BlockCopy(unencodeFbMemebershipDBytes, 0, buffer, 0, unencodeFbMemebershipDBytes.Length); Buffer.BlockCopy(saltBytes, 0, buffer, unencodeFbMemebershipDBytes.Length - 1, saltBytes.Length); } return buffer; } /// <summary> /// Hashes a clear string to the given hashtype /// </summary> /// <param name="clearString"> /// Clear string to hash /// </param> /// <param name="hashType"> /// hash Algorithm to be used /// </param> /// <param name="salt"> /// Salt to be applied to hashing algorithm /// </param> /// <param name="useSalt"> /// Should salt be applied to hashing algorithm /// </param> /// <param name="hashHex"> /// The hash Hex. /// </param> /// <param name="hashCase"> /// The hash Case. /// </param> /// <param name="hashRemoveChars"> /// The hash Remove Chars. /// </param> /// <param name="standardComp"> /// The standard Comp. /// </param> /// <returns> /// Hashed String as Hex or Base64 /// </returns> public static string Hash( string clearString, string hashType, string salt, bool useSalt, bool hashHex, string hashCase, string hashRemoveChars, bool standardComp) { byte[] buffer; if (useSalt) { buffer = GeneratePassworFbMemebershipDBuffer(salt, clearString, standardComp); } else { byte[] unencodeFbMemebershipDBytes = Encoding.UTF8.GetBytes(clearString); // UTF8 used to maintain compatibility buffer = new byte[unencodeFbMemebershipDBytes.Length]; Buffer.BlockCopy(unencodeFbMemebershipDBytes, 0, buffer, 0, unencodeFbMemebershipDBytes.Length); } byte[] hasheFbMemebershipDBytes = Hash(buffer, hashType); // Hash string hashedString; hashedString = hashHex ? BitBoolExtensions.ToHexString(hasheFbMemebershipDBytes) : Convert.ToBase64String(hasheFbMemebershipDBytes); // Adjust the case of the hash output switch (hashCase.ToLower()) { case "upper": hashedString = hashedString.ToUpper(); break; case "lower": hashedString = hashedString.ToLower(); break; } if (hashRemoveChars.IsSet()) { hashedString = hashRemoveChars.Aggregate(hashedString, (current, removeChar) => current.Replace(removeChar.ToString(), string.Empty)); } return hashedString; } /// <summary> /// Change Users password /// </summary> /// <param name="username"> /// Username to change password for /// </param> /// <param name="oldPassword"> /// The old Password. /// </param> /// <param name="newPassword"> /// New question /// </param> /// <returns> /// Boolean depending on whether the change was successful /// </returns> public override bool ChangePassword(string username, string oldPassword, string newPassword) { string passwordSalt = string.Empty; string newEncPassword = string.Empty; // Clean input // Check password meets requirements as set by Configuration settings if (!this.IsPasswordCompliant(newPassword)) { return false; } FbUserPasswordInfo currentPasswordInfo = FbUserPasswordInfo.CreateInstanceFromDB(ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // validate the correct user information was found... if (currentPasswordInfo == null) { return false; } // validate the correct user password was entered... if (!currentPasswordInfo.IsCorrectPassword(oldPassword)) { return false; } if (this.UseSalt) { // generate a salt if one doesn't exist... passwordSalt = currentPasswordInfo.PasswordSalt.IsNotSet() ? GenerateSalt() : currentPasswordInfo.PasswordSalt; } // encode new password newEncPassword = EncodeString( newPassword, (int)this.PasswordFormat, passwordSalt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // Call SQL Password to Change FbDB.Current.ChangePassword( ConnectionStringName, this.ApplicationName, username, newEncPassword, passwordSalt, (int)this.PasswordFormat, currentPasswordInfo.PasswordAnswer); // Return True return true; } /// <summary> /// The change password question and answer. /// </summary> /// <param name="username"> /// The username. /// </param> /// <param name="password"> /// The password. /// </param> /// <param name="newPasswordQuestion"> /// The new password question. /// </param> /// <param name="newPasswordAnswer"> /// The new password answer. /// </param> /// <returns> /// The change password question and answer. /// </returns> /// <exception cref="ArgumentException"> /// </exception> public override bool ChangePasswordQuestionAndAnswer( string username, string password, string newPasswordQuestion, string newPasswordAnswer) { // Check arguments for null values if ((username == null) || (password == null) || (newPasswordQuestion == null) || (newPasswordAnswer == null)) { throw new ArgumentException("Username, Password, Password Question or Password Answer cannot be null"); } FbUserPasswordInfo currentPasswordInfo = FbUserPasswordInfo.CreateInstanceFromDB(ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); newPasswordAnswer = EncodeString( newPasswordAnswer, currentPasswordInfo.PasswordFormat, currentPasswordInfo.PasswordSalt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentPasswordInfo.IsCorrectPassword(password)) { try { FbDB.Current.ChangePasswordQuestionAndAnswer(ConnectionStringName, this.ApplicationName, username, newPasswordQuestion, newPasswordAnswer); return true; } catch { // will return false... } } return false; // Invalid password return false } /// <summary> /// Create user and add to provider /// </summary> /// <param name="username"> /// Username /// </param> /// <param name="password"> /// Password /// </param> /// <param name="email"> /// Email Address /// </param> /// <param name="passwordQuestion"> /// Password Question /// </param> /// <param name="passwordAnswer"> /// Password Answer - used for password retrievals. /// </param> /// <param name="isApproved"> /// Is the User approved? /// </param> /// <param name="providerUserKey"> /// Provider User Key to identify the User /// </param> /// <param name="status"> /// Out - MembershipCreateStatus object containing status of the Create User process /// </param> /// <returns> /// Boolean depending on whether the deletion was successful /// </returns> public override MembershipUser CreateUser( string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { // ValidatePasswordEventArgs e = new ValidatePasswordEventArgs( username, password, true ); // OnValidatingPassword( e ); // if ( e.Cancel ) // { // status = MembershipCreateStatus.InvalidPassword; // return null; // } string salt = string.Empty, pass = string.Empty; // Check password meets requirements as set out in the web.config if (!this.IsPasswordCompliant(password)) { status = MembershipCreateStatus.InvalidPassword; return null; } // Check password Question and Answer requirements. if (this.RequiresQuestionAndAnswer) { if (passwordQuestion.IsNotSet()) { status = MembershipCreateStatus.InvalidQuestion; return null; } if (passwordAnswer.IsNotSet()) { status = MembershipCreateStatus.InvalidAnswer; return null; } } // Check provider User Key if (!(providerUserKey == null)) { // IS not a duplicate key if (!(GetUser(providerUserKey, false) == null)) { status = MembershipCreateStatus.DuplicateProviderUserKey; return null; } } // Check for unique email if (this.RequiresUniqueEmail) { if (this.GetUserNameByEmail(email).IsSet()) { status = MembershipCreateStatus.DuplicateEmail; // Email exists return null; } } // Check for unique user name if (!(this.GetUser(username, false) == null)) { status = MembershipCreateStatus.DuplicateUserName; // Username exists return null; } if (this.UseSalt) { salt = GenerateSalt(); } pass = EncodeString( password, (int)this.PasswordFormat, salt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // Encode Password Answer string encodedPasswordAnswer = EncodeString( passwordAnswer, (int)this.PasswordFormat, salt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // Process database user creation request FbDB.Current.CreateUser(ConnectionStringName, this.ApplicationName, username, pass, salt, (int)this.PasswordFormat, email, passwordQuestion, encodedPasswordAnswer, isApproved, providerUserKey); status = MembershipCreateStatus.Success; return this.GetUser(username, false); } /// <summary> /// Delete User and User's information from provider /// </summary> /// <param name="username"> /// Username to delete /// </param> /// <param name="deleteAllRelatedData"> /// Delete all related daata /// </param> /// <returns> /// Boolean depending on whether the deletion was successful /// </returns> public override bool DeleteUser(string username, bool deleteAllRelatedData) { // Check username argument is not null if (username == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "USERNAMENULL"); } // Process database user deletion request try { FbDB.Current.DeleteUser(ConnectionStringName, this.ApplicationName, username, deleteAllRelatedData); return true; } catch { // will return false... } return false; } /// <summary> /// Retrieves all users into a MembershupUserCollection where Email Matches /// </summary> /// <param name="emailToMatch"> /// Email use as filter criteria /// </param> /// <param name="pageIndex"> /// Page Index /// </param> /// <param name="pageSize"> /// The page Size. /// </param> /// <param name="totalRecords"> /// Out - Number of records held /// </param> /// <returns> /// <see cref="MembershipUser"/> Collection /// </returns> public override MembershipUserCollection FindUsersByEmail( string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { var users = new MembershipUserCollection(); if (pageIndex < 0) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGEINDEX"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGESIZE"); } // Loop through all users foreach (DataRow dr in FbDB.Current.FindUsersByEmail(ConnectionStringName, this.ApplicationName, emailToMatch, pageIndex, pageSize).Rows) { // Add new user to collection users.Add(this.UserFromDataRow(dr)); } totalRecords = users.Count; return users; } /// <summary> /// Creates a new <see cref="MembershipUser"/> from a <see cref="DataRow"/> with proper fields. /// </summary> /// <param name="dr"></param> /// <returns></returns> private MembershipUser UserFromDataRow(DataRow dr) { return new MembershipUser( this.Name.ToStringDBNull(), dr["Username"].ToStringDBNull(), dr["UserID"].ToStringDBNull(), dr["Email"].ToStringDBNull(), dr["PasswordQuestion"].ToStringDBNull(), dr["Comment"].ToStringDBNull(), dr["IsApproved"].ToBool(), dr["IsLockedOut"].ToBool(), dr["Joined"].ToDateTime(DateTime.UtcNow), dr["LastLogin"].ToDateTime(DateTime.UtcNow), dr["LastActivity"].ToDateTime(DateTime.UtcNow), dr["LastPasswordChange"].ToDateTime(DateTime.UtcNow), dr["LastLockout"].ToDateTime(DateTime.UtcNow)); } /// <summary> /// Retrieves all users into a <see cref="MembershipUserCollection"/> where Username matches /// </summary> /// <param name="usernameToMatch"> /// Username use as filter criteria /// </param> /// <param name="pageIndex"> /// Page Index /// </param> /// <param name="pageSize"> /// The page Size. /// </param> /// <param name="totalRecords"> /// Out - Number of records held /// </param> /// <returns> /// <see cref="MembershipUser"/> Collection /// </returns> public override MembershipUserCollection FindUsersByName( string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { var users = new MembershipUserCollection(); if (pageIndex < 0) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGEINDEX"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGESIZE"); } // Loop through all users foreach (DataRow dr in FbDB.Current.FindUsersByName(ConnectionStringName, this.ApplicationName, usernameToMatch, pageIndex, pageSize).Rows) { // Add new user to collection users.Add(this.UserFromDataRow(dr)); } totalRecords = users.Count; return users; } /// <summary> /// Retrieves all users into a <see cref="MembershipUserCollection"/> /// </summary> /// <param name="pageIndex"> /// Page Index /// </param> /// <param name="pageSize"> /// The page Size. /// </param> /// <param name="totalRecords"> /// Out - Number of records held /// </param> /// <returns> /// <see cref="MembershipUser"/> Collection /// </returns> public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { var users = new MembershipUserCollection(); if (pageIndex < 0) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGEINDEX"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGESIZE"); } // Loop through all users foreach (DataRow dr in FbDB.Current.GetAllUsers(ConnectionStringName, this.ApplicationName, pageIndex, pageSize).Rows) { // Add new user to collection users.Add(this.UserFromDataRow(dr)); } totalRecords = users.Count; return users; } /// <summary> /// Retrieves the number of users currently online for this application /// </summary> /// <returns> /// Number of users online /// </returns> public override int GetNumberOfUsersOnline() { return FbDB.Current.GetNumberOfUsersOnline(ConnectionStringName, this.ApplicationName, Membership.UserIsOnlineTimeWindow); } /// <summary> /// Retrieves the Users password (if <see cref="EnablePasswordRetrieval"/> is <see langword="true"/>) /// </summary> /// <param name="username"> /// Username to retrieve password for /// </param> /// <param name="answer"> /// Answer to the Users Membership Question /// </param> /// <returns> /// Password unencrypted /// </returns> public override string GetPassword(string username, string answer) { if (!this.EnablePasswordRetrieval) { ExceptionReporter.ThrowNotSupported("MEMBERSHIP", "PASSWORDRETRIEVALNOTSUPPORTED"); } // Check for null arguments if ((username == null) || (answer == null)) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMEPASSWORDNULL"); } FbUserPasswordInfo currentPasswordInfo = FbUserPasswordInfo.CreateInstanceFromDB(ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentPasswordInfo != null && currentPasswordInfo.IsCorrectAnswer(answer)) { return DecodeString(currentPasswordInfo.Password, currentPasswordInfo.PasswordFormat); } return null; } /// <summary> /// Retrieves a <see cref="MembershipUser"/> object from the criteria given /// </summary> /// <param name="username"> /// Username to be foundr /// </param> /// <param name="userIsOnline"> /// Is the User currently online /// </param> /// <returns> /// MembershipUser object /// </returns> public override MembershipUser GetUser(string username, bool userIsOnline) { if (username == null) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMENULL"); } // if it's empty don't bother calling the FbDB. if (username.IsNotSet()) { return null; } DataRow dr = FbDB.Current.GetUser(ConnectionStringName, this.ApplicationName, null, username, userIsOnline); return dr != null ? this.UserFromDataRow(dr) : null; } /// <summary> /// Retrieves a <see cref="MembershipUser"/> object from the criteria given /// </summary> /// <param name="providerUserKey"> /// User to be found based on UserKey /// </param> /// <param name="userIsOnline"> /// Is the User currently online /// </param> /// <returns> /// MembershipUser object /// </returns> public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { if (providerUserKey == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "USERKEYNULL"); } DataRow dr = FbDB.Current.GetUser(ConnectionStringName, this.ApplicationName, providerUserKey, null, userIsOnline); return dr != null ? this.UserFromDataRow(dr) : null; } /// <summary> /// Retrieves a <see cref="MembershipUser"/> object from the criteria given /// </summary> /// <param name="email"> /// The email. /// </param> /// <returns> /// Username as string /// </returns> public override string GetUserNameByEmail(string email) { if (email == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "EMAILNULL"); } DataTable users = FbDB.Current.GetUserNameByEmail(ConnectionStringName, this.ApplicationName, email); if (this.RequiresUniqueEmail && users.Rows.Count > 1) { ExceptionReporter.ThrowProvider("MEMBERSHIP", "TOOMANYUSERNAMERETURNS"); } return users.Rows.Count == 0 ? null : users.Rows[0]["Username"].ToString(); } /// <summary> /// Initialize Membership Provider /// </summary> /// <param name="name"> /// Membership Provider Name /// </param> /// <param name="config"> /// <see cref="NameValueCollection"/> of configuration items /// </param> public override void Initialize(string name, NameValueCollection config) { // Verify that the configuration section was properly passed if (!config.HasKeys()) { ExceptionReporter.ThrowArgument("ROLES", "CONFIGNOTFOUND"); } // Retrieve information for provider from web config // config ints // Minimum Required Password Length from Provider configuration this._minimumRequiredPasswordLength = int.Parse(config["minRequiredPasswordLength"] ?? "6"); // Minimum Required Non Alpha-numeric Characters from Provider configuration this._minRequiredNonAlphanumericCharacters = int.Parse(config["minRequiredNonalphanumericCharacters"] ?? "0"); // Maximum number of allowed password attempts this._maxInvalidPasswordAttempts = int.Parse(config["maxInvalidPasswordAttempts"] ?? "5"); // Password Attempt Window when maximum attempts have been reached this._passwordAttemptWindow = int.Parse(config["passwordAttemptWindow"] ?? "10"); // Check whething Hashing methods should use Salt this._useSalt = (config["useSalt"] ?? "false").ToBool(); // Check whether password hashing should output as Hex instead of Base64 this._hashHex = (config["hashHex"] ?? "false").ToBool(); // Check to see if password hex case should be altered this._hashCase = config["hashCase"].ToStringDBNull("None"); // Check to see if password should have characters removed this._hashRemoveChars = config["hashRemoveChars"].ToStringDBNull(); // Check to see if password/salt combination needs to asp.net standard membership compliant this._msCompliant = (config["msCompliant"] ?? "false").ToBool(); // Application Name this._appName = config["applicationName"].ToStringDBNull(Config.ApplicationName); // Connection String Name this._connStrName = config["connectionStringName"].ToStringDBNull(Config.ConnectionStringName); this._passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"].ToStringDBNull(); // Password reset enabled from Provider Configuration this._enablePasswordReset = (config["enablePasswordReset"] ?? "true").ToBool(); this._enablePasswordRetrieval = (config["enablePasswordRetrieval"] ?? "false").ToBool(); this._requiresQuestionAndAnswer = (config["requiresQuestionAndAnswer"] ?? "true").ToBool(); this._requiresUniqueEmail = (config["requiresUniqueEmail"] ?? "true").ToBool(); string strPasswordFormat = config["passwordFormat"].ToStringDBNull("Hashed"); switch (strPasswordFormat) { case "Clear": this._passwordFormat = MembershipPasswordFormat.Clear; break; case "Encrypted": this._passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Hashed": this._passwordFormat = MembershipPasswordFormat.Hashed; break; default: ExceptionReporter.Throw("MEMBERSHIP", "BADPASSWORDFORMAT"); break; } // is the connection string set? if (this._connStrName.IsSet()) { string connStr = ConfigurationManager.ConnectionStrings[this._connStrName].ConnectionString; ConnectionString = connStr; ConnectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connStr); // set the app variable... if (YafContext.Current.Get<HttpApplicationStateBase>()[ConnStrAppKeyName] == null) { YafContext.Current.Get<HttpApplicationStateBase>().Add(ConnStrAppKeyName, connStr); } else { YafContext.Current.Get<HttpApplicationStateBase>()[ConnStrAppKeyName] = connStr; } } base.Initialize(name, config); } /// <summary> /// Reset a users password - * /// </summary> /// <param name="username"> /// User to be found based by Name /// </param> /// <param name="answer"> /// Verification that it is them /// </param> /// <returns> /// Username as string /// </returns> public override string ResetPassword(string username, string answer) { string newPassword = string.Empty, newPasswordEnc = string.Empty, newPasswordSalt = string.Empty, newPasswordAnswer = string.Empty; // Check Password reset is enabled if (!this.EnablePasswordReset) { ExceptionReporter.ThrowNotSupported("MEMBERSHIP", "RESETNOTSUPPORTED"); } // Check arguments for null values if (username == null) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMEPASSWORDNULL"); } // get an instance of the current password information class FbUserPasswordInfo currentPasswordInfo = FbUserPasswordInfo.CreateInstanceFromDB(ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentPasswordInfo != null) { if (this.UseSalt && currentPasswordInfo.PasswordSalt.IsNotSet()) { // get a new password salt... newPasswordSalt = GenerateSalt(); } else { // use existing salt... newPasswordSalt = currentPasswordInfo.PasswordSalt; } if (answer.IsSet()) { // verify answer is correct... if (!currentPasswordInfo.IsCorrectAnswer(answer)) { return null; } } // create a new password newPassword = GeneratePassword(this.MinRequiredPasswordLength, this.MinRequiredNonAlphanumericCharacters); // encode it... newPasswordEnc = EncodeString( newPassword, (int)this.PasswordFormat, newPasswordSalt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // save to the database FbDB.Current.ResetPassword(ConnectionStringName, this.ApplicationName, username, newPasswordEnc, newPasswordSalt, (int)this.PasswordFormat, this.MaxInvalidPasswordAttempts, this.PasswordAttemptWindow); // Return unencrypted password return newPassword; } return null; } /// <summary> /// Unlocks a users account /// </summary> /// <param name="userName"> /// The user Name. /// </param> /// <returns> /// True/False is users account has been unlocked /// </returns> public override bool UnlockUser(string userName) { // Check for null argument if (userName == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "USERNAMENULL"); } try { FbDB.Current.UnlockUser(ConnectionStringName, this.ApplicationName, userName); return true; } catch { // will return false below } return false; } /// <summary> /// Updates a providers user information /// </summary> /// <param name="user"> /// <see cref="MembershipUser"/> object /// </param> public override void UpdateUser(MembershipUser user) { // Check User object is not null if (user == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "MEMBERSHIPUSERNULL"); } // Update User int updateStatus = FbDB.Current.UpdateUser(ConnectionStringName, this.ApplicationName, user, this.RequiresUniqueEmail); // Check update was not successful if (updateStatus != 0) { // An error has occurred, determine which one. switch (updateStatus) { case 1: ExceptionReporter.Throw("MEMBERSHIP", "USERKEYNULL"); break; case 2: ExceptionReporter.Throw("MEMBERSHIP", "DUPLICATEEMAIL"); break; } } } /// <summary> /// Validates a user by user name / password /// </summary> /// <param name="username"> /// Username /// </param> /// <param name="password"> /// Password /// </param> /// /// /// <returns> /// True/False whether username/password match what is on database. /// </returns> public override bool ValidateUser(string username, string password) { FbUserPasswordInfo currentUser = FbUserPasswordInfo.CreateInstanceFromDB(ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentUser != null && currentUser.IsApproved) { return currentUser.IsCorrectPassword(password); } return false; } #endregion #region Methods /// <summary> /// Encrypt string to hash method. /// </summary> /// <param name="clearString"> /// UnEncrypted Clear String /// </param> /// <param name="encFormat"> /// The enc Format. /// </param> /// <param name="salt"> /// Salt to be used in Hash method /// </param> /// <param name="useSalt"> /// Salt to be used in Hash method /// </param> /// <param name="hashHex"> /// The hash Hex. /// </param> /// <param name="hashCase"> /// The hash Case. /// </param> /// <param name="hashRemoveChars"> /// The hash Remove Chars. /// </param> /// <param name="msCompliant"> /// The ms Compliant. /// </param> /// <returns> /// Encrypted string /// </returns> internal static string EncodeString( string clearString, int encFormat, string salt, bool useSalt, bool hashHex, string hashCase, string hashRemoveChars, bool msCompliant) { string encodedPass = string.Empty; var passwordFormat = (MembershipPasswordFormat)Enum.ToObject(typeof(MembershipPasswordFormat), encFormat); // Multiple Checks to ensure UseSalt is valid. if (clearString.IsNotSet()) { // Check to ensure string is not null or empty. return String.Empty; } if (useSalt && salt.IsNotSet()) { // If Salt value is null disable Salt procedure useSalt = false; } if (useSalt && passwordFormat == MembershipPasswordFormat.Encrypted) { useSalt = false; // Cannot use Salt with encryption } // Check Encoding format / method switch (passwordFormat) { case MembershipPasswordFormat.Clear: // plain text encodedPass = clearString; break; case MembershipPasswordFormat.Hashed: encodedPass = Hash(clearString, HashType(), salt, useSalt, hashHex, hashCase, hashRemoveChars, msCompliant); break; case MembershipPasswordFormat.Encrypted: encodedPass = Encrypt(clearString, salt, msCompliant); break; default: encodedPass = Hash(clearString, HashType(), salt, useSalt, hashHex, hashCase, hashRemoveChars, msCompliant); break; } return encodedPass; } /// <summary> /// Decrypt string using passwordFormat. /// </summary> /// <param name="pass"> /// Password to be decrypted /// </param> /// <param name="passwordFormat"> /// Method of encryption /// </param> /// <returns> /// Unencrypted string /// </returns> private static string DecodeString(string pass, int passwordFormat) { switch ((MembershipPasswordFormat)Enum.ToObject(typeof(MembershipPasswordFormat), passwordFormat)) { case MembershipPasswordFormat.Clear: // MembershipPasswordFormat.Clear: return pass; case MembershipPasswordFormat.Hashed: // MembershipPasswordFormat.Hashed: ExceptionReporter.Throw("MEMBERSHIP", "DECODEHASH"); break; case MembershipPasswordFormat.Encrypted: byte[] bIn = Convert.FromBase64String(pass); byte[] bRet = (new VzfFirebirdMembershipProvider()).DecryptPassword(bIn); if (bRet == null) { return null; } return Encoding.Unicode.GetString(bRet, 16, bRet.Length - 16); default: ExceptionReporter.Throw("MEMBERSHIP", "DECODEHASH"); break; } return String.Empty; // Removes "Not all paths return a value" warning. } /// <summary> /// The encrypt. /// </summary> /// <param name="clearString"> /// The clear string. /// </param> /// <param name="saltString"> /// The salt string. /// </param> /// <param name="standardComp"> /// The standard comp. /// </param> /// <returns> /// The encrypt. /// </returns> private static string Encrypt(string clearString, string saltString, bool standardComp) { byte[] buffer = GeneratePassworFbMemebershipDBuffer(saltString, clearString, standardComp); return Convert.ToBase64String((new VzfFirebirdMembershipProvider()).EncryptPassword(buffer)); } /// <summary> /// Creates a random password based on a miniumum length and a minimum number of non-alphanumeric characters /// </summary> /// <param name="minPassLength"> /// Minimum characters in the password /// </param> /// <param name="minNonAlphas"> /// Minimum non-alphanumeric characters /// </param> /// <returns> /// Random string /// </returns> private static string GeneratePassword(int minPassLength, int minNonAlphas) { return Membership.GeneratePassword(minPassLength < _passwordsize ? _passwordsize : minPassLength, minNonAlphas); } /// <summary> /// Creates a random string used as Salt for hashing /// </summary> /// <returns> /// Random string /// </returns> private static string GenerateSalt() { var buf = new byte[16]; var rngCryptoSp = new RNGCryptoServiceProvider(); rngCryptoSp.GetBytes(buf); return Convert.ToBase64String(buf); } /// <summary> /// Hashes clear bytes to given hashtype /// </summary> /// <param name="clearBytes"> /// Clear bytes to hash /// </param> /// <param name="hashType"> /// hash Algorithm to be used /// </param> /// <returns> /// Hashed bytes /// </returns> private static byte[] Hash(byte[] clearBytes, string hashType) { // MD5, SHA1, SHA256, SHA384, SHA512 byte[] hash = HashAlgorithm.Create(hashType).ComputeHash(clearBytes); return hash; } /// <summary> /// The hash type. /// </summary> /// <returns> /// The hash type. /// </returns> private static string HashType() { if (Membership.HashAlgorithmType.IsNotSet()) { return "MD5"; // Default Hash Algorithm Type } else { return Membership.HashAlgorithmType; } } /// <summary> /// Check to see if password(string) matches required criteria. /// </summary> /// <param name="password"> /// Password to be checked /// </param> /// <param name="minLength"> /// Minimum length required /// </param> /// <param name="minNonAlphaNumerics"> /// Minimum number of Non-alpha numerics in password /// </param> /// <param name="strengthRegEx"> /// Regular Expression Strength /// </param> /// <returns> /// True/False /// </returns> private static bool IsPasswordCompliant( string password, int minLength, int minNonAlphaNumerics, string strengthRegEx) { // Check password meets minimum length criteria. if (!(password.Length >= minLength)) { return false; } // Count Non alphanumerics int symbolCount = 0; foreach (char checkChar in password.ToCharArray()) { if (!char.IsLetterOrDigit(checkChar)) { symbolCount++; } } // Check password meets minimum alphanumeric criteria if (!(symbolCount >= minNonAlphaNumerics)) { return false; } // Check Reg Expression is present if (strengthRegEx.Length > 0) { // Check password strength meets Password Strength Regex Requirements if (!Regex.IsMatch(password, strengthRegEx)) { return false; } } // Check string meets requirements as set in config return true; } /// <summary> /// Check to see if password(string) matches required criteria. /// </summary> /// <param name="passsword"> /// The passsword. /// </param> /// <returns> /// True/False /// </returns> private bool IsPasswordCompliant(string passsword) { return IsPasswordCompliant( passsword, this.MinRequiredPasswordLength, this.MinRequiredNonAlphanumericCharacters, this.PasswordStrengthRegularExpression); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using NPOI.Util; using NPOI.SS.Formula; using NPOI.SS.Formula.PTG; using NPOI.SS.Formula.Constant; /** * EXTERNALNAME<p/> * * @author Josh Micich */ public class ExternalNameRecord : StandardRecord { public const short sid = 0x23; // as per BIFF8. (some old versions used 0x223) private const int OPT_BUILTIN_NAME = 0x0001; private const int OPT_AUTOMATIC_LINK = 0x0002; // m$ doc calls this fWantAdvise private const int OPT_PICTURE_LINK = 0x0004; private const int OPT_STD_DOCUMENT_NAME = 0x0008; private const int OPT_OLE_LINK = 0x0010; // private const int OPT_CLIP_FORMAT_MASK = 0x7FE0; private const int OPT_ICONIFIED_PICTURE_LINK = 0x8000; private short field_1_option_flag; private short field_2_ixals; private short field_3_not_used; private String field_4_name; private NPOI.SS.Formula.Formula field_5_name_definition; // TODO - junits for name definition field /** * 'rgoper' / 'Last received results of the DDE link' * (seems to be only applicable to DDE links)<br/> * Logically this is a 2-D array, which has been flattened into 1-D array here. */ private Object[] _ddeValues; /** * (logical) number of columns in the {@link #_ddeValues} array */ private int _nColumns; /** * (logical) number of rows in the {@link #_ddeValues} array */ private int _nRows; public ExternalNameRecord() { field_2_ixals = 0; } public ExternalNameRecord(RecordInputStream in1) { field_1_option_flag = in1.ReadShort(); field_2_ixals = in1.ReadShort(); field_3_not_used = in1.ReadShort(); int numChars = in1.ReadUByte(); field_4_name = StringUtil.ReadUnicodeString(in1, numChars); // the record body can take different forms. // The form is dictated by the values of 3-th and 4-th bits in field_1_option_flag if (!IsOLELink && !IsStdDocumentNameIdentifier) { // another switch: the fWantAdvise bit specifies whether the body describes // an external defined name or a DDE data item if (IsAutomaticLink) { if (in1.Available() > 0) { //body specifies DDE data item int nColumns = in1.ReadUByte() + 1; int nRows = in1.ReadShort() + 1; int totalCount = nRows * nColumns; _ddeValues = ConstantValueParser.Parse(in1, totalCount); _nColumns = nColumns; _nRows = nRows; } } else { //body specifies an external defined name int formulaLen = in1.ReadUShort(); field_5_name_definition = Formula.Read(formulaLen, in1); } } //int nameLength = in1.ReadUByte(); //int multibyteFlag = in1.ReadUByte(); //if (multibyteFlag == 0) //{ // field_4_name = in1.ReadCompressedUnicode(nameLength); //} //else //{ // field_4_name = in1.ReadUnicodeLEString(nameLength); //} //if (!HasFormula) //{ // if (!IsStdDocumentNameIdentifier && !IsOLELink && IsAutomaticLink) // { // // both need to be incremented // int nColumns = in1.ReadUByte() + 1; // int nRows = in1.ReadShort() + 1; // int totalCount = nRows * nColumns; // _ddeValues = ConstantValueParser.Parse(in1, totalCount); // _nColumns = nColumns; // _nRows = nRows; // } // if (in1.Remaining > 0) // { // throw ReadFail("Some Unread data (is formula present?)"); // } // field_5_name_definition = null; // return; //} //int nBytesRemaining = in1.Available(); //if (in1.Remaining <= 0) //{ // throw ReadFail("Ran out of record data trying to read formula."); //} //short formulaLen = in1.ReadShort(); //nBytesRemaining -= 2; //field_5_name_definition = NPOI.SS.Formula.Formula.Read(formulaLen, in1, nBytesRemaining); } /** * Convenience Function to determine if the name Is a built-in name */ public bool IsBuiltInName { get { return (field_1_option_flag & OPT_BUILTIN_NAME) != 0; } } /** * For OLE and DDE, links can be either 'automatic' or 'manual' */ public bool IsAutomaticLink { get { return (field_1_option_flag & OPT_AUTOMATIC_LINK) != 0; } } /** * only for OLE and DDE */ public bool IsPicureLink { get { return (field_1_option_flag & OPT_PICTURE_LINK) != 0; } } /** * DDE links only. If <c>true</c>, this denotes the 'StdDocumentName' */ public bool IsStdDocumentNameIdentifier { get { return (field_1_option_flag & OPT_STD_DOCUMENT_NAME) != 0; } } public bool IsOLELink { get { return (field_1_option_flag & OPT_OLE_LINK) != 0; } } public bool IsIconifiedPictureLink { get { return (field_1_option_flag & OPT_ICONIFIED_PICTURE_LINK) != 0; } } public short Ix { get { return field_2_ixals; } set { field_2_ixals = value; } } /** * @return the standard String representation of this name */ public String Text { get { return field_4_name; } set { field_4_name = value; } } public Ptg[] GetParsedExpression() { return Formula.GetTokens(field_5_name_definition); } public void SetParsedExpression(Ptg[] ptgs) { field_5_name_definition = Formula.Create(ptgs); } protected override int DataSize { get { //int result = 3 * 2 // 3 short fields // + 2 + field_4_name.Length; // nameLen and name //if (HasFormula) //{ // result += field_5_name_definition.EncodedSize; //} //else //{ // if (_ddeValues != null) // { // result += 3; // byte, short // result += ConstantValueParser.GetEncodedSize(_ddeValues); // } //} //return result; int result = 2 + 4; // short and int result += StringUtil.GetEncodedSize(field_4_name) - 1; //size is byte, not short if (!IsOLELink && !IsStdDocumentNameIdentifier) { if (IsAutomaticLink) { result += 3; // byte, short result += ConstantValueParser.GetEncodedSize(_ddeValues); } else { result += field_5_name_definition.EncodedSize; } } return result; } } public override void Serialize(ILittleEndianOutput out1) { //out1.WriteShort(field_1_option_flag); //out1.WriteShort(field_2_ixals); //out1.WriteShort(field_3_not_used); //int nameLen = field_4_name.Length; //out1.WriteShort(nameLen); //StringUtil.PutCompressedUnicode(field_4_name, out1); //if (HasFormula) //{ // field_5_name_definition.Serialize(out1); //} //else //{ // if (_ddeValues != null) // { // out1.WriteByte(_nColumns - 1); // out1.WriteShort(_nRows - 1); // ConstantValueParser.Encode(out1, _ddeValues); // } //} out1.WriteShort(field_1_option_flag); out1.WriteShort(field_2_ixals); out1.WriteShort(field_3_not_used); out1.WriteByte(field_4_name.Length); StringUtil.WriteUnicodeStringFlagAndData(out1, field_4_name); if (!IsOLELink && !IsStdDocumentNameIdentifier) { if (IsAutomaticLink) { out1.WriteByte(_nColumns - 1); out1.WriteShort(_nRows - 1); ConstantValueParser.Encode(out1, _ddeValues); } else { field_5_name_definition.Serialize(out1); } } } //public override int RecordSize //{ // get { return 4 + DataSize; } //} /* * Makes better error messages (while HasFormula() Is not reliable) * Remove this when HasFormula() Is stable. */ private Exception ReadFail(String msg) { String fullMsg = msg + " fields: (option=" + field_1_option_flag + " index=" + field_2_ixals + " not_used=" + field_3_not_used + " name='" + field_4_name + "')"; return new Exception(fullMsg); } private bool HasFormula { get { // TODO - determine exact conditions when formula Is present //if (false) //{ // // "Microsoft Office Excel 97-2007 Binary File Format (.xls) Specification" // // m$'s document suggests logic like this, but bugzilla 44774 att 21790 seems to disagree // if (IsStdDocumentNameIdentifier) // { // if (IsOLELink) // { // // seems to be not possible according to m$ document // throw new InvalidOperationException( // "flags (std-doc-name and ole-link) cannot be true at the same time"); // } // return false; // } // if (IsOLELink) // { // return false; // } // return true; //} // This was derived by trial and error, but doesn't seem quite right if (IsAutomaticLink) { return false; } return true; } } public override short Sid { get { return sid; } } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append("[EXTERNALNAME]\n"); sb.Append(" .options = ").Append(field_1_option_flag).Append("\n"); sb.Append(" .ix = ").Append(field_2_ixals).Append("\n"); sb.Append(" .name = ").Append(field_4_name).Append("\n"); if (field_5_name_definition != null) { Ptg[] ptgs = field_5_name_definition.Tokens; for (int i = 0; i < ptgs.Length; i++) { Ptg ptg = ptgs[i]; sb.Append(ptg.ToString()).Append(ptg.RVAType).Append("\n"); } } sb.Append("[/EXTERNALNAME]\n"); return sb.ToString(); } } }
using System; /* * $Id: InfBlocks.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $ * Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) * and contributors of zlib. */ namespace Org.BouncyCastle.Utilities.Zlib { public enum InflateBlockMode { /// <summary> /// get type bits (3, including end bit) /// </summary> TYPE = 0, /// <summary> /// get lengths for stored /// </summary> LENS = 1, /// <summary> /// cessing stored block /// </summary> STORED = 2, /// <summary> /// get table lengths /// </summary> TABLE = 3, /// <summary> /// get bit lengths tree for a dynamic block /// </summary> BTREE = 4, /// <summary> /// get length, distance trees for a dynamic block /// </summary> DTREE = 5, /// <summary> /// processing fixed or dynamic block /// </summary> CODES = 6, /// <summary> /// output remaining window bytes /// </summary> DRY = 7, /// <summary> /// finished last block, done /// </summary> DONE = 8, /// <summary> /// ot a data error--stuck here /// </summary> BAD = 9 } internal sealed class InflateBlocks : InflateCodes { private const int MANY = 1440; // And'ing with mask[n] masks the lower n bits private static readonly int[] inflate_mask = { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff }; // Table for deflate from PKZIP's appnote.txt. static readonly int[] border = { // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; internal InflateBlockMode mode; // current inflate_block mode internal int left; // if STORED, bytes left to copy internal int table; // table lengths (14 bits) internal int index; // index into blens (or border) internal int[] blens; // bit lengths of codes internal int[] bb = new int[1]; // bit length tree depth internal int[] tb = new int[1]; // bit length decoding tree //internal InfCodes codes = new InfCodes(); // if CODES, current state int last; // true if this block is the last block // mode independent information internal int bitk; // bits in bit buffer internal int bitb; // bit buffer internal int[] hufts; // single malloc for tree space internal byte[] window; // sliding window internal int end; // one byte after sliding window internal int read; // window read pointer internal int write; // window write pointer internal Object checkfn; // check function internal long check; // check on output internal InflateTree inftree = new InflateTree(); internal InflateBlocks(ICompressor z, Object checkfn, int w) { hufts = new int[MANY * 3]; window = new byte[w]; end = w; this.checkfn = checkfn; mode = InflateBlockMode.TYPE; reset(z, null); } internal void reset(ICompressor z, long[] c) { if (c != null) c[0] = check; if (mode == InflateBlockMode.BTREE || mode == InflateBlockMode.DTREE) { } if (mode == InflateBlockMode.CODES) { codesfree(z); } mode = InflateBlockMode.TYPE; bitk = 0; bitb = 0; read = write = 0; if (checkfn != null) z.adler = check = Adler32.adler32(0L, null, 0, 0); } internal ZLibStatus proc(ICompressor z, ZLibStatus r) { int t; // temporary storage ZLibStatus tt; int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; { // bytes to end of window or read pointer // copy input/output information to locals (UPDATE macro restores) p = z.next_in_index; n = z.avail_in; b = bitb; k = bitk; } { q = write; m = (int)(q < read ? read - q - 1 : end - q); } // process input based on current state while (true) { switch (mode) { case InflateBlockMode.TYPE: while (k < (3)) { if (n != 0) { r = ZLibStatus.Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); }; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } t = (int)(b & 7); last = t & 1; switch (t >> 1) { case 0: { // stored b >>= (3); k -= (3); } t = k & 7; { // go to byte boundary b >>= (t); k -= (t); } mode = InflateBlockMode.LENS; // get length of stored block break; case 1: { // fixed int[] bl = new int[1]; int[] bd = new int[1]; int[][] tl = new int[1][]; int[][] td = new int[1][]; InflateTree.InflateTreesFixed(bl, bd, tl, td, z); codesinit(bl[0], bd[0], tl[0], 0, td[0], 0, z); } { b >>= (3); k -= (3); } mode = InflateBlockMode.CODES; break; case 2: { // dynamic b >>= (3); k -= (3); } mode = InflateBlockMode.TABLE; break; case 3: { // illegal b >>= (3); k -= (3); } mode = InflateBlockMode.BAD; z.msg = "invalid block type"; r = ZLibStatus.Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } break; case InflateBlockMode.LENS: while (k < (32)) { if (n != 0) { r = ZLibStatus.Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); }; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } if ((((~b) >> 16) & 0xffff) != (b & 0xffff)) { mode = InflateBlockMode.BAD; z.msg = "invalid stored block lengths"; r = ZLibStatus.Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } left = (b & 0xffff); b = k = 0; // dump bits mode = left != 0 ? InflateBlockMode.STORED : (last != 0 ? InflateBlockMode.DRY : InflateBlockMode.TYPE); break; case InflateBlockMode.STORED: if (n == 0) { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } if (m == 0) { if (q == end && read != 0) { q = 0; m = (int)(q < read ? read - q - 1 : end - q); } if (m == 0) { write = q; r = inflate_flush(z, r); q = write; m = (int)(q < read ? read - q - 1 : end - q); if (q == end && read != 0) { q = 0; m = (int)(q < read ? read - q - 1 : end - q); } if (m == 0) { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } } } r = ZLibStatus.Z_OK; t = left; if (t > n) t = n; if (t > m) t = m; System.Array.Copy(z.next_in, p, window, q, t); p += t; n -= t; q += t; m -= t; if ((left -= t) != 0) break; mode = last != 0 ? InflateBlockMode.DRY : InflateBlockMode.TYPE; break; case InflateBlockMode.TABLE: while (k < (14)) { if (n != 0) { r = ZLibStatus.Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); }; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } table = t = (b & 0x3fff); if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { mode = InflateBlockMode.BAD; z.msg = "too many length or distance symbols"; r = ZLibStatus.Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); if (blens == null || blens.Length < t) { blens = new int[t]; } else { for (int i = 0; i < t; i++) { blens[i] = 0; } } { b >>= (14); k -= (14); } index = 0; mode = InflateBlockMode.BTREE; goto case InflateBlockMode.BTREE; case InflateBlockMode.BTREE: while (index < 4 + (table >> 10)) { while (k < (3)) { if (n != 0) { r = ZLibStatus.Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); }; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } blens[border[index++]] = b & 7; { b >>= (3); k -= (3); } } while (index < 19) { blens[border[index++]] = 0; } bb[0] = 7; tt = inftree.InflateTreesBits(blens, bb, tb, hufts, z); if (tt != ZLibStatus.Z_OK) { r = tt; if (r == ZLibStatus.Z_DATA_ERROR) { blens = null; mode = InflateBlockMode.BAD; } bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } index = 0; mode = InflateBlockMode.DTREE; goto case InflateBlockMode.DTREE; case InflateBlockMode.DTREE: while (true) { t = table; if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))) { break; } int i, j, c; t = bb[0]; while (k < (t)) { if (n != 0) { r = ZLibStatus.Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); }; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } if (tb[0] == -1) { //System.err.println("null..."); } t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1]; c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2]; if (c < 16) { b >>= (t); k -= (t); blens[index++] = c; } else { // c == 16..18 i = c == 18 ? 7 : c - 14; j = c == 18 ? 11 : 3; while (k < (t + i)) { if (n != 0) { r = ZLibStatus.Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); }; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } b >>= (t); k -= (t); j += (b & inflate_mask[i]); b >>= (i); k -= (i); i = index; t = table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { blens = null; mode = InflateBlockMode.BAD; z.msg = "invalid bit length repeat"; r = ZLibStatus.Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } c = c == 16 ? blens[i - 1] : 0; do { blens[i++] = c; } while (--j != 0); index = i; } } tb[0] = -1; { int[] bl = new int[1]; int[] bd = new int[1]; int[] tl = new int[1]; int[] td = new int[1]; bl[0] = 9; // must be <= 9 for lookahead assumptions bd[0] = 6; // must be <= 9 for lookahead assumptions t = table; tt = inftree.InflateTreesDynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td, hufts, z); if (tt != ZLibStatus.Z_OK) { if (tt == ZLibStatus.Z_DATA_ERROR) { blens = null; mode = InflateBlockMode.BAD; } r = tt; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } codesinit(bl[0], bd[0], hufts, tl[0], hufts, td[0], z); } mode = InflateBlockMode.CODES; goto case InflateBlockMode.CODES; case InflateBlockMode.CODES: bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; if ((r = codesproc(this, z, r)) != ZLibStatus.Z_STREAM_END) { return inflate_flush(z, r); } r = ZLibStatus.Z_OK; codesfree(z); p = z.next_in_index; n = z.avail_in; b = bitb; k = bitk; q = write; m = (int)(q < read ? read - q - 1 : end - q); if (last == 0) { mode = InflateBlockMode.TYPE; break; } mode = InflateBlockMode.DRY; goto case InflateBlockMode.DRY; case InflateBlockMode.DRY: write = q; r = inflate_flush(z, r); q = write; m = (int)(q < read ? read - q - 1 : end - q); if (read != write) { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } mode = InflateBlockMode.DONE; goto case InflateBlockMode.DONE; case InflateBlockMode.DONE: r = ZLibStatus.Z_STREAM_END; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); case InflateBlockMode.BAD: r = ZLibStatus.Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); default: r = ZLibStatus.Z_STREAM_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } } } internal void free(ICompressor z) { reset(z, null); window = null; hufts = null; //ZFREE(z, s); } internal void set_dictionary(byte[] d, int start, int n) { System.Array.Copy(d, start, window, 0, n); read = write = n; } // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or FlushType.Z_FULL_FLUSH. internal ZLibStatus sync_point() { return mode == InflateBlockMode.LENS ? ZLibStatus.Z_STREAM_END : ZLibStatus.Z_OK; } // copy as much as possible from the sliding window to the output area internal ZLibStatus inflate_flush(ICompressor z, ZLibStatus r) { int n; int p; int q; // local copies of source and destination pointers p = z.next_out_index; q = read; // compute number of bytes to copy as far as end of window n = (int)((q <= write ? write : end) - q); if (n > z.avail_out) n = z.avail_out; if (n != 0 && r == ZLibStatus.Z_BUF_ERROR) r = ZLibStatus.Z_OK; // update counters z.avail_out -= n; z.total_out += n; // update check information if (checkfn != null) z.adler = check = Adler32.adler32(check, window, q, n); // copy as far as end of window System.Array.Copy(window, q, z.next_out, p, n); p += n; q += n; // see if more to copy at beginning of window if (q == end) { // wrap pointers q = 0; if (write == end) write = 0; // compute bytes to copy n = write - q; if (n > z.avail_out) n = z.avail_out; if (n != 0 && r == ZLibStatus.Z_BUF_ERROR) r = ZLibStatus.Z_OK; // update counters z.avail_out -= n; z.total_out += n; // update check information if (checkfn != null) z.adler = check = Adler32.adler32(check, window, q, n); // copy System.Array.Copy(window, q, z.next_out, p, n); p += n; q += n; } // update pointers z.next_out_index = p; read = q; // done return r; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration.Provider; using System.Linq; using System.Security.Cryptography; using System.Web.Hosting; using System.Web.Profile; using System.Web.Security; using Velyo.Web.Security.Models; using Velyo.Web.Security.Store; namespace Velyo.Web.Security { /// <summary> /// Specialized MembershipProvider that uses a file (Users.config) to store its data. /// Passwords for the users are always stored as a salted hash (see: http://msdn.microsoft.com/msdnmag/issues/03/08/SecurityBriefs/) /// </summary> public class XmlMembershipProvider : MembershipProviderBase, IDisposable { private string _file; private WeakReference _storeRef; /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="XmlMembershipProvider"/> is reclaimed by garbage collection. /// </summary> ~XmlMembershipProvider() { Dispose(false); } /// <summary> /// Gets the store. /// </summary> /// <value>The store.</value> protected XmlUserStore Store { get { XmlUserStore store = StoreRef.Target as XmlUserStore; if (store == null) { StoreRef.Target = store = new XmlUserStore(_file); } return store; } } /// <summary> /// Gets the store ref. /// </summary> /// <value>The store ref.</value> private WeakReference StoreRef { get { return _storeRef ?? (_storeRef = new WeakReference(new XmlUserStore(_file))); } } /// <summary> /// Gets the users. /// </summary> /// <value>The users.</value> public List<User> Users { get { return Store.Users; } } /// <summary> /// Setups the specified saved state. /// </summary> /// <param name="savedState">State of the saved.</param> private static void SetupInitialUser(string role, string user, string password) { if (Roles.Enabled) { if (!Roles.RoleExists(role)) Roles.CreateRole(role); Membership.CreateUser(user, password); Roles.AddUserToRole(user, role); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (_storeRef != null) { var store = _storeRef.Target as XmlUserStore; if (store != null) store.Dispose(); _storeRef.Target = store = null; _storeRef = null; } _file = null; } } /// <summary> /// Adds a new membership user to the data source. /// </summary> /// <param name="username">The user name for the new user.</param> /// <param name="password">The password for the new user.</param> /// <param name="email">The e-mail address for the new user.</param> /// <param name="passwordQuestion">The password question for the new user.</param> /// <param name="passwordAnswer">The password answer for the new user</param> /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when username is <c>null</c></exception> public override MembershipUser CreateUser( string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { if (username == null) throw new ArgumentNullException(nameof(username)); try { bool valid = VerifyUserIsValid( providerUserKey, username, password, email, passwordQuestion, passwordAnswer, out status); if (valid) { // user date is valid then create DateTime now = UseUniversalTime ? DateTime.UtcNow : DateTime.Now; string salt = string.Empty; string encodedPassword = EncodePassword(password, ref salt); var userKey = (providerUserKey != null) ? (Guid)providerUserKey : Guid.NewGuid(); var user = new User { UserKey = userKey, UserName = username, PasswordSalt = salt, Password = encodedPassword, Email = email, PasswordQuestion = passwordQuestion, PasswordAnswer = passwordAnswer, IsApproved = isApproved, CreationDate = now, LastActivityDate = now, LastPasswordChangeDate = now }; lock (SyncRoot) { // Add the user to the store Store.Users.Add(user); Store.Save(); } return CreateMembershipFromInternalUser(user); } else { return null; } } catch { throw; } } /// <summary> /// Removes a user from the membership data source. /// </summary> /// <param name="username">The name of the user to delete.</param> /// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param> /// <returns> /// true if the user was successfully deleted; otherwise, false. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when username is <c>null</c></exception> public override bool DeleteUser(string username, bool deleteAllRelatedData) { if (username == null) throw new ArgumentNullException(nameof(username)); try { if (deleteAllRelatedData) { // remove user from roles string[] roles = Roles.GetRolesForUser(username); if ((roles != null) && (roles.Length > 0)) { Roles.RemoveUsersFromRoles(new string[] { username }, roles); } // delete user profile ProfileManager.DeleteProfile(username); } lock (SyncRoot) { User user = GetInternalUser(username); if (user != null) { Store.Users.Remove(user); Store.Save(); } } return true; } catch { throw; } } /// <summary> /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match. /// </summary> /// <param name="emailToMatch">The e-mail address to search for.</param> /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when emailToMatch is <c>null</c></exception> public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { if (emailToMatch == null) throw new ArgumentNullException(nameof(emailToMatch)); User[] users; int pageOffset = pageIndex * pageSize; try { var comparison = Comparison; var query = from u in Users let email = u.Email where ((email != null) && (email.IndexOf(emailToMatch, comparison) >= 0)) select u; lock (SyncRoot) { totalRecords = query.Count(); users = query.Skip(pageOffset).Take(pageSize).ToArray(); } return CreateMembershipCollectionFromInternalList(users); } catch { throw; } } /// <summary> /// Gets a collection of membership users where the user name contains the specified user name to match. /// </summary> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when usernameToMatch is <c>null</c></exception> public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { if (usernameToMatch == null) throw new ArgumentNullException(nameof(usernameToMatch)); int pageOffset = pageIndex * pageSize; User[] users; try { var comparison = Comparison; var query = from u in Users let name = u.UserName where (name.IndexOf(usernameToMatch, comparison) >= 0) select u; lock (SyncRoot) { totalRecords = query.Count(); users = query.Skip(pageOffset).Take(pageSize).ToArray(); } return CreateMembershipCollectionFromInternalList(users); } catch { throw; } } /// <summary> /// Gets a collection of all the users in the data source in pages of data. /// </summary> /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> /// <param name="pageSize">The size of the page of results to return.</param> /// <param name="totalRecords">The total number of matched users.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex. /// </returns> public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { int pageOffset = pageIndex * pageSize; User[] users; try { lock (SyncRoot) { totalRecords = Users.Count; users = Users.Skip(pageOffset).Take(pageSize).ToArray(); } return CreateMembershipCollectionFromInternalList(users); } catch { throw; } } /// <summary> /// Gets the number of users currently accessing the application. /// </summary> /// <returns> /// The number of users currently accessing the application. /// </returns> public override int GetNumberOfUsersOnline() { int count = 0; int onlineTime = Membership.UserIsOnlineTimeWindow; DateTime now = UseUniversalTime ? DateTime.UtcNow : DateTime.Now; try { var query = from u in Users where (u.LastActivityDate.AddMinutes(onlineTime) >= now) select u; lock (SyncRoot) { count = query.Count(); } } catch { throw; } return count; } /// <summary> /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user. /// </summary> /// <param name="username">The name of the user to get information for.</param> /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when username is <c>null</c></exception> public override MembershipUser GetUser(string username, bool userIsOnline) { if (username == null) throw new ArgumentNullException(nameof(username)); User user; try { lock (SyncRoot) { user = GetInternalUser(username); if ((user != null) && (userIsOnline)) { user.LastActivityDate = UseUniversalTime ? DateTime.UtcNow : DateTime.Now; Store.Save(); } } return CreateMembershipFromInternalUser(user); } catch { throw; } } /// <summary> /// Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user. /// </summary> /// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param> /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when providerUserKey is <c>null</c></exception> /// <exception cref="T:System.ArgumentException">Thrown when providerUserKey is not a <see cref="T:System.Guid"></see></exception> public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { if (providerUserKey == null) throw new ArgumentNullException(nameof(providerUserKey)); if (!(providerUserKey is Guid)) throw new ArgumentException("Invalid provider user key. Must be a Guid."); User user; Guid key = (Guid)providerUserKey; try { var query = from u in Users where (u.UserKey == key) select u; lock (SyncRoot) { user = query.FirstOrDefault(); if ((user != null) && (userIsOnline)) { user.LastActivityDate = DateTime.Now; Store.Save(); } } return CreateMembershipFromInternalUser(user); } catch { throw; } } /// <summary> /// Gets the user name associated with the specified e-mail address. /// </summary> /// <param name="email">The e-mail address to search for.</param> /// <returns> /// The user name associated with the specified e-mail address. If no match is found, return null. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when email is <c>null</c></exception> public override string GetUserNameByEmail(string email) { if (email == null) throw new ArgumentNullException(nameof(email)); User user; try { var comparison = Comparison; var query = from u in Users where u.Email.Equals(email, comparison) select u; lock (SyncRoot) { if (RequiresUniqueEmail && (query.Count() > 1)) throw new ProviderException("More than one user with same email found."); user = query.FirstOrDefault(); } return (user != null) ? user.UserName : null; } catch { throw; } } /// <summary> /// Clears a lock so that the membership user can be validated. /// </summary> /// <param name="username">The username.</param> /// <returns> /// true if the membership user was successfully unlocked; otherwise, false. /// </returns> /// <exception cref="T:System.ArgumentNullException">Thrown when username is <c>null</c></exception> public override bool UnlockUser(string username) { if (username == null) throw new ArgumentNullException(nameof(username)); bool unlocked = false; try { lock (SyncRoot) { var user = GetInternalUser(username); if (user != null && user.IsLockedOut) { user.IsLockedOut = false; user.FailedPasswordAttemptCount = 0; Store.Save(); } } } catch { throw; } return unlocked; } /// <summary> /// Updates information about a user in the data source. /// </summary> /// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"></see> object that represents the user to update and the updated information for the user.</param> /// <exception cref="T:System.ArgumentNullException">Thrown when user is <c>null</c></exception> public override void UpdateUser(MembershipUser user) { if (user == null) throw new ArgumentNullException(nameof(user)); // TODO should we allow username to be changed as well //if (this.VerifyUserNameIsUnique(user.UserName, (Guid)user.ProviderUserKey)) // throw new ArgumentException("UserName is not unique!"); if (RequiresUniqueEmail && !VerifyEmailIsUnique(user.Email, (Guid)user.ProviderUserKey)) { throw new ArgumentException("Email is not unique!"); } lock (SyncRoot) { var xuser = GetInternalUser(user.UserName); if (xuser != null) { xuser.Email = user.Email; xuser.LastActivityDate = user.LastActivityDate; xuser.LastLoginDate = user.LastLoginDate; xuser.Comment = user.Comment; xuser.IsApproved = user.IsApproved; Store.Save(); } else { throw new ProviderException("User does not exist!"); } } } #region - Helpers - /// <summary> /// Creates the membership from internal user. /// </summary> /// <param name="user">The user.</param> /// <returns></returns> private MembershipUser CreateMembershipFromInternalUser(User user) { return (user != null) ? new MembershipUser(Name, user.UserName, user.UserKey, user.Email, user.PasswordQuestion, user.Comment, user.IsApproved, user.IsLockedOut, user.CreationDate, user.LastLoginDate, user.LastActivityDate, user.LastPasswordChangeDate, user.LastLockoutDate) : null; } /// <summary> /// Creates the membership collection from internal list. /// </summary> /// <param name="users">The users.</param> /// <returns></returns> private MembershipUserCollection CreateMembershipCollectionFromInternalList(IEnumerable<User> users) { MembershipUserCollection returnCollection = new MembershipUserCollection(); foreach (User user in users) { returnCollection.Add(CreateMembershipFromInternalUser(user)); } return returnCollection; } /// <summary> /// Gets the internal user. /// </summary> /// <param name="username">The username.</param> /// <returns></returns> private User GetInternalUser(string username) { var comparison = Comparison; var query = from u in Users where u.UserName.Equals(username, comparison) select u; return query.FirstOrDefault(); } /// <summary> /// Tries the get password. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="salt">The salt.</param> /// <param name="question"></param> /// <param name="answer">The answer.</param> /// <returns></returns> protected override bool TryGetPassword(string username, out string password, out string salt, out string question, out string answer) { lock (SyncRoot) { User user = GetInternalUser(username); if (user != null) { password = user.Password; salt = user.PasswordSalt; question = user.PasswordQuestion; answer = user.PasswordAnswer; return true; } else { password = salt = question = answer = null; return false; } } } /// <summary> /// Tries the set password. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="salt">The salt.</param> /// <param name="question"></param> /// <param name="answer">The answer.</param> /// <returns></returns> protected override bool TrySetPassword(string username, string password, string salt, string question, string answer) { lock (SyncRoot) { User user = GetInternalUser(username); if (user != null) { user.LastPasswordChangeDate = UseUniversalTime ? DateTime.UtcNow : DateTime.Now; user.Password = password; user.PasswordSalt = salt; user.PasswordQuestion = question; user.PasswordAnswer = answer; Store.Save(); return true; } else { return false; } } } /// <summary> /// Updates the user info. /// </summary> /// <param name="username"></param> /// <param name="valid">if set to <c>true</c> [valid].</param> protected override void UpdateUserInfo(string username, bool valid) { try { lock (SyncRoot) { var user = GetInternalUser(username); if (user != null) { DateTime now = UseUniversalTime ? DateTime.UtcNow : DateTime.Now; user.LastActivityDate = now; if (valid) { user.LastLoginDate = now; user.FailedPasswordAttemptCount = 0; } else { user.FailedPasswordAttemptCount++; if (!user.IsLockedOut) { user.IsLockedOut = (user.FailedPasswordAttemptCount >= MaxInvalidPasswordAttempts); if (user.IsLockedOut) user.LastLockoutDate = now; } } Store.Save(); } } } catch { throw; } } #endregion /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception> /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException(nameof(config)); // prerequisites if (string.IsNullOrEmpty(name)) { name = "XmlMembershipProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "XML Membership Provider"); } // Initialize the abstract base class. base.Initialize(name, config); // initialize provider fields string fileName = config.GetString("fileName", "Users.xml"); string folder = config.GetString("folder", "~/App_Data/"); if (!folder.EndsWith("/")) folder += "/"; _file = HostingEnvironment.MapPath(string.Format("{0}{1}", folder, fileName)); } } public sealed class SaltedHash { private readonly string _salt; private readonly string _hash; private const int saltLength = 6; public string Salt { get { return _salt; } } public string Hash { get { return _hash; } } public static SaltedHash Create(string password) { string salt = CreateSalt(); string hash = CalculateHash(salt, password); return new SaltedHash(salt, hash); } public static SaltedHash Create(string salt, string hash) { return new SaltedHash(salt, hash); } public bool Verify(string password) { string h = CalculateHash(_salt, password); return _hash.Equals(h); } private SaltedHash(string s, string h) { _salt = s; _hash = h; } private static string CreateSalt() { byte[] r = CreateRandomBytes(saltLength); return Convert.ToBase64String(r); } private static byte[] CreateRandomBytes(int len) { byte[] r = new byte[len]; new RNGCryptoServiceProvider().GetBytes(r); return r; } private static string CalculateHash(string salt, string password) { byte[] data = ToByteArray(salt + password); byte[] hash = CalculateHash(data); return Convert.ToBase64String(hash); } private static byte[] CalculateHash(byte[] data) { return new SHA1CryptoServiceProvider().ComputeHash(data); } private static byte[] ToByteArray(string s) { return System.Text.Encoding.UTF8.GetBytes(s); } } }
//#define USE_SharpZipLib #if !UNITY_WEBPLAYER #define USE_FileIO #endif /* * * * * * A simple JSON Parser / builder * ------------------------------ * * It mainly has been written as a simple JSON parser. It can build a JSON string * from the node-tree, or generate a node tree from any valid JSON string. * * If you want to use compression when saving to file / stream / B64 you have to include * SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and * define "USE_SharpZipLib" at the top of the file * * Written by Bunny83 * 2012-06-09 * * Features / attributes: * - provides strongly typed node classes and lists / dictionaries * - provides easy access to class members / array items / data values * - the parser ignores data types. Each value is a string. * - only double quotes (") are used for quoting strings. * - values and names are not restricted to quoted strings. They simply add up and are trimmed. * - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData) * - provides "casting" properties to easily convert to / from those types: * int / float / double / bool * - provides a common interface for each node so no explicit casting is required. * - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined * * * 2012-12-17 Update: * - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree * Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator * The class determines the required type by it's further use, creates the type and removes itself. * - Added binary serialization / deserialization. * - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) * The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top * - The serializer uses different types when it comes to store the values. Since my data values * are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string. * It's not the most efficient way but for a moderate amount of data it should work on all platforms. * * * * * */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace SimpleJSON { public enum JSONBinaryTag { Array = 1, Class = 2, Value = 3, IntValue = 4, DoubleValue = 5, BoolValue = 6, FloatValue = 7, } public class JSONNode { #region common interface public virtual void Add(string aKey, JSONNode aItem){ } public virtual JSONNode this[int aIndex] { get { return null; } set { } } public virtual JSONNode this[string aKey] { get { return null; } set { } } public virtual string Value { get { return ""; } set { } } public virtual int Count { get { return 0; } } public virtual void Add(JSONNode aItem) { Add("", aItem); } public virtual JSONNode Remove(string aKey) { return null; } public virtual JSONNode Remove(int aIndex) { return null; } public virtual JSONNode Remove(JSONNode aNode) { return aNode; } public virtual IEnumerable<JSONNode> Childs { get { yield break;} } public IEnumerable<JSONNode> DeepChilds { get { foreach (var C in Childs) foreach (var D in C.DeepChilds) yield return D; } } public override string ToString() { return "JSONNode"; } public virtual string ToString(string aPrefix) { return "JSONNode"; } #endregion common interface #region typecasting properties public virtual int AsInt { get { int v = 0; if (int.TryParse(Value,out v)) return v; return 0; } set { Value = value.ToString(); } } public virtual float AsFloat { get { float v = 0.0f; if (float.TryParse(Value,out v)) return v; return 0.0f; } set { Value = value.ToString(); } } public virtual double AsDouble { get { double v = 0.0; if (double.TryParse(Value,out v)) return v; return 0.0; } set { Value = value.ToString(); } } public virtual bool AsBool { get { bool v = false; if (bool.TryParse(Value,out v)) return v; return !string.IsNullOrEmpty(Value); } set { Value = (value)?"true":"false"; } } public virtual JSONArray AsArray { get { return this as JSONArray; } } public virtual JSONClass AsObject { get { return this as JSONClass; } } #endregion typecasting properties #region operators public static implicit operator JSONNode(string s) { return new JSONData(s); } public static implicit operator string(JSONNode d) { return (d == null)?null:d.Value; } public static bool operator ==(JSONNode a, object b) { if (b == null && a is JSONLazyCreator) return true; return System.Object.ReferenceEquals(a,b); } public static bool operator !=(JSONNode a, object b) { return !(a == b); } public override bool Equals (object obj) { return System.Object.ReferenceEquals(this, obj); } public override int GetHashCode () { return base.GetHashCode(); } #endregion operators internal static string Escape(string aText) { string result = ""; foreach(char c in aText) { switch(c) { case '\\' : result += "\\\\"; break; case '\"' : result += "\\\""; break; case '\n' : result += "\\n" ; break; case '\r' : result += "\\r" ; break; case '\t' : result += "\\t" ; break; case '\b' : result += "\\b" ; break; case '\f' : result += "\\f" ; break; default : result += c ; break; } } return result; } public static JSONNode Parse(string aJSON) { Stack<JSONNode> stack = new Stack<JSONNode>(); JSONNode ctx = null; int i = 0; string Token = ""; string TokenName = ""; bool QuoteMode = false; while (i < aJSON.Length) { switch (aJSON[i]) { case '{': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new JSONClass()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(stack.Peek()); else if (TokenName != "") ctx.Add(TokenName,stack.Peek()); } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '[': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new JSONArray()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(stack.Peek()); else if (TokenName != "") ctx.Add(TokenName,stack.Peek()); } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '}': case ']': if (QuoteMode) { Token += aJSON[i]; break; } if (stack.Count == 0) throw new Exception("JSON Parse: Too many closing brackets"); stack.Pop(); if (Token != "") { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(Token); else if (TokenName != "") ctx.Add(TokenName,Token); } TokenName = ""; Token = ""; if (stack.Count>0) ctx = stack.Peek(); break; case ':': if (QuoteMode) { Token += aJSON[i]; break; } TokenName = Token; Token = ""; break; case '"': QuoteMode ^= true; break; case ',': if (QuoteMode) { Token += aJSON[i]; break; } if (Token != "") { if (ctx is JSONArray) ctx.Add(Token); else if (TokenName != "") ctx.Add(TokenName, Token); } TokenName = ""; Token = ""; break; case '\r': case '\n': break; case ' ': case '\t': if (QuoteMode) Token += aJSON[i]; break; case '\\': ++i; if (QuoteMode) { char C = aJSON[i]; switch (C) { case 't' : Token += '\t'; break; case 'r' : Token += '\r'; break; case 'n' : Token += '\n'; break; case 'b' : Token += '\b'; break; case 'f' : Token += '\f'; break; case 'u': { string s = aJSON.Substring(i+1,4); Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier); i += 4; break; } default : Token += C; break; } } break; default: Token += aJSON[i]; break; } ++i; } if (QuoteMode) { throw new Exception("JSON Parse: Quotation marks seems to be messed up."); } return ctx; } public virtual void Serialize(System.IO.BinaryWriter aWriter) {} public void SaveToStream(System.IO.Stream aData) { var W = new System.IO.BinaryWriter(aData); Serialize(W); } #if USE_SharpZipLib public void SaveToCompressedStream(System.IO.Stream aData) { using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData)) { gzipOut.IsStreamOwner = false; SaveToStream(gzipOut); gzipOut.Close(); } } public void SaveToCompressedFile(string aFileName) { #if USE_FileIO System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName); using(var F = System.IO.File.OpenWrite(aFileName)) { SaveToCompressedStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public string SaveToCompressedBase64() { using (var stream = new System.IO.MemoryStream()) { SaveToCompressedStream(stream); stream.Position = 0; return System.Convert.ToBase64String(stream.ToArray()); } } #else public void SaveToCompressedStream(System.IO.Stream aData) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public void SaveToCompressedFile(string aFileName) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } // public string SaveToCompressedBase64() // { // throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); // } #endif public void SaveToFile(string aFileName) { #if USE_FileIO System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName); using(var F = System.IO.File.OpenWrite(aFileName)) { SaveToStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public string SaveToBase64() { using (var stream = new System.IO.MemoryStream()) { SaveToStream(stream); stream.Position = 0; return System.Convert.ToBase64String(stream.ToArray()); } } public static JSONNode Deserialize(System.IO.BinaryReader aReader) { JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte(); switch(type) { case JSONBinaryTag.Array: { int count = aReader.ReadInt32(); JSONArray tmp = new JSONArray(); for(int i = 0; i < count; i++) tmp.Add(Deserialize(aReader)); return tmp; } case JSONBinaryTag.Class: { int count = aReader.ReadInt32(); JSONClass tmp = new JSONClass(); for(int i = 0; i < count; i++) { string key = aReader.ReadString(); var val = Deserialize(aReader); tmp.Add(key, val); } return tmp; } case JSONBinaryTag.Value: { return new JSONData(aReader.ReadString()); } case JSONBinaryTag.IntValue: { return new JSONData(aReader.ReadInt32()); } case JSONBinaryTag.DoubleValue: { return new JSONData(aReader.ReadDouble()); } case JSONBinaryTag.BoolValue: { return new JSONData(aReader.ReadBoolean()); } case JSONBinaryTag.FloatValue: { return new JSONData(aReader.ReadSingle()); } default: { throw new Exception("Error deserializing JSON. Unknown tag: " + type); } } } #if USE_SharpZipLib public static JSONNode LoadFromCompressedStream(System.IO.Stream aData) { var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData); return LoadFromStream(zin); } public static JSONNode LoadFromCompressedFile(string aFileName) { #if USE_FileIO using(var F = System.IO.File.OpenRead(aFileName)) { return LoadFromCompressedStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public static JSONNode LoadFromCompressedBase64(string aBase64) { var tmp = System.Convert.FromBase64String(aBase64); var stream = new System.IO.MemoryStream(tmp); stream.Position = 0; return LoadFromCompressedStream(stream); } #else public static JSONNode LoadFromCompressedFile(string aFileName) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public static JSONNode LoadFromCompressedStream(System.IO.Stream aData) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public static JSONNode LoadFromCompressedBase64(string aBase64) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } #endif public static JSONNode LoadFromStream(System.IO.Stream aData) { using(var R = new System.IO.BinaryReader(aData)) { return Deserialize(R); } } public static JSONNode LoadFromFile(string aFileName) { #if USE_FileIO using(var F = System.IO.File.OpenRead(aFileName)) { return LoadFromStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public static JSONNode LoadFromBase64(string aBase64) { var tmp = System.Convert.FromBase64String(aBase64); var stream = new System.IO.MemoryStream(tmp); stream.Position = 0; return LoadFromStream(stream); } } // End of JSONNode public class JSONArray : JSONNode, IEnumerable { private List<JSONNode> m_List = new List<JSONNode>(); public override JSONNode this[int aIndex] { get { if (aIndex<0 || aIndex >= m_List.Count) return new JSONLazyCreator(this); return m_List[aIndex]; } set { if (aIndex<0 || aIndex >= m_List.Count) m_List.Add(value); else m_List[aIndex] = value; } } public override JSONNode this[string aKey] { get{ return new JSONLazyCreator(this);} set{ m_List.Add(value); } } public override int Count { get { return m_List.Count; } } public override void Add(string aKey, JSONNode aItem) { m_List.Add(aItem); } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_List.Count) return null; JSONNode tmp = m_List[aIndex]; m_List.RemoveAt(aIndex); return tmp; } public override JSONNode Remove(JSONNode aNode) { m_List.Remove(aNode); return aNode; } public override IEnumerable<JSONNode> Childs { get { foreach(JSONNode N in m_List) yield return N; } } public IEnumerator GetEnumerator() { foreach(JSONNode N in m_List) yield return N; } public override string ToString() { string result = "[ "; foreach (JSONNode N in m_List) { if (result.Length > 2) result += ", "; result += N.ToString(); } result += " ]"; return result; } public override string ToString(string aPrefix) { string result = "[ "; foreach (JSONNode N in m_List) { if (result.Length > 3) result += ", "; result += "\n" + aPrefix + " "; result += N.ToString(aPrefix+" "); } result += "\n" + aPrefix + "]"; return result; } public override void Serialize (System.IO.BinaryWriter aWriter) { aWriter.Write((byte)JSONBinaryTag.Array); aWriter.Write(m_List.Count); for(int i = 0; i < m_List.Count; i++) { m_List[i].Serialize(aWriter); } } } // End of JSONArray public class JSONClass : JSONNode, IEnumerable { private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>(); public override JSONNode this[string aKey] { get { if (m_Dict.ContainsKey(aKey)) return m_Dict[aKey]; else return new JSONLazyCreator(this, aKey); } set { if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = value; else m_Dict.Add(aKey,value); } } public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; return m_Dict.ElementAt(aIndex).Value; } set { if (aIndex < 0 || aIndex >= m_Dict.Count) return; string key = m_Dict.ElementAt(aIndex).Key; m_Dict[key] = value; } } public override int Count { get { return m_Dict.Count; } } public override void Add(string aKey, JSONNode aItem) { if (!string.IsNullOrEmpty(aKey)) { if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = aItem; else m_Dict.Add(aKey, aItem); } else m_Dict.Add(Guid.NewGuid().ToString(), aItem); } public override JSONNode Remove(string aKey) { if (!m_Dict.ContainsKey(aKey)) return null; JSONNode tmp = m_Dict[aKey]; m_Dict.Remove(aKey); return tmp; } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; var item = m_Dict.ElementAt(aIndex); m_Dict.Remove(item.Key); return item.Value; } public override JSONNode Remove(JSONNode aNode) { try { var item = m_Dict.Where(k => k.Value == aNode).First(); m_Dict.Remove(item.Key); return aNode; } catch { return null; } } public override IEnumerable<JSONNode> Childs { get { foreach(KeyValuePair<string,JSONNode> N in m_Dict) yield return N.Value; } } public IEnumerator GetEnumerator() { foreach(KeyValuePair<string, JSONNode> N in m_Dict) yield return N; } public override string ToString() { string result = "{"; foreach (KeyValuePair<string, JSONNode> N in m_Dict) { if (result.Length > 2) result += ", "; result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString(); } result += "}"; return result; } public override string ToString(string aPrefix) { string result = "{ "; foreach (KeyValuePair<string, JSONNode> N in m_Dict) { if (result.Length > 3) result += ", "; result += "\n" + aPrefix + " "; result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" "); } result += "\n" + aPrefix + "}"; return result; } public override void Serialize (System.IO.BinaryWriter aWriter) { aWriter.Write((byte)JSONBinaryTag.Class); aWriter.Write(m_Dict.Count); foreach(string K in m_Dict.Keys) { aWriter.Write(K); m_Dict[K].Serialize(aWriter); } } } // End of JSONClass public class JSONData : JSONNode { private string m_Data; public override string Value { get { return m_Data; } set { m_Data = value; } } public JSONData(string aData) { m_Data = aData; } public JSONData(float aData) { AsFloat = aData; } public JSONData(double aData) { AsDouble = aData; } public JSONData(bool aData) { AsBool = aData; } public JSONData(int aData) { AsInt = aData; } public override string ToString() { return "\"" + Escape(m_Data) + "\""; } public override string ToString(string aPrefix) { return "\"" + Escape(m_Data) + "\""; } public override void Serialize (System.IO.BinaryWriter aWriter) { var tmp = new JSONData(""); tmp.AsInt = AsInt; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.IntValue); aWriter.Write(AsInt); return; } tmp.AsFloat = AsFloat; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.FloatValue); aWriter.Write(AsFloat); return; } tmp.AsDouble = AsDouble; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.DoubleValue); aWriter.Write(AsDouble); return; } tmp.AsBool = AsBool; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.BoolValue); aWriter.Write(AsBool); return; } aWriter.Write((byte)JSONBinaryTag.Value); aWriter.Write(m_Data); } } // End of JSONData internal class JSONLazyCreator : JSONNode { private JSONNode m_Node = null; private string m_Key = null; public JSONLazyCreator(JSONNode aNode) { m_Node = aNode; m_Key = null; } public JSONLazyCreator(JSONNode aNode, string aKey) { m_Node = aNode; m_Key = aKey; } private void Set(JSONNode aVal) { if (m_Key == null) { m_Node.Add(aVal); } else { m_Node.Add(m_Key, aVal); } m_Node = null; // Be GC friendly. } public override JSONNode this[int aIndex] { get { return new JSONLazyCreator(this); } set { var tmp = new JSONArray(); tmp.Add(value); Set(tmp); } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this, aKey); } set { var tmp = new JSONClass(); tmp.Add(aKey, value); Set(tmp); } } public override void Add (JSONNode aItem) { var tmp = new JSONArray(); tmp.Add(aItem); Set(tmp); } public override void Add (string aKey, JSONNode aItem) { var tmp = new JSONClass(); tmp.Add(aKey, aItem); Set(tmp); } public static bool operator ==(JSONLazyCreator a, object b) { if (b == null) return true; return System.Object.ReferenceEquals(a,b); } public static bool operator !=(JSONLazyCreator a, object b) { return !(a == b); } public override bool Equals (object obj) { if (obj == null) return true; return System.Object.ReferenceEquals(this, obj); } public override int GetHashCode () { return base.GetHashCode(); } public override string ToString() { return ""; } public override string ToString(string aPrefix) { return ""; } public override int AsInt { get { JSONData tmp = new JSONData(0); Set(tmp); return 0; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override float AsFloat { get { JSONData tmp = new JSONData(0.0f); Set(tmp); return 0.0f; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override double AsDouble { get { JSONData tmp = new JSONData(0.0); Set(tmp); return 0.0; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override bool AsBool { get { JSONData tmp = new JSONData(false); Set(tmp); return false; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override JSONArray AsArray { get { JSONArray tmp = new JSONArray(); Set(tmp); return tmp; } } public override JSONClass AsObject { get { JSONClass tmp = new JSONClass(); Set(tmp); return tmp; } } } // End of JSONLazyCreator public static class JSON { public static JSONNode Parse(string aJSON) { return JSONNode.Parse(aJSON); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Mercurial.Configuration; using Mercurial.Versions; namespace Mercurial { /// <summary> /// This class encapsulates the Mercurial client application. /// </summary> public static class ClientExecutable { /// <summary> /// Indicates whether it is running on Windows or not. /// </summary> /// <value> /// True on Windows, false on elsewhere. /// </value> static bool IsWindows { get { switch (Environment.OSVersion.Platform) { case PlatformID.MacOSX: case PlatformID.Unix: return false; default: return true; } } } /// <summary> /// Gets the mercurial executable. /// </summary> /// <value> /// The mercurial executable. /// </value> public static string MercurialExecutable { get { return IsWindows ? "hg.exe" : "hg"; } } /// <summary> /// Gets the platform environment separator. /// </summary> /// <value> /// The platform environment separator. /// </value> public static char PlatformEnvironmentPathSeparator { get { return IsWindows ? ';' : ':'; } } public static Encoding TextEncoding { get { return text_encoding; } } // FIXME: current implementation could generate garbage for UTF8 BOMs. But // CommandServerOutputDecoder.DecodeOneBlock() hangs when we use UTF8. //static readonly Encoding text_encoding = IsWindows ? Encoding.GetEncoding ("iso-8859-1") : new UTF8Encoding (true, false); static readonly Encoding text_encoding = Encoding.GetEncoding ("iso-8859-1"); public static string TextEncodingName { get { return text_encoding.BodyName; } } /// <summary> /// If <c>true</c>, then the <see cref="LazyInitialize"/> method has executed, possibly unable /// to locate the client. /// </summary> private static bool _LazyInitializationExecuted; /// <summary> /// This is the backing field for the <see cref="ClientPath"/> property. /// </summary> private static string _ClientPath; /// <summary> /// This is the backing field for the <see cref="Configuration"/> property. /// </summary> private static ClientConfigurationCollection _Configuration; /// <summary> /// This is the backing field for the <see cref="CurrentVersion"/> property. /// </summary> private static Version _CurrentVersion; /// <summary> /// Gets a collection of supported versions of the Mercurial client. /// </summary> public static IEnumerable<Version> SupportedVersions { get { yield return new Version(1, 6, 0, 0); yield return new Version(1, 6, 1, 0); yield return new Version(1, 6, 2, 0); yield return new Version(1, 6, 3, 0); yield return new Version(1, 7, 0, 0); yield return new Version(1, 7, 1, 0); yield return new Version(1, 7, 2, 0); yield return new Version(1, 7, 3, 0); yield return new Version(1, 7, 4, 0); yield return new Version(1, 7, 5, 0); yield return new Version(1, 8, 0, 0); yield return new Version(1, 8, 1, 0); yield return new Version(1, 8, 2, 0); yield return new Version(1, 8, 3, 0); yield return new Version(1, 8, 4, 0); yield return new Version(1, 9, 0, 0); yield return new Version(1, 9, 1, 0); yield return new Version(1, 9, 2, 0); yield return new Version(1, 9, 3, 0); yield return new Version(2, 0, 0, 0); yield return new Version(2, 0, 1, 0); yield return new Version(2, 0, 2, 0); yield return new Version(2, 1, 0, 0); } } /// <summary> /// Gets the path to the Mercurial client executable. /// </summary> public static string ClientPath { get { LazyInitialize(); return _ClientPath; } private set { _ClientPath = value; } } /// <summary> /// Gets a value indicating whether the Mercurial client executable could be located or not. /// </summary> public static bool CouldLocateClient { get { LazyInitialize(); return !StringEx.IsNullOrWhiteSpace(ClientPath); } } /// <summary> /// Perform lazy on-demand initialization of locating the client and extracting its version. /// </summary> internal static void LazyInitialize() { if (!_LazyInitializationExecuted) { _LazyInitializationExecuted = true; ClientPath = LocateClient(); Initialize(); } } /// <summary> /// Gets the current client configuration. /// </summary> /// <exception cref="InvalidOperationException"> /// The Mercurial client configuration is not available because the client executable could not be located. /// </exception> public static ClientConfigurationCollection Configuration { get { LazyInitialize(); if (!CouldLocateClient) throw new InvalidOperationException( "The Mercurial client configuration is not available because the client executable could not be located"); return _Configuration; } } /// <summary> /// Gets the version of the Mercurial client installed and in use, that was detected during /// startup of the Mercurial.Net library, or overriden through the use of <see cref="SetClientPath"/>. /// </summary> /// <remarks> /// Note that this value is cached from startup/override time, and does not execute the executable when /// you read it. If you want a fresh, up-to-date value, use the <see cref="GetVersion"/> method instead. /// </remarks> public static Version CurrentVersion { get { LazyInitialize(); return _CurrentVersion; } private set { _CurrentVersion = value; } } /// <summary> /// Initializes local data structures from the Mercurial client. /// </summary> private static void Initialize() { if (!StringEx.IsNullOrWhiteSpace(ClientPath)) { _Configuration = new ClientConfigurationCollection(); CurrentVersion = GetVersion(); MercurialVersionBase.AssignCurrent(CurrentVersion); _Configuration.Refresh(); } else { _Configuration = null; CurrentVersion = null; } } /// <summary> /// Assigns a specific client path to the Mercurial.Net library, allowing /// the program that uses the library to select the applicable /// Mercurial version to use, or even to come bundled with its own Mercurial /// client files. /// </summary> /// <param name="clientPath"> /// The full path to the folder and file that is the /// Mercurial command line executable that should be used. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="clientPath"/> is <c>null</c> or empty.</para> /// </exception> /// <exception cref="ArgumentException"> /// <para><paramref name="clientPath"/> does not point to the Mercurial executable.</para> /// </exception> public static void SetClientPath(string clientPath) { if (StringEx.IsNullOrWhiteSpace(clientPath)) throw new ArgumentNullException("clientPath"); if (Directory.Exists(clientPath) && File.Exists(Path.Combine(clientPath, MercurialExecutable))) clientPath = Path.Combine(clientPath, MercurialExecutable); if (!File.Exists(clientPath)) throw new ArgumentException("The specified path does not contain the Mercurial executable"); ClientPath = clientPath; Initialize(); } /// <summary> /// Gets the version of the Mercurial client installed and in use. Note that <see cref="System.Version.Revision"/> /// and <see cref="System.Version.Build"/> can be 0 for major and minor versions of Mercurial. /// </summary> /// <returns> /// The <see cref="System.Version"/> of the Mercurial client installed and in use. /// </returns> /// <exception cref="InvalidOperationException"> /// <para>Unable to find or interpret version number from the Mercurial client.</para> /// </exception> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Since reading the version means executing an external program, a property is not the way to go.")] public static Version GetVersion() { LazyInitialize(); var command = new VersionCommand(); NonPersistentClient.Execute(command); string firstLine = command.Result.Split( new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).First(); var re = new Regex(@"\(version\s+(?<version>[0-9.]+)(-rc)?(\+\d+-[a-f0-9]+)?\)", RegexOptions.IgnoreCase); Match ma = re.Match(firstLine); if (!ma.Success) throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Unable to locate Mercurial version number in '{0}'", firstLine)); string versionString = ma.Groups["version"].Value; switch (versionString.Split('.').Length) { case 1: return new Version(string.Format(CultureInfo.InvariantCulture, "{0}.0.0.0", versionString)); case 2: return new Version(string.Format(CultureInfo.InvariantCulture, "{0}.0.0", versionString)); case 3: return new Version(string.Format(CultureInfo.InvariantCulture, "{0}.0", versionString)); case 4: return new Version(versionString); default: throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Incorrect version number length, too many or too few parts: {0}", versionString)); } } /// <summary> /// Initializes a repository remotely, through a server which supports such functionality. /// </summary> /// <param name="location"> /// The url of the repository to initialize remotely. /// </param> /// <param name="command"> /// Any extra options to the init method, or <c>null</c> for default options. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="location"/> is <c>null</c> or empty.</para> /// </exception> /// <exception cref="ArgumentException"> /// <para><see cref="RemoteInitCommand.Location"/> cannot be set before calling this method.</para> /// </exception> public static void RemoteInit(string location, RemoteInitCommand command = null) { if (StringEx.IsNullOrWhiteSpace(location)) throw new ArgumentNullException("location"); if (command != null && !StringEx.IsNullOrWhiteSpace(command.Location)) throw new ArgumentException("RemoteInitCommand.Location cannot be set before calling this method", "command"); command = (command ?? new RemoteInitCommand()) .WithLocation(location); NonPersistentClient.Execute(command); } /// <summary> /// Initializes a repository remotely, through a server which supports such functionality. /// </summary> /// <param name="command"> /// The options to the init method. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="command"/> is <c>null</c>.</para> /// </exception> public static void RemoteInit(RemoteInitCommand command) { if (command == null) throw new ArgumentNullException("command"); NonPersistentClient.Execute(command); } /// <summary> /// Attempts to locate the command line client executable. /// </summary> /// <returns> /// The full path to the client executable, or <c>null</c> if it could not be located. /// </returns> private static string LocateClient() { string environmentPath = Environment.GetEnvironmentVariable("PATH"); if (string.IsNullOrEmpty(environmentPath)) return null; return (from path in environmentPath.Split(PlatformEnvironmentPathSeparator) where !StringEx.IsNullOrWhiteSpace(path) let executablePath = Path.Combine(path.Trim(), MercurialExecutable) where File.Exists(executablePath) select executablePath).FirstOrDefault(); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Collections; using System.Diagnostics; #if !HAVE_LINQ using Microsoft.Identity.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Globalization; #if HAVE_METHOD_IMPL_ATTRIBUTE using System.Runtime.CompilerServices; #endif using Microsoft.Identity.Json.Serialization; namespace Microsoft.Identity.Json.Utilities { internal static class CollectionUtils { /// <summary> /// Determines whether the collection is <c>null</c> or empty. /// </summary> /// <param name="collection">The collection.</param> /// <returns> /// <c>true</c> if the collection is <c>null</c> or empty; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty<T>(ICollection<T> collection) { if (collection != null) { return collection.Count == 0; } return true; } /// <summary> /// Adds the elements of the specified collection to the specified generic <see cref="IList{T}"/>. /// </summary> /// <param name="initial">The list to add to.</param> /// <param name="collection">The collection of elements to add.</param> public static void AddRange<T>(this IList<T> initial, IEnumerable<T> collection) { if (initial == null) { throw new ArgumentNullException(nameof(initial)); } if (collection == null) { return; } foreach (T value in collection) { initial.Add(value); } } #if !HAVE_COVARIANT_GENERICS public static void AddRange<T>(this IList<T> initial, IEnumerable collection) { ValidationUtils.ArgumentNotNull(initial, nameof(initial)); // because earlier versions of .NET didn't support covariant generics initial.AddRange(collection.Cast<T>()); } #endif public static bool IsDictionaryType(Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); if (typeof(IDictionary).IsAssignableFrom(type)) { return true; } if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary<,>))) { return true; } #if HAVE_READ_ONLY_COLLECTIONS if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IReadOnlyDictionary<,>))) { return true; } #endif return false; } public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) { Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType); return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument); } public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) { Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType); ConstructorInfo match = null; foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) { IList<ParameterInfo> parameters = constructor.GetParameters(); if (parameters.Count == 1) { Type parameterType = parameters[0].ParameterType; if (genericEnumerable == parameterType) { // exact match match = constructor; break; } // in case we can't find an exact match, use first inexact if (match == null) { if (parameterType.IsAssignableFrom(constructorArgumentType)) { match = constructor; } } } } return match; } public static bool AddDistinct<T>(this IList<T> list, T value) { return list.AddDistinct(value, EqualityComparer<T>.Default); } public static bool AddDistinct<T>(this IList<T> list, T value, IEqualityComparer<T> comparer) { if (list.ContainsValue(value, comparer)) { return false; } list.Add(value); return true; } // this is here because LINQ Bridge doesn't support Contains with IEqualityComparer<T> public static bool ContainsValue<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer) { if (comparer == null) { comparer = EqualityComparer<TSource>.Default; } if (source == null) { throw new ArgumentNullException(nameof(source)); } foreach (TSource local in source) { if (comparer.Equals(local, value)) { return true; } } return false; } public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values, IEqualityComparer<T> comparer) { bool allAdded = true; foreach (T value in values) { if (!list.AddDistinct(value, comparer)) { allAdded = false; } } return allAdded; } public static int IndexOf<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { int index = 0; foreach (T value in collection) { if (predicate(value)) { return index; } index++; } return -1; } public static bool Contains<T>(this List<T> list, T value, IEqualityComparer comparer) { for (int i = 0; i < list.Count; i++) { if (comparer.Equals(value, list[i])) { return true; } } return false; } public static int IndexOfReference<T>(this List<T> list, T item) { for (int i = 0; i < list.Count; i++) { if (ReferenceEquals(item, list[i])) { return i; } } return -1; } #if HAVE_FAST_REVERSE // faster reverse in .NET Framework with value types - https://github.com/JamesNK/Microsoft.Identity.Json/issues/1430 public static void FastReverse<T>(this List<T> list) { int i = 0; int j = list.Count - 1; while (i < j) { T temp = list[i]; list[i] = list[j]; list[j] = temp; i++; j--; } } #endif private static IList<int> GetDimensions(IList values, int dimensionsCount) { IList<int> dimensions = new List<int>(); IList currentArray = values; while (true) { dimensions.Add(currentArray.Count); // don't keep calculating dimensions for arrays inside the value array if (dimensions.Count == dimensionsCount) { break; } if (currentArray.Count == 0) { break; } object v = currentArray[0]; if (v is IList list) { currentArray = list; } else { break; } } return dimensions; } private static void CopyFromJaggedToMultidimensionalArray(IList values, Array multidimensionalArray, int[] indices) { int dimension = indices.Length; if (dimension == multidimensionalArray.Rank) { multidimensionalArray.SetValue(JaggedArrayGetValue(values, indices), indices); return; } int dimensionLength = multidimensionalArray.GetLength(dimension); IList list = (IList)JaggedArrayGetValue(values, indices); int currentValuesLength = list.Count; if (currentValuesLength != dimensionLength) { #pragma warning disable CA2201 // Do not raise reserved exception types throw new Exception("Cannot deserialize non-cubical array as multidimensional array."); #pragma warning restore CA2201 // Do not raise reserved exception types } int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) { newIndices[i] = indices[i]; } for (int i = 0; i < multidimensionalArray.GetLength(dimension); i++) { newIndices[dimension] = i; CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, newIndices); } } private static object JaggedArrayGetValue(IList values, int[] indices) { IList currentList = values; for (int i = 0; i < indices.Length; i++) { int index = indices[i]; if (i == indices.Length - 1) { return currentList[index]; } else { currentList = (IList)currentList[index]; } } return currentList; } public static Array ToMultidimensionalArray(IList values, Type type, int rank) { IList<int> dimensions = GetDimensions(values, rank); while (dimensions.Count < rank) { dimensions.Add(0); } Array multidimensionalArray = Array.CreateInstance(type, dimensions.ToArray()); CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, ArrayEmpty<int>()); return multidimensionalArray; } // 4.6 has Array.Empty<T> to return a cached empty array. Lacking that in other // frameworks, Enumerable.Empty<T> happens to be implemented as a cached empty // array in all versions (in .NET Core the same instance as Array.Empty<T>). // This includes the internal Linq bridge for 2.0. // Since this method is simple and only 11 bytes long in a release build it's // pretty much guaranteed to be inlined, giving us fast access of that cached // array. With 4.5 and up we use AggressiveInlining just to be sure, so it's // effectively the same as calling Array.Empty<T> even when not available. #if HAVE_METHOD_IMPL_ATTRIBUTE [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static T[] ArrayEmpty<T>() { T[] array = Enumerable.Empty<T>() as T[]; Debug.Assert(array != null); // Defensively guard against a version of Linq where Enumerable.Empty<T> doesn't // return an array, but throw in debug versions so a better strategy can be // used if that ever happens. return array ?? new T[0]; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32; namespace Microsoft.PythonTools.Interpreter { [Export(typeof(IInterpreterOptionsService))] [PartCreationPolicy(CreationPolicy.Shared)] sealed class InterpreterOptionsService : IInterpreterOptionsService { private readonly Lazy<IInterpreterRegistryService> _registryService; private readonly Lazy<CPythonInterpreterFactoryProvider> _cpythonProvider; private readonly Lazy<IPackageManagerProvider>[] _packageManagerProviders; private bool _defaultInterpreterWatched; private string _defaultInterpreterId; IPythonInterpreterFactory _defaultInterpreter; private readonly object _defaultInterpreterLock = new object(); private EventHandler _defaultInterpreterChanged; private int _requireDefaultInterpreterChangeEvent; private int _suppressDefaultInterpreterChangeEvent; // The second is a static registry entry for the local machine and/or // the current user (HKCU takes precedence), intended for being set by // other installers. private const string DefaultInterpreterOptionsCollection = @"SOFTWARE\\Microsoft\\PythonTools\\Interpreters"; private const string DefaultInterpreterSetting = "DefaultInterpreter"; private const string PathKey = "ExecutablePath"; private const string WindowsPathKey = "WindowedExecutablePath"; private const string ArchitectureKey = "SysArchitecture"; private const string VersionKey = "SysVersion"; private const string PathEnvVarKey = "PathEnvironmentVariable"; private const string DescriptionKey = "DisplayName"; private const string CustomCompany = "VisualStudio"; private const string CustomInterpreterKey = "SOFTWARE\\Python\\" + CustomCompany; [ImportingConstructor] public InterpreterOptionsService( [Import] Lazy<IInterpreterRegistryService> registryService, [Import] Lazy<CPythonInterpreterFactoryProvider> cpythonProvider, [ImportMany] Lazy<IPackageManagerProvider>[] packageManagerProviders ) { _registryService = registryService; _cpythonProvider = cpythonProvider; _packageManagerProviders = packageManagerProviders; } private void InitializeDefaultInterpreterWatcher() { Debug.Assert(!_defaultInterpreterWatched); _registryService.Value.InterpretersChanged += Provider_InterpreterFactoriesChanged; RegistryHive hive = RegistryHive.CurrentUser; RegistryView view = RegistryView.Default; if (RegistryWatcher.Instance.TryAdd( hive, view, DefaultInterpreterOptionsCollection, DefaultInterpreterRegistry_Changed, recursive: false, notifyValueChange: true, notifyKeyChange: false ) == null) { // DefaultInterpreterOptions subkey does not exist yet, so // create it and then start the watcher. SaveDefaultInterpreterId(); RegistryWatcher.Instance.Add( hive, view, DefaultInterpreterOptionsCollection, DefaultInterpreterRegistry_Changed, recursive: false, notifyValueChange: true, notifyKeyChange: false ); } _defaultInterpreterWatched = true; } private void Provider_InterpreterFactoriesChanged(object sender, EventArgs e) { // reload the default interpreter ID and see if it changed... SetDefaultInterpreter(LoadDefaultInterpreterId(), null); } private void DefaultInterpreterRegistry_Changed(object sender, RegistryChangedEventArgs e) { try { SetDefaultInterpreter(LoadDefaultInterpreterId(), null); } catch (InvalidComObjectException) { // Race between VS closing and accessing the settings store. } catch (Exception ex) { try { //ActivityLog.LogError( // "Python Tools for Visual Studio", // string.Format("Exception updating default interpreter: {0}", ex) //); } catch (InvalidOperationException) { // Can't get the activity log service either. This probably // means we're being used from outside of VS, but also // occurs during some unit tests. We want to debug this if // possible, but generally avoid crashing. Debug.Fail(ex.ToString()); } } } private string LoadDefaultInterpreterId() { string id; using (var interpreterOptions = Registry.CurrentUser.OpenSubKey(DefaultInterpreterOptionsCollection)) { id = interpreterOptions?.GetValue(DefaultInterpreterSetting) as string; } InterpreterConfiguration newDefault = null; if (!string.IsNullOrEmpty(id)) { newDefault = _registryService.Value.FindConfiguration(id); } if (newDefault == null) { var defaultConfig = _registryService.Value.Configurations .Where(PythonInterpreterFactoryExtensions.IsRunnable) .LastOrDefault(c => c.CanBeAutoDefault()); id = defaultConfig?.Id; if (!string.IsNullOrEmpty(id)) { using (var interpreterOptions = Registry.CurrentUser.CreateSubKey(DefaultInterpreterOptionsCollection)) { interpreterOptions?.SetValue(DefaultInterpreterSetting, id); } } } return id ?? string.Empty; } private void SaveDefaultInterpreterId() { var id = _defaultInterpreterId; BeginSuppressDefaultInterpreterChangeEvent(); try { using (var interpreterOptions = Registry.CurrentUser.CreateSubKey(DefaultInterpreterOptionsCollection, true)) { if (string.IsNullOrEmpty(id)) { interpreterOptions.DeleteValue(DefaultInterpreterSetting, false); } else { Debug.Assert(!InterpreterRegistryConstants.IsNoInterpretersFactory(id)); interpreterOptions.SetValue(DefaultInterpreterSetting, id); } } } finally { EndSuppressDefaultInterpreterChangeEvent(); } } private void SetDefaultInterpreter(string id, IPythonInterpreterFactory factory) { id = id ?? factory?.Configuration?.Id ?? string.Empty; BeginSuppressDefaultInterpreterChangeEvent(); try { lock (_defaultInterpreterLock) { if (_defaultInterpreterId == id) { return; } if (string.IsNullOrEmpty(id) && _defaultInterpreterId == null) { return; } if (string.IsNullOrEmpty(id)) { _defaultInterpreter = null; } else { _defaultInterpreter = factory; } _defaultInterpreterId = id; SaveDefaultInterpreterId(); } OnDefaultInterpreterChanged(); } finally { EndSuppressDefaultInterpreterChangeEvent(); } } public string DefaultInterpreterId { get { if (_defaultInterpreterId == null) { _defaultInterpreterId = LoadDefaultInterpreterId(); } return _defaultInterpreterId; } set { SetDefaultInterpreter(value, null); } } public IPythonInterpreterFactory DefaultInterpreter { get { IPythonInterpreterFactory factory = _defaultInterpreter; if (factory != null) { // We've loaded and found the factory already return factory; } // FxCop won't let us compare to String.Empty, so we do // two comparisons for "performance reasons" if (_defaultInterpreterId != null && string.IsNullOrEmpty(_defaultInterpreterId)) { // We've loaded, and there's nothing there return _registryService.Value.NoInterpretersValue; } lock (_defaultInterpreterLock) { if (_defaultInterpreterId == null) { // We haven't loaded yet _defaultInterpreterId = LoadDefaultInterpreterId(); } if (_defaultInterpreter == null && !string.IsNullOrEmpty(_defaultInterpreterId)) { // We've loaded but haven't found the factory yet _defaultInterpreter = _registryService.Value.FindInterpreter(_defaultInterpreterId); } } return _defaultInterpreter ?? _registryService.Value.NoInterpretersValue; } set { var newDefault = value; if (newDefault == _registryService.Value.NoInterpretersValue) { newDefault = null; } SetDefaultInterpreter(null, newDefault); } } private void BeginSuppressDefaultInterpreterChangeEvent() { Interlocked.Increment(ref _suppressDefaultInterpreterChangeEvent); } private void EndSuppressDefaultInterpreterChangeEvent() { if (0 == Interlocked.Decrement(ref _suppressDefaultInterpreterChangeEvent) && 0 != Interlocked.Exchange(ref _requireDefaultInterpreterChangeEvent, 0)) { _defaultInterpreterChanged?.Invoke(this, EventArgs.Empty); } } private void OnDefaultInterpreterChanged() { if (Volatile.Read(ref _suppressDefaultInterpreterChangeEvent) != 0) { Volatile.Write(ref _requireDefaultInterpreterChangeEvent, 1); return; } _defaultInterpreterChanged?.Invoke(this, EventArgs.Empty); } public event EventHandler DefaultInterpreterChanged { add { if (!_defaultInterpreterWatched) { InitializeDefaultInterpreterWatcher(); } _defaultInterpreterChanged += value; } remove { _defaultInterpreterChanged -= value; } } public string AddConfigurableInterpreter(string name, InterpreterConfiguration config) { using (_cpythonProvider.Value.SuppressDiscoverFactories()) { var collection = CustomInterpreterKey + "\\" + name; using (var key = Registry.CurrentUser.CreateSubKey(CustomInterpreterKey, true)) { key.SetValue(DescriptionKey, Strings.CustomEnvironmentLabel); } using (var key = Registry.CurrentUser.CreateSubKey(collection, true)) { if (config.Architecture != InterpreterArchitecture.Unknown) { key.SetValue(ArchitectureKey, config.Architecture.ToPEP514()); } else { key.DeleteValue(ArchitectureKey, false); } if (config.Version != new Version()) { key.SetValue(VersionKey, config.Version.ToString()); } else { key.DeleteValue(VersionKey, false); } if (!string.IsNullOrEmpty(config.PathEnvironmentVariable)) { key.SetValue(PathEnvVarKey, config.PathEnvironmentVariable); } else { key.DeleteValue(PathEnvVarKey, false); } if (!string.IsNullOrEmpty(config.Description)) { key.SetValue(DescriptionKey, config.Description); } else { key.DeleteValue(DescriptionKey, false); } var vsConfig = (VisualStudioInterpreterConfiguration) config; using (var installPath = key.CreateSubKey("InstallPath")) { string exePath = config.InterpreterPath ?? vsConfig.WindowsInterpreterPath ?? ""; if (!string.IsNullOrEmpty(vsConfig.PrefixPath)) { installPath.SetValue("", vsConfig.PrefixPath); } else if (!string.IsNullOrWhiteSpace(exePath)) { installPath.SetValue("", Path.GetDirectoryName(exePath)); } installPath.SetValue(WindowsPathKey, config.GetWindowsInterpreterPath() ?? string.Empty); installPath.SetValue(PathKey, config.InterpreterPath ?? string.Empty); } } } return CPythonInterpreterFactoryConstants.GetInterpreterId(CustomCompany, name); } public void RemoveConfigurableInterpreter(string id) { string company, tag; if (CPythonInterpreterFactoryConstants.TryParseInterpreterId(id, out company, out tag) && company == CustomCompany) { var collection = CustomInterpreterKey + "\\" + tag; using (_cpythonProvider.Value.SuppressDiscoverFactories()) { try { Registry.CurrentUser.DeleteSubKeyTree(collection); _cpythonProvider.Value.DiscoverInterpreterFactories(); } catch (ArgumentException) { } } } } public bool IsConfigurable(string id) { string company, tag; return CPythonInterpreterFactoryConstants.TryParseInterpreterId(id, out company, out tag) && company == CustomCompany; } public IEnumerable<IPackageManager> GetPackageManagers(IPythonInterpreterFactory factory) { if (_packageManagerProviders == null || !_packageManagerProviders.Any() || factory == null) { return Enumerable.Empty<IPackageManager>(); } return _packageManagerProviders.SelectMany(p => p.Value.GetPackageManagers(factory)) .GroupBy(p => p.UniqueKey) .Select(g => g.OrderBy(p => p.Priority).FirstOrDefault()) .Where(p => p != null) .OrderBy(p => p.Priority) .ToArray(); } } }
// // 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.Collections.Generic; using NLog.Config; namespace NLog.UnitTests.Layouts { using System; using NLog.Layouts; using Xunit; public class XmlLayoutTests : NLogTestBase { [Fact] public void XmlLayoutRendering() { var xmlLayout = new XmlLayout() { Elements = { new XmlElement("date", "${longdate}"), new XmlElement("level", "${level}"), new XmlElement("message", "${message}"), }, IndentXml = true, IncludeAllProperties = true, }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue"; Assert.Equal(string.Format(System.Globalization.CultureInfo.InvariantCulture, @"<logevent>{0}{1}<date>2010-01-01 12:34:56.0000</date>{0}{1}<level>Info</level>{0}{1}<message>hello, world</message>{0}{1}<property key=""nlogPropertyKey"">nlogPropertyValue</property>{0}</logevent>", Environment.NewLine, " "), xmlLayout.Render(logEventInfo)); } [Fact] public void XmlLayoutLog4j() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='debug'> <layout type='xmllayout' elementName='log4j:event' propertiesElementName='log4j:data' propertiesElementKeyAttribute='name' propertiesElementValueAttribute='value' includeAllProperties='true' includeMdc='true' includeMdlc='true' > <attribute name='logger' layout='${logger}' includeEmptyValue='true' /> <attribute name='level' layout='${uppercase:${level}}' includeEmptyValue='true' /> <element name='log4j:message' value='${message}' /> <element name='log4j:throwable' value='${exception:format=tostring}' /> <element name='log4j:locationInfo'> <attribute name='class' layout='${callsite:methodName=false}' includeEmptyValue='true' /> </element> </layout> </target> </targets> <rules> <logger name='*' minlevel='debug' appendto='debug' /> </rules> </nlog>"); MappedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("foo1", "bar1"); MappedDiagnosticsContext.Set("foo2", "bar2"); MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set("foo3", "bar3"); var logger = LogManager.GetLogger("hello"); var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", null, null, "some message"); logEventInfo.Properties["nlogPropertyKey"] = "<nlog\r\nPropertyValue>"; logger.Log(logEventInfo); var target = LogManager.Configuration.FindTargetByName<NLog.Targets.DebugTarget>("debug"); Assert.Equal(@"<log4j:event logger=""A"" level=""DEBUG""><log4j:message>some message</log4j:message><log4j:locationInfo class=""NLog.UnitTests.Layouts.XmlLayoutTests""/><log4j:data name=""foo1"" value=""bar1""/><log4j:data name=""foo2"" value=""bar2""/><log4j:data name=""foo3"" value=""bar3""/><log4j:data name=""nlogPropertyKey"" value=""&lt;nlog&#13;&#10;PropertyValue&gt;""/></log4j:event>", target.LastMessage); } [Fact] public void XmlLayout_EncodeValue_RenderXmlMessage() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}"), }, }; var logEventInfo = new LogEventInfo { Message = @"<hello planet=""earth""/>" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>&lt;hello planet=&quot;earth&quot;/&gt;</message></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_SkipEncodeValue_RenderXmlMessage() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") { Encode = false } }, }; var logEventInfo = new LogEventInfo { Message = @"<hello planet=""earth""/>" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message><hello planet=""earth""/></message></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_IncludeEmptyValue_RenderEmptyValue() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") { IncludeEmptyValue = true }, }, IncludeAllProperties = true, IncludeEmptyValue = true, }; var logEventInfo = new LogEventInfo { Message = "" }; logEventInfo.Properties["nlogPropertyKey"] = null; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message></message><property key=""nlogPropertyKey"">null</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_NoIndent_RendersOneLine() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("level", "${level}"), new XmlElement("message", "${message}"), }, IndentXml = false, IncludeAllProperties = true, }; var logEventInfo = new LogEventInfo { Message = "message 1", Level = LogLevel.Debug }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; logEventInfo.Properties["prop3"] = "c"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><level>Debug</level><message>message 1</message><property key=""prop1"">a</property><property key=""prop2"">b</property><property key=""prop3"">c</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_ExcludeProperties_RenderNotProperty() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}"), }, IncludeAllProperties = true, ExcludeProperties = new HashSet<string> { "prop2" } }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; logEventInfo.Properties["prop3"] = "c"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>message 1</message><property key=""prop1"">a</property><property key=""prop3"">c</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_OnlyLogEventProperties_RenderRootCorrect() { // Arrange var xmlLayout = new XmlLayout() { IncludeAllProperties = true, }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; logEventInfo.Properties["prop3"] = "c"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><property key=""prop1"">a</property><property key=""prop2"">b</property><property key=""prop3"">c</property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_InvalidXmlPropertyName_RenderNameCorrect() { // Arrange var xmlLayout = new XmlLayout() { IncludeAllProperties = true, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["1prop"] = "a"; logEventInfo.Properties["_2prop"] = "b"; logEventInfo.Properties[" 3prop"] = "c"; logEventInfo.Properties["_4 prop"] = "d"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><_1prop>a</_1prop><_2prop>b</_2prop><_3prop>c</_3prop><_4_prop>d</_4_prop></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesAttributeNames_RenderPropertyName() { // Arrange var xmlLayout = new XmlLayout() { IncludeAllProperties = true, PropertiesElementName = "p", PropertiesElementKeyAttribute = "k", PropertiesElementValueAttribute = "v", }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><p k=""prop1"" v=""a""/><p k=""prop2"" v=""b""/></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyName() { // Arrange var xmlLayout = new XmlLayout() { IncludeAllProperties = true, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", PropertiesElementValueAttribute = "v", }; var logEventInfo = new LogEventInfo { Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><prop1 v=""a""/><prop2 v=""b""/></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_DoubleNestedElements_RendersAllElements() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") { Elements = { new XmlElement("level", "${level}") }, IncludeAllProperties = true, } }, }; var logEventInfo = new LogEventInfo { Level = LogLevel.Debug, Message = "message 1" }; logEventInfo.Properties["prop1"] = "a"; logEventInfo.Properties["prop2"] = "b"; // Act var result = xmlLayout.Render(logEventInfo); // Assert string expected = @"<logevent><message>message 1<level>Debug</level><property key=""prop1"">a</property><property key=""prop2"">b</property></message></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyDictionary() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeAllProperties = true, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new Dictionary<string, object> { { "Hello", "World" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><property key=""Hello"">World</property></property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyDictionary() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeAllProperties = true, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new Dictionary<string, object> { { "Hello", "World" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><Hello>World</Hello></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyList() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeAllProperties = true, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new [] { "Hello", "World" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><item>Hello</item><item>World</item></property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyList() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeAllProperties = true, PropertiesCollectionItemName = "node", PropertiesElementValueAttribute = "value", }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new[] { "Hello", "World" }; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><node value=""Hello""/><node value=""World""/></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyObject() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeAllProperties = true, }; var guid = Guid.NewGuid(); var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new { Id = guid, Name = "Hello World", Elements = new[] { "Earth", "Wind", "Fire" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><property key=""Id"">" + guid.ToString() + @"</property><property key=""Name"">Hello World</property><property key=""Elements""><item>Earth</item><item>Wind</item><item>Fire</item></property></property></logevent>"; Assert.Equal(expected, result); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderPropertyObject() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeAllProperties = true, }; var guid = Guid.NewGuid(); var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new { Id = guid, Name = "Hello World", Elements = new[] { "Earth", "Wind", "Fire" } }; // Act var result = xmlLayout.Render(logEventInfo); // Assert string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><Id>" + guid.ToString() + @"</Id><Name>Hello World</Name><Elements><item>Earth</item><item>Wind</item><item>Fire</item></Elements></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } #if DYNAMIC_OBJECT [Fact] public void XmlLayout_PropertiesElementNameDefault_Properties_RenderPropertyExpando() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, IncludeAllProperties = true, }; dynamic object1 = new System.Dynamic.ExpandoObject(); object1.Id = 123; object1.Name = "test name"; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = object1; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><property key=""nlogPropertyKey""><property key=""Id"">123</property><property key=""Name"">test name</property></property></logevent>"; Assert.Equal(expected, result); } #endif [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderInfiniteLoop() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeAllProperties = true, MaxRecursionLimit = 10, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; logEventInfo.Properties["nlogPropertyKey"] = new TestList(); // Act var result = xmlLayout.Render(logEventInfo); // Assert var cnt = System.Text.RegularExpressions.Regex.Matches(result, "<item>alpha</item><item>bravo</item>").Count; Assert.Equal(10, cnt); } [Fact] public void XmlLayout_PropertiesElementNameFormat_RenderTrickyDictionary() { // Arrange var xmlLayout = new XmlLayout() { Elements = { new XmlElement("message", "${message}") }, PropertiesElementName = "{0}", PropertiesElementKeyAttribute = "", IncludeAllProperties = true, MaxRecursionLimit = 10, }; var logEventInfo = new LogEventInfo { Message = "Monster massage" }; IDictionary<object, object> testDictionary = new Internal.TrickyTestDictionary(); testDictionary.Add("key1", 13); testDictionary.Add("key 2", 1.3m); logEventInfo.Properties["nlogPropertyKey"] = testDictionary; // Act var result = xmlLayout.Render(logEventInfo); // Assert const string expected = @"<logevent><message>Monster massage</message><nlogPropertyKey><key1>13</key1><key_2>1.3</key_2></nlogPropertyKey></logevent>"; Assert.Equal(expected, result); } private class TestList : IEnumerable<System.Collections.IEnumerable> { static List<int> _list1 = new List<int> { 17, 3 }; static List<string> _list2 = new List<string> { "alpha", "bravo" }; public IEnumerator<System.Collections.IEnumerable> GetEnumerator() { yield return _list1; yield return _list2; yield return new TestList(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public override bool Equals(object obj) { throw new Exception("object.Equals should never be called"); } public override int GetHashCode() { throw new Exception("GetHashCode should never be called"); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Scheduler; using Microsoft.Azure.Management.Scheduler.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Scheduler.Test.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Net; using Xunit; using SchedulerDayOfWeek = Microsoft.Azure.Management.Scheduler.Models.DayOfWeek; using Microsoft.Rest.Azure.OData; namespace Scheduler.Test.ScenarioTests { public class JobTests { private const string subscriptionId = "623d50f1-4fa8-4e46-a967-a9214aed43ab"; private const string resourceGroupName = "CS-SouthCentralUS-scheduler"; private const string type = "Microsoft.Scheduler/jobCollections/jobs"; private const string location = "South Central US"; private static DateTime EndTime = new DateTime(2020, 10, 10, 10, 10, 10, DateTimeKind.Utc); [Fact] public void Scenario_JobCreateWithScheduleForDay() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.None, }, ErrorAction = new JobErrorAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", } } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Day, Count = 100, EndTime = JobTests.EndTime, Schedule = new JobRecurrenceSchedule() { Hours = new List<int?>() { 5, 10, 15, 20 }, Minutes = new List<int?>() { 0, 10, 20, 30, 40, 50 }, } }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.Http, result.Properties.Action.Type); Assert.Equal("http://www.bing.com/", result.Properties.Action.Request.Uri); Assert.Equal("GET", result.Properties.Action.Request.Method); Assert.Equal(RetryType.None, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.ErrorAction.Type); Assert.Equal("schedulersdktest", result.Properties.Action.ErrorAction.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.ErrorAction.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.ErrorAction.QueueMessage.Message); Assert.Null(result.Properties.Action.ErrorAction.QueueMessage.SasToken); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Day, result.Properties.Recurrence.Frequency); Assert.Equal(100, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, result.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, result.Properties.Recurrence.Schedule.Minutes); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var getResult = client.Jobs.Get(resourceGroupName, jobCollectionName, jobName); Assert.Equal(id, getResult.Id); Assert.Equal(type, getResult.Type); Assert.Equal(jobDefinitionname, getResult.Name); Assert.Equal(JobActionType.Http, getResult.Properties.Action.Type); Assert.Equal("http://www.bing.com/", getResult.Properties.Action.Request.Uri); Assert.Equal("GET", getResult.Properties.Action.Request.Method); Assert.Equal(RetryType.None, getResult.Properties.Action.RetryPolicy.RetryType); Assert.Equal(JobActionType.StorageQueue, getResult.Properties.Action.ErrorAction.Type); Assert.Equal("schedulersdktest", getResult.Properties.Action.ErrorAction.QueueMessage.StorageAccount); Assert.Equal("queue1", getResult.Properties.Action.ErrorAction.QueueMessage.QueueName); Assert.Equal("some message!", getResult.Properties.Action.ErrorAction.QueueMessage.Message); Assert.Null(getResult.Properties.Action.ErrorAction.QueueMessage.SasToken); Assert.Equal(JobState.Enabled, getResult.Properties.State); Assert.Equal(RecurrenceFrequency.Day, getResult.Properties.Recurrence.Frequency); Assert.Equal(100, getResult.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, getResult.Properties.Recurrence.EndTime); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, getResult.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, getResult.Properties.Recurrence.Schedule.Minutes); Assert.Null(getResult.Properties.Status.LastExecutionTime); Assert.Equal(0, getResult.Properties.Status.ExecutionCount); Assert.Equal(0, getResult.Properties.Status.FailureCount); Assert.Equal(0, getResult.Properties.Status.FaultedCount); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateWithScheduleForWeek() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, Schedule = new JobRecurrenceSchedule() { WeekDays = new List<SchedulerDayOfWeek?>() { SchedulerDayOfWeek.Monday }, Hours = new List<int?>() { 5, 10, 15, 20 }, Minutes = new List<int?>() { 0, 10, 20, 30, 40, 50 }, } }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.Type); Assert.Equal("schedulersdktest", result.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.QueueMessage.Message); Assert.Null(result.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Equal(new List<SchedulerDayOfWeek?>() { SchedulerDayOfWeek.Monday }, result.Properties.Recurrence.Schedule.WeekDays); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, result.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, result.Properties.Recurrence.Schedule.Minutes); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var getResult = client.Jobs.Get(resourceGroupName, jobCollectionName, jobName); Assert.Equal(type, getResult.Type); Assert.Equal(jobDefinitionname, getResult.Name); Assert.Equal(JobActionType.StorageQueue, getResult.Properties.Action.Type); Assert.Equal("schedulersdktest", getResult.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", getResult.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", getResult.Properties.Action.QueueMessage.Message); Assert.Null(getResult.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, getResult.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, getResult.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), getResult.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobState.Enabled, getResult.Properties.State); Assert.Equal(RecurrenceFrequency.Week, getResult.Properties.Recurrence.Frequency); Assert.Equal(1, getResult.Properties.Recurrence.Interval); Assert.Equal(10000, getResult.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, getResult.Properties.Recurrence.EndTime); Assert.Equal(new List<SchedulerDayOfWeek?>() { SchedulerDayOfWeek.Monday }, getResult.Properties.Recurrence.Schedule.WeekDays); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, getResult.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, getResult.Properties.Recurrence.Schedule.Minutes); Assert.Null(getResult.Properties.Status.LastExecutionTime); Assert.Equal(0, getResult.Properties.Status.ExecutionCount); Assert.Equal(0, getResult.Properties.Status.FailureCount); Assert.Equal(0, getResult.Properties.Status.FaultedCount); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateWithScheduleForMonth() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", }, } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Month, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, Schedule = new JobRecurrenceSchedule() { MonthDays = new List<int?>() { 15, 30 }, Hours = new List<int?>() { 5, 10, 15, 20 }, Minutes = new List<int?>() { 0, 10, 20, 30, 40, 50 }, } }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.Type); Assert.Equal("schedulersdktest", result.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.QueueMessage.Message); Assert.Null(result.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.Http, result.Properties.Action.ErrorAction.Type); Assert.Equal("http://www.bing.com/", result.Properties.Action.ErrorAction.Request.Uri); Assert.Equal("GET", result.Properties.Action.ErrorAction.Request.Method); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Month, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Equal(new List<int?>() { 15, 30 }, result.Properties.Recurrence.Schedule.MonthDays); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, result.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, result.Properties.Recurrence.Schedule.Minutes); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var getResult = client.Jobs.Get(resourceGroupName, jobCollectionName, jobName); Assert.Equal(type, getResult.Type); Assert.Equal(jobDefinitionname, getResult.Name); Assert.Equal(JobActionType.StorageQueue, getResult.Properties.Action.Type); Assert.Equal("schedulersdktest", getResult.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", getResult.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", getResult.Properties.Action.QueueMessage.Message); Assert.Null(getResult.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, getResult.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, getResult.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), getResult.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.Http, getResult.Properties.Action.ErrorAction.Type); Assert.Equal("http://www.bing.com/", getResult.Properties.Action.ErrorAction.Request.Uri); Assert.Equal("GET", getResult.Properties.Action.ErrorAction.Request.Method); Assert.Equal(JobState.Enabled, getResult.Properties.State); Assert.Equal(RecurrenceFrequency.Month, getResult.Properties.Recurrence.Frequency); Assert.Equal(1, getResult.Properties.Recurrence.Interval); Assert.Equal(10000, getResult.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, getResult.Properties.Recurrence.EndTime); Assert.Equal(new List<int?>() { 15, 30 }, getResult.Properties.Recurrence.Schedule.MonthDays); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, getResult.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, getResult.Properties.Recurrence.Schedule.Minutes); Assert.Null(getResult.Properties.Status.LastExecutionTime); Assert.Equal(0, getResult.Properties.Status.ExecutionCount); Assert.Equal(0, getResult.Properties.Status.FailureCount); Assert.Equal(0, getResult.Properties.Status.FaultedCount); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateWithScheduleForMonthlyOccurrence() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", }, } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Month, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, Schedule = new JobRecurrenceSchedule() { Hours = new List<int?>() { 5, 10, 15, 20 }, Minutes = new List<int?>() { 0, 10, 20, 30, 40, 50 }, MonthlyOccurrences = new List<JobRecurrenceScheduleMonthlyOccurrence>() { new JobRecurrenceScheduleMonthlyOccurrence() { Day = JobScheduleDay.Monday, Occurrence = 1, }, new JobRecurrenceScheduleMonthlyOccurrence() { Day = JobScheduleDay.Friday, Occurrence = 1, } }, } }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.Type); Assert.Equal("schedulersdktest", result.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.QueueMessage.Message); Assert.Null(result.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.Http, result.Properties.Action.ErrorAction.Type); Assert.Equal("http://www.bing.com/", result.Properties.Action.ErrorAction.Request.Uri); Assert.Equal("GET", result.Properties.Action.ErrorAction.Request.Method); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Month, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Equal(2, result.Properties.Recurrence.Schedule.MonthlyOccurrences.Count); Assert.Equal(JobScheduleDay.Monday, result.Properties.Recurrence.Schedule.MonthlyOccurrences[0].Day); Assert.Equal(1, result.Properties.Recurrence.Schedule.MonthlyOccurrences[0].Occurrence); Assert.Equal(JobScheduleDay.Friday, result.Properties.Recurrence.Schedule.MonthlyOccurrences[1].Day); Assert.Equal(1, result.Properties.Recurrence.Schedule.MonthlyOccurrences[1].Occurrence); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, result.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, result.Properties.Recurrence.Schedule.Minutes); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var getResult = client.Jobs.Get(resourceGroupName, jobCollectionName, jobName); Assert.Equal(type, getResult.Type); Assert.Equal(jobDefinitionname, getResult.Name); Assert.Equal(JobActionType.StorageQueue, getResult.Properties.Action.Type); Assert.Equal("schedulersdktest", getResult.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", getResult.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", getResult.Properties.Action.QueueMessage.Message); Assert.Null(getResult.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, getResult.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, getResult.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), getResult.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.Http, getResult.Properties.Action.ErrorAction.Type); Assert.Equal("http://www.bing.com/", getResult.Properties.Action.ErrorAction.Request.Uri); Assert.Equal("GET", getResult.Properties.Action.ErrorAction.Request.Method); Assert.Equal(JobState.Enabled, getResult.Properties.State); Assert.Equal(RecurrenceFrequency.Month, getResult.Properties.Recurrence.Frequency); Assert.Equal(1, getResult.Properties.Recurrence.Interval); Assert.Equal(10000, getResult.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, getResult.Properties.Recurrence.EndTime); Assert.Equal(2, getResult.Properties.Recurrence.Schedule.MonthlyOccurrences.Count); Assert.Equal(JobScheduleDay.Monday, getResult.Properties.Recurrence.Schedule.MonthlyOccurrences[0].Day); Assert.Equal(1, getResult.Properties.Recurrence.Schedule.MonthlyOccurrences[0].Occurrence); Assert.Equal(JobScheduleDay.Friday, getResult.Properties.Recurrence.Schedule.MonthlyOccurrences[1].Day); Assert.Equal(1, getResult.Properties.Recurrence.Schedule.MonthlyOccurrences[1].Occurrence); Assert.Equal(new List<int?>() { 5, 10, 15, 20 }, getResult.Properties.Recurrence.Schedule.Hours); Assert.Equal(new List<int?>() { 0, 10, 20, 30, 40, 50 }, getResult.Properties.Recurrence.Schedule.Minutes); Assert.Null(getResult.Properties.Status.LastExecutionTime); Assert.Equal(0, getResult.Properties.Status.ExecutionCount); Assert.Equal(0, getResult.Properties.Status.FailureCount); Assert.Equal(0, getResult.Properties.Status.FaultedCount); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateUpdateDeleteHttpJob() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var header = new Dictionary<string, string>(); header.Add("content-type", "application/xml"); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", Body = "some body message!", Headers = header, }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", } } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.Http, result.Properties.Action.Type); Assert.Equal("http://www.bing.com/", result.Properties.Action.Request.Uri); Assert.Equal("GET", result.Properties.Action.Request.Method); Assert.Equal("some body message!", result.Properties.Action.Request.Body); Assert.Equal(header, result.Properties.Action.Request.Headers); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.ErrorAction.Type); Assert.Equal("schedulersdktest", result.Properties.Action.ErrorAction.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.ErrorAction.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.ErrorAction.QueueMessage.Message); Assert.Null(result.Properties.Action.ErrorAction.QueueMessage.SasToken); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var updateResult = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", } }, State = JobState.Disabled, } }); Assert.Equal(id, updateResult.Id); Assert.Equal(type, updateResult.Type); Assert.Equal(jobDefinitionname, updateResult.Name); Assert.Equal(JobActionType.Http, updateResult.Properties.Action.Type); Assert.Equal("http://www.bing.com/", updateResult.Properties.Action.Request.Uri); Assert.Equal("GET", updateResult.Properties.Action.Request.Method); Assert.Null(updateResult.Properties.Action.Request.Body); Assert.Null(updateResult.Properties.Action.RetryPolicy); Assert.Null(updateResult.Properties.Action.ErrorAction); Assert.Equal(JobState.Disabled, updateResult.Properties.State); Assert.Null(updateResult.Properties.Recurrence); Assert.Null(updateResult.Properties.Status); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateHttpJobWithBasicAuth() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var header = new Dictionary<string, string>(); header.Add("content-type", "application/xml"); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", Body = "some body message!", Headers = header, Authentication = new BasicAuthentication() { Username = "username", Password = "pasworrd", Type = HttpAuthenticationType.Basic, } }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", } } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.Http, result.Properties.Action.Type); Assert.Equal("http://www.bing.com/", result.Properties.Action.Request.Uri); Assert.Equal("GET", result.Properties.Action.Request.Method); Assert.Equal("some body message!", result.Properties.Action.Request.Body); Assert.Equal(header, result.Properties.Action.Request.Headers); Assert.NotNull(result.Properties.Action.Request.Authentication); Assert.Equal(HttpAuthenticationType.Basic, result.Properties.Action.Request.Authentication.Type); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.ErrorAction.Type); Assert.Equal("schedulersdktest", result.Properties.Action.ErrorAction.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.ErrorAction.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.ErrorAction.QueueMessage.Message); Assert.Null(result.Properties.Action.ErrorAction.QueueMessage.SasToken); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var updateResult = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", } }, State = JobState.Disabled, } }); Assert.Equal(id, updateResult.Id); Assert.Equal(type, updateResult.Type); Assert.Equal(jobDefinitionname, updateResult.Name); Assert.Equal(JobActionType.Http, updateResult.Properties.Action.Type); Assert.Equal("http://www.bing.com/", updateResult.Properties.Action.Request.Uri); Assert.Equal("GET", updateResult.Properties.Action.Request.Method); Assert.Null(updateResult.Properties.Action.Request.Body); Assert.Null(updateResult.Properties.Action.RetryPolicy); Assert.Null(updateResult.Properties.Action.ErrorAction); Assert.Equal(JobState.Disabled, updateResult.Properties.State); Assert.Null(updateResult.Properties.Recurrence); Assert.Null(updateResult.Properties.Status); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateHttpJobWithOAuth() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var header = new Dictionary<string, string>(); header.Add("content-type", "application/xml"); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "https://management.azure.com/subscriptions/11111111-1111-1111-1111-111111111111/", Method = "GET", Body = "some body message!", Headers = header, Authentication = new OAuthAuthentication() { // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")] Secret = "ThisIsFakeSecret", Audience = "https://management.core.windows.net/", ClientId = "11111111-1111-1111-1111-111111111111", Tenant = "fake.tenant.com", Type = HttpAuthenticationType.ActiveDirectoryOAuth, } }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", } } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.Http, result.Properties.Action.Type); Assert.Equal("https://management.azure.com/subscriptions/9d4e2ad0-e20b-4464-9219-353bded52513/", result.Properties.Action.Request.Uri); Assert.Equal("GET", result.Properties.Action.Request.Method); Assert.Equal("some body message!", result.Properties.Action.Request.Body); Assert.Equal(header, result.Properties.Action.Request.Headers); Assert.Equal(HttpAuthenticationType.ActiveDirectoryOAuth, result.Properties.Action.Request.Authentication.Type); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.ErrorAction.Type); Assert.Equal("schedulersdktest", result.Properties.Action.ErrorAction.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.ErrorAction.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.ErrorAction.QueueMessage.Message); Assert.Null(result.Properties.Action.ErrorAction.QueueMessage.SasToken); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var updateResult = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", } }, State = JobState.Disabled, } }); Assert.Equal(id, updateResult.Id); Assert.Equal(type, updateResult.Type); Assert.Equal(jobDefinitionname, updateResult.Name); Assert.Equal(JobActionType.Http, updateResult.Properties.Action.Type); Assert.Equal("http://www.bing.com/", updateResult.Properties.Action.Request.Uri); Assert.Equal("GET", updateResult.Properties.Action.Request.Method); Assert.Null(updateResult.Properties.Action.Request.Body); Assert.Null(updateResult.Properties.Action.RetryPolicy); Assert.Null(updateResult.Properties.Action.ErrorAction); Assert.Equal(JobState.Disabled, updateResult.Properties.State); Assert.Null(updateResult.Properties.Recurrence); Assert.Null(updateResult.Properties.Status); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateHttpJobWithClientCertAuth() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var header = new Dictionary<string, string>(); header.Add("content-type", "application/xml"); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "https://www.bing.com/", Method = "GET", Body = "some body message!", Headers = header, Authentication = new ClientCertAuthentication() { Password = "FakePassword", Pfx = "ThisIsfakePfx", Type = HttpAuthenticationType.ClientCertificate, } }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", } } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.Http, result.Properties.Action.Type); Assert.Equal("https://www.bing.com/", result.Properties.Action.Request.Uri); Assert.Equal("GET", result.Properties.Action.Request.Method); Assert.Equal("some body message!", result.Properties.Action.Request.Body); Assert.Equal(header, result.Properties.Action.Request.Headers); Assert.Equal(HttpAuthenticationType.ClientCertificate, result.Properties.Action.Request.Authentication.Type); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.ErrorAction.Type); Assert.Equal("schedulersdktest", result.Properties.Action.ErrorAction.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.ErrorAction.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.ErrorAction.QueueMessage.Message); Assert.Null(result.Properties.Action.ErrorAction.QueueMessage.SasToken); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var updateResult = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", } }, State = JobState.Disabled, } }); Assert.Equal(id, updateResult.Id); Assert.Equal(type, updateResult.Type); Assert.Equal(jobDefinitionname, updateResult.Name); Assert.Equal(JobActionType.Http, updateResult.Properties.Action.Type); Assert.Equal("http://www.bing.com/", updateResult.Properties.Action.Request.Uri); Assert.Equal("GET", updateResult.Properties.Action.Request.Method); Assert.Null(updateResult.Properties.Action.Request.Body); Assert.Null(updateResult.Properties.Action.RetryPolicy); Assert.Null(updateResult.Properties.Action.ErrorAction); Assert.Equal(JobState.Disabled, updateResult.Properties.State); Assert.Null(updateResult.Properties.Recurrence); Assert.Null(updateResult.Properties.Status); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreatePatchDeleteStorageJob() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.StorageQueue, QueueMessage = new StorageQueueMessage() { StorageAccount = "schedulersdktest", QueueName = "queue1", Message = "some message!", SasToken = "ThIsiSmYtOkeNdoyOusEe", }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", }, } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.StorageQueue, result.Properties.Action.Type); Assert.Equal("schedulersdktest", result.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", result.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", result.Properties.Action.QueueMessage.Message); Assert.Null(result.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.Http, result.Properties.Action.ErrorAction.Type); Assert.Equal("http://www.bing.com/", result.Properties.Action.ErrorAction.Request.Uri); Assert.Equal("GET", result.Properties.Action.ErrorAction.Request.Method); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var patchResult = client.Jobs.Patch( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 14), Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Day, Interval = 1, }, } }); Assert.Equal(type, patchResult.Type); Assert.Equal(jobDefinitionname, patchResult.Name); Assert.Equal(new DateTime(2015, 7, 14, 0, 0, 0, DateTimeKind.Utc), patchResult.Properties.StartTime); Assert.Equal(JobActionType.StorageQueue, patchResult.Properties.Action.Type); Assert.Equal("schedulersdktest", patchResult.Properties.Action.QueueMessage.StorageAccount); Assert.Equal("queue1", patchResult.Properties.Action.QueueMessage.QueueName); Assert.Equal("some message!", patchResult.Properties.Action.QueueMessage.Message); Assert.Null(patchResult.Properties.Action.QueueMessage.SasToken); Assert.Equal(RetryType.Fixed, patchResult.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, patchResult.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), patchResult.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.Http, patchResult.Properties.Action.ErrorAction.Type); Assert.Equal("http://www.bing.com/", patchResult.Properties.Action.ErrorAction.Request.Uri); Assert.Equal("GET", patchResult.Properties.Action.ErrorAction.Request.Method); Assert.Equal(JobState.Enabled, patchResult.Properties.State); Assert.Equal(RecurrenceFrequency.Day, patchResult.Properties.Recurrence.Frequency); Assert.Equal(1, patchResult.Properties.Recurrence.Interval); Assert.Equal(10000, patchResult.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, patchResult.Properties.Recurrence.EndTime); Assert.Null(patchResult.Properties.Status.LastExecutionTime); Assert.Equal(0, patchResult.Properties.Status.ExecutionCount); Assert.Equal(0, patchResult.Properties.Status.FailureCount); Assert.Equal(0, patchResult.Properties.Status.FaultedCount); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateUpdateDeleteServiceBusQueueJob() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")] var sasKey = "ThisIsFakeSasKey"; var sasKeyName = "RootManageSharedAccessKey"; var contentType = "Application/Json"; var brokerMessageProperties = new ServiceBusBrokeredMessageProperties() { ContentType = contentType, TimeToLive = TimeSpan.FromSeconds(5), }; var customMessageProperties = new Dictionary<string, string>(); customMessageProperties.Add("customMessagePropertyName", "customMessagePropertyValue"); var message = "Some Message!"; var namespaceProperty = "scheduler-sdk-ns"; var queueName = "scheduler-sdk-queue"; var topicPath = "scheduler-sdk-topic"; var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var header = new Dictionary<string, string>(); header.Add("content-type", "application/xml"); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.ServiceBusQueue, ServiceBusQueueMessage = new ServiceBusQueueMessage() { Authentication = new ServiceBusAuthentication() { SasKey = sasKey, SasKeyName = sasKeyName, Type = ServiceBusAuthenticationType.SharedAccessKey, }, BrokeredMessageProperties = brokerMessageProperties, CustomMessageProperties = customMessageProperties, Message = message, NamespaceProperty = namespaceProperty, QueueName = queueName, TransportType = ServiceBusTransportType.NetMessaging, }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.ServiceBusTopic, ServiceBusTopicMessage = new ServiceBusTopicMessage() { Authentication = new ServiceBusAuthentication() { SasKey = sasKey, SasKeyName = sasKeyName, Type = ServiceBusAuthenticationType.SharedAccessKey, }, BrokeredMessageProperties = brokerMessageProperties, CustomMessageProperties = customMessageProperties, Message = message, NamespaceProperty = namespaceProperty, TopicPath = topicPath, TransportType = ServiceBusTransportType.NetMessaging, }, } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.ServiceBusQueue, result.Properties.Action.Type); Assert.Null(result.Properties.Action.ServiceBusQueueMessage.Authentication.SasKey); Assert.Equal(sasKeyName, result.Properties.Action.ServiceBusQueueMessage.Authentication.SasKeyName); Assert.Equal(ServiceBusAuthenticationType.SharedAccessKey, result.Properties.Action.ServiceBusQueueMessage.Authentication.Type); Assert.Equal(contentType, result.Properties.Action.ServiceBusQueueMessage.BrokeredMessageProperties.ContentType); Assert.Equal(customMessageProperties, result.Properties.Action.ServiceBusQueueMessage.CustomMessageProperties); Assert.Equal(message, result.Properties.Action.ServiceBusQueueMessage.Message); Assert.Equal(namespaceProperty, result.Properties.Action.ServiceBusQueueMessage.NamespaceProperty); Assert.Equal(queueName, result.Properties.Action.ServiceBusQueueMessage.QueueName); Assert.Equal(ServiceBusTransportType.NetMessaging, result.Properties.Action.ServiceBusQueueMessage.TransportType); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.ServiceBusTopic, result.Properties.Action.ErrorAction.Type); Assert.Null(result.Properties.Action.ErrorAction.ServiceBusTopicMessage.Authentication.SasKey); Assert.Equal(sasKeyName, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.Authentication.SasKeyName); Assert.Equal(ServiceBusAuthenticationType.SharedAccessKey, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.Authentication.Type); Assert.Equal(contentType, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.BrokeredMessageProperties.ContentType); Assert.Equal(customMessageProperties, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.CustomMessageProperties); Assert.Equal(message, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.Message); Assert.Equal(namespaceProperty, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.NamespaceProperty); Assert.Equal(topicPath, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.TopicPath); Assert.Equal(ServiceBusTransportType.NetMessaging, result.Properties.Action.ErrorAction.ServiceBusTopicMessage.TransportType); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var updateResult = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", } }, State = JobState.Disabled, } }); Assert.Equal(id, updateResult.Id); Assert.Equal(type, updateResult.Type); Assert.Equal(jobDefinitionname, updateResult.Name); Assert.Equal(JobActionType.Http, updateResult.Properties.Action.Type); Assert.Equal("http://www.bing.com/", updateResult.Properties.Action.Request.Uri); Assert.Equal("GET", updateResult.Properties.Action.Request.Method); Assert.Null(updateResult.Properties.Action.Request.Body); Assert.Null(updateResult.Properties.Action.RetryPolicy); Assert.Null(updateResult.Properties.Action.ErrorAction); Assert.Equal(JobState.Disabled, updateResult.Properties.State); Assert.Null(updateResult.Properties.Recurrence); Assert.Null(updateResult.Properties.Status); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobCreateUpdateDeleteServiceBusTopicJob() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName = TestUtilities.GenerateName("j1"); string jobDefinitionname = string.Format("{0}/{1}", jobCollectionName, jobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName); // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")] var sasKey = "ThisIsFakeSasKey"; var sasKeyName = "RootManageSharedAccessKey"; var contentType = "Application/Json"; var brokerMessageProperties = new ServiceBusBrokeredMessageProperties() { ContentType = contentType, }; var customMessageProperties = new Dictionary<string, string>(); customMessageProperties.Add("customMessagePropertyName", "customMessagePropertyValue"); var message = "Some Message!"; var namespaceProperty = "scheduler-sdk-ns"; var queueName = "scheduler-sdk-queue"; var topicPath = "scheduler-sdk-topic"; var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); var header = new Dictionary<string, string>(); header.Add("content-type", "application/xml"); var result = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.ServiceBusTopic, ServiceBusTopicMessage = new ServiceBusTopicMessage() { Authentication = new ServiceBusAuthentication() { SasKey = sasKey, SasKeyName = sasKeyName, Type = ServiceBusAuthenticationType.SharedAccessKey, }, BrokeredMessageProperties = brokerMessageProperties, CustomMessageProperties = customMessageProperties, Message = message, NamespaceProperty = namespaceProperty, TopicPath = topicPath, TransportType = ServiceBusTransportType.NetMessaging, }, RetryPolicy = new RetryPolicy() { RetryType = RetryType.Fixed, RetryCount = 2, RetryInterval = TimeSpan.FromMinutes(1), }, ErrorAction = new JobErrorAction() { Type = JobActionType.ServiceBusQueue, ServiceBusQueueMessage = new ServiceBusQueueMessage() { Authentication = new ServiceBusAuthentication() { SasKey = sasKey, SasKeyName = sasKeyName, Type = ServiceBusAuthenticationType.SharedAccessKey, }, BrokeredMessageProperties = brokerMessageProperties, CustomMessageProperties = customMessageProperties, Message = message, NamespaceProperty = namespaceProperty, QueueName = queueName, TransportType = ServiceBusTransportType.NetMessaging, }, } }, Recurrence = new JobRecurrence() { Frequency = RecurrenceFrequency.Week, Interval = 1, Count = 10000, EndTime = JobTests.EndTime, }, State = JobState.Enabled, } }); Assert.Equal(id, result.Id); Assert.Equal(type, result.Type); Assert.Equal(jobDefinitionname, result.Name); Assert.Equal(JobActionType.ServiceBusTopic, result.Properties.Action.Type); Assert.Null(result.Properties.Action.ServiceBusTopicMessage.Authentication.SasKey); Assert.Equal(sasKeyName, result.Properties.Action.ServiceBusTopicMessage.Authentication.SasKeyName); Assert.Equal(ServiceBusAuthenticationType.SharedAccessKey, result.Properties.Action.ServiceBusTopicMessage.Authentication.Type); Assert.Equal(contentType, result.Properties.Action.ServiceBusTopicMessage.BrokeredMessageProperties.ContentType); Assert.Equal(customMessageProperties, result.Properties.Action.ServiceBusTopicMessage.CustomMessageProperties); Assert.Equal(message, result.Properties.Action.ServiceBusTopicMessage.Message); Assert.Equal(namespaceProperty, result.Properties.Action.ServiceBusTopicMessage.NamespaceProperty); Assert.Equal(topicPath, result.Properties.Action.ServiceBusTopicMessage.TopicPath); Assert.Equal(ServiceBusTransportType.NetMessaging, result.Properties.Action.ServiceBusTopicMessage.TransportType); Assert.Equal(RetryType.Fixed, result.Properties.Action.RetryPolicy.RetryType); Assert.Equal(2, result.Properties.Action.RetryPolicy.RetryCount); Assert.Equal(TimeSpan.FromMinutes(1), result.Properties.Action.RetryPolicy.RetryInterval); Assert.Equal(JobActionType.ServiceBusQueue, result.Properties.Action.ErrorAction.Type); Assert.Null(result.Properties.Action.ErrorAction.ServiceBusQueueMessage.Authentication.SasKey); Assert.Equal(sasKeyName, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.Authentication.SasKeyName); Assert.Equal(ServiceBusAuthenticationType.SharedAccessKey, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.Authentication.Type); Assert.Equal(contentType, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.BrokeredMessageProperties.ContentType); Assert.Equal(customMessageProperties, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.CustomMessageProperties); Assert.Equal(message, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.Message); Assert.Equal(namespaceProperty, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.NamespaceProperty); Assert.Equal(queueName, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.QueueName); Assert.Equal(ServiceBusTransportType.NetMessaging, result.Properties.Action.ErrorAction.ServiceBusQueueMessage.TransportType); Assert.Equal(JobState.Enabled, result.Properties.State); Assert.Equal(RecurrenceFrequency.Week, result.Properties.Recurrence.Frequency); Assert.Equal(1, result.Properties.Recurrence.Interval); Assert.Equal(10000, result.Properties.Recurrence.Count); Assert.Equal(JobTests.EndTime, result.Properties.Recurrence.EndTime); Assert.Null(result.Properties.Status.LastExecutionTime); Assert.Equal(0, result.Properties.Status.ExecutionCount); Assert.Equal(0, result.Properties.Status.FailureCount); Assert.Equal(0, result.Properties.Status.FaultedCount); var updateResult = client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", } }, State = JobState.Disabled, } }); Assert.Equal(id, updateResult.Id); Assert.Equal(type, updateResult.Type); Assert.Equal(jobDefinitionname, updateResult.Name); Assert.Equal(JobActionType.Http, updateResult.Properties.Action.Type); Assert.Equal("http://www.bing.com/", updateResult.Properties.Action.Request.Uri); Assert.Equal("GET", updateResult.Properties.Action.Request.Method); Assert.Null(updateResult.Properties.Action.Request.Body); Assert.Null(updateResult.Properties.Action.RetryPolicy); Assert.Null(updateResult.Properties.Action.ErrorAction); Assert.Equal(JobState.Disabled, updateResult.Properties.State); Assert.Null(updateResult.Properties.Recurrence); Assert.Null(updateResult.Properties.Status); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobList() { using (MockContext context = MockContext.Start(this.GetType())) { string jobCollectionName = TestUtilities.GenerateName("jc1"); string jobName1 = TestUtilities.GenerateName("j1"); string jobName2 = TestUtilities.GenerateName("j2"); string jobDefinitionName1 = string.Format("{0}/{1}", jobCollectionName, jobName1); string jobDefinitionName2 = string.Format("{0}/{1}", jobCollectionName, jobName2); string id1 = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName1); string id2 = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, jobCollectionName, jobName2); var client = context.GetServiceClient<SchedulerManagementClient>(); this.CreateJobCollection(client, jobCollectionName); client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName1, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 13), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.bing.com/", Method = "GET", } }, State = JobState.Enabled, } }); client.Jobs.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobName: jobName2, job: new JobDefinition() { Properties = new JobProperties() { StartTime = new DateTime(2015, 7, 14), Action = new JobAction() { Type = JobActionType.Http, Request = new HttpRequest() { Uri = "http://www.google.com/", Method = "POST", } }, State = JobState.Disabled, } }); var disabledJob = client.Jobs.List(resourceGroupName, jobCollectionName, new ODataQuery<JobStateFilter>(filter => filter.State == JobState.Disabled) { Top = 5 }); Assert.Single(disabledJob); Assert.True(disabledJob.All(job => job.Properties.State == JobState.Disabled)); var enabledJob = client.Jobs.List(resourceGroupName, jobCollectionName, new ODataQuery<JobStateFilter>(filter => filter.State == JobState.Enabled) { Top = 5 }); Assert.Single(enabledJob); Assert.True(enabledJob.All(job => job.Properties.State == JobState.Enabled)); var listResult = client.Jobs.List(resourceGroupName, jobCollectionName); Assert.Equal(2, listResult.Count()); var listResult1 = listResult.Where(job => string.Compare(job.Id, id1) == 0).FirstOrDefault(); var listResult2 = listResult.Where(job => string.Compare(job.Id, id2) == 0).FirstOrDefault(); Assert.Equal(jobDefinitionName1, listResult1.Name); Assert.Equal(new DateTime(2015, 7, 13, 0, 0, 0, DateTimeKind.Utc), listResult1.Properties.StartTime); Assert.Equal(JobActionType.Http, listResult1.Properties.Action.Type); Assert.Equal("http://www.bing.com/", listResult1.Properties.Action.Request.Uri); Assert.Equal("GET", listResult1.Properties.Action.Request.Method); Assert.Equal(JobState.Enabled, listResult1.Properties.State); Assert.Equal(jobDefinitionName2, listResult2.Name); Assert.Equal(new DateTime(2015, 7, 14, 0, 0, 0, DateTimeKind.Utc), listResult2.Properties.StartTime); Assert.Equal(JobActionType.Http, listResult2.Properties.Action.Type); Assert.Equal("http://www.google.com/", listResult2.Properties.Action.Request.Uri); Assert.Equal("POST", listResult2.Properties.Action.Request.Method); Assert.Equal(JobState.Disabled, listResult2.Properties.State); client.JobCollections.Delete(resourceGroupName, jobCollectionName); } } [Fact] public void Scenario_JobHistoryList() { using (MockContext context = MockContext.Start(this.GetType())) { const string existingJobCollectionName = "sdk-test"; const string existingJobName = "http_job"; const string historyType = "Microsoft.Scheduler/jobCollections/jobs/history"; string jobDefinitionName = string.Format("{0}/{1}", existingJobCollectionName, existingJobName); string id = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Scheduler/jobCollections/{2}/jobs/{3}", subscriptionId, resourceGroupName, existingJobCollectionName, existingJobName); var client = context.GetServiceClient<SchedulerManagementClient>(); var completedHistories = client.Jobs.ListJobHistory(resourceGroupName, existingJobCollectionName, existingJobName, new ODataQuery<JobHistoryFilter>(filter => filter.Status == JobExecutionStatus.Completed)); Assert.True(completedHistories.Count() >= 0); Assert.True(completedHistories.All(history => history.Properties.Status == null)); var failedHistories = client.Jobs.ListJobHistory(resourceGroupName, existingJobCollectionName, existingJobName, new ODataQuery<JobHistoryFilter>(filter => filter.Status == JobExecutionStatus.Failed)); Assert.True(failedHistories.Count() >= 0); Assert.True(failedHistories.All(history => history.Properties.Status == JobExecutionStatus.Failed)); var listTopResult = client.Jobs.ListJobHistory(resourceGroupName, existingJobCollectionName, existingJobName, new ODataQuery<JobHistoryFilter> { Top = 5 }); var listSkipResult = client.Jobs.ListJobHistory(resourceGroupName, existingJobCollectionName, existingJobName, new ODataQuery<JobHistoryFilter> { Top = 5, Skip = 5 }); var listResult = client.Jobs.ListJobHistory(resourceGroupName, existingJobCollectionName, existingJobName); Assert.True(listResult.Count() >= 0); Assert.Contains(id, listResult.ElementAt(0).Id); Assert.Contains(jobDefinitionName, listResult.ElementAt(0).Name); Assert.Equal(historyType, listResult.ElementAt(0).Type); Assert.Equal(JobHistoryActionName.MainAction, listResult.ElementAt(0).Properties.ActionName); Assert.NotNull(listResult.ElementAt(0).Properties.EndTime); Assert.NotNull(listResult.ElementAt(0).Properties.ExpectedExecutionTime); Assert.NotNull(listResult.ElementAt(0).Properties.Message); Assert.True(listResult.ElementAt(0).Properties.RepeatCount > 0); Assert.True(listResult.ElementAt(0).Properties.RetryCount >= 0); Assert.NotNull(listResult.ElementAt(0).Properties.StartTime); Assert.True(listTopResult.Count() == 5); Assert.Equal(listResult.ElementAt(0).Type, listTopResult.ElementAt(0).Type); Assert.Equal(listResult.ElementAt(0).Properties.ActionName, listTopResult.ElementAt(0).Properties.ActionName); Assert.Equal(listResult.ElementAt(0).Properties.EndTime, listTopResult.ElementAt(0).Properties.EndTime); Assert.Equal(listResult.ElementAt(0).Properties.ExpectedExecutionTime, listTopResult.ElementAt(0).Properties.ExpectedExecutionTime); Assert.Equal(listResult.ElementAt(0).Properties.Message, listTopResult.ElementAt(0).Properties.Message); Assert.Equal(listResult.ElementAt(0).Properties.RepeatCount, listTopResult.ElementAt(0).Properties.RepeatCount); Assert.Equal(listResult.ElementAt(0).Properties.RetryCount, listTopResult.ElementAt(0).Properties.RetryCount); Assert.Equal(listResult.ElementAt(0).Properties.StartTime, listTopResult.ElementAt(0).Properties.StartTime); Assert.True(listSkipResult.Count() == 5); Assert.True(listTopResult.ElementAt(0).Properties.EndTime > listSkipResult.ElementAt(0).Properties.EndTime); Assert.True(listTopResult.ElementAt(0).Properties.ExpectedExecutionTime > listSkipResult.ElementAt(0).Properties.ExpectedExecutionTime); Assert.True(listTopResult.ElementAt(0).Properties.StartTime > listSkipResult.ElementAt(0).Properties.StartTime); } } private void CreateJobCollection(SchedulerManagementClient client, string jobCollectionName) { client.JobCollections.CreateOrUpdate( resourceGroupName: resourceGroupName, jobCollectionName: jobCollectionName, jobCollection: new JobCollectionDefinition() { Name = jobCollectionName, Location = location, Properties = new JobCollectionProperties() { Sku = new Sku() { Name = SkuDefinition.Standard, }, State = JobCollectionState.Enabled, Quota = new JobCollectionQuota() { MaxJobCount = 50, MaxRecurrence = new JobMaxRecurrence() { Frequency = RecurrenceFrequency.Minute, Interval = 1, } } } }); } } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Input; using System.Windows.Controls; using System.Windows.Documents; using ImageOrganizer.Common.Extensions; namespace ImageOrganizer.Presentation.Behaviors { public static class ControlExtensions { #region Static Properties public static readonly DependencyProperty IsControlSizeBoundProperty = DependencyProperty.RegisterAttached( "IsControlSizeBound", typeof(bool), typeof(ControlExtensions), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, IsControlSizeBound_PropertyChanged) ); public static readonly DependencyProperty OneWayControlWidthProperty = DependencyProperty.RegisterAttached( "OneWayControlWidth", typeof(double), typeof(ControlExtensions), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault) ); public static readonly DependencyProperty OneWayControlHeightProperty = DependencyProperty.RegisterAttached( "OneWayControlHeight", typeof(double), typeof(ControlExtensions), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault) ); public static readonly DependencyProperty LaunchHyperlinkProperty = DependencyProperty.RegisterAttached( "LaunchHyperlink", typeof(bool), typeof(ControlExtensions), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, LaunchHyperlink_PropertyChanged) ); public static readonly DependencyProperty IsAutoCenterItemProperty = DependencyProperty.RegisterAttached( "IsAutoCenterItem", typeof(bool), typeof(ControlExtensions), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, IsAutoCenterItem_PropertyChanged) ); public static readonly DependencyProperty BubbleMouseWheelProperty = DependencyProperty.RegisterAttached( "BubbleMouseWheel", typeof(bool), typeof(ControlExtensions), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None, BubbleMouseWheelProperty_PropertyChanged) ); public static readonly DependencyProperty BubbleMouseWheelRequireControlProperty = DependencyProperty.RegisterAttached( "BubbleMouseWheelRequireControl", typeof(bool), typeof(ControlExtensions), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None) ); #endregion #region Static Methods public static bool GetIsControlSizeBound(Control element) { return (bool)element.GetValue(IsControlSizeBoundProperty); } public static void SetIsControlSizeBound(Control element, bool Value) { element.SetValue(IsControlSizeBoundProperty, Value); } public static double GetOneWayControlWidth(Control element) { return (double)element.GetValue(OneWayControlWidthProperty); } public static void SetOneWayControlWidth(Control element, double Value) { element.SetValue(OneWayControlWidthProperty, Value); } public static double GetOneWayControlHeight(Control element) { return (double)element.GetValue(OneWayControlHeightProperty); } public static void SetOneWayControlHeight(Control element, double Value) { element.SetValue(OneWayControlHeightProperty, Value); } public static bool GetBubbleMouseWheel(FrameworkElement Element) { return (bool)Element.GetValue(BubbleMouseWheelProperty); } public static void SetBubbleMouseWheel(FrameworkElement Element, bool Value) { Element.SetValue(BubbleMouseWheelProperty, Value); } public static bool GetBubbleMouseWheelRequireControl(FrameworkElement Element) { return (bool)Element.GetValue(BubbleMouseWheelRequireControlProperty); } public static void SetBubbleMouseWheelRequireControl(FrameworkElement Element, bool Value) { Element.SetValue(BubbleMouseWheelRequireControlProperty, Value); } public static bool GetLaunchHyperlink(Hyperlink element) { return (bool)element.GetValue(LaunchHyperlinkProperty); } public static void SetLaunchHyperlink(Hyperlink element, bool Value) { element.SetValue(LaunchHyperlinkProperty, Value); } public static bool GetIsAutoCenterItem(ListBox element) { return (bool)element.GetValue(IsAutoCenterItemProperty); } public static void SetIsAutoCenterItem(ListBox element, bool Value) { element.SetValue(IsAutoCenterItemProperty, Value); } private static void IsControlSizeBound_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Element = o as Control; if (Element == null) return; var IsSet = (bool)e.NewValue; Element.SizeChanged -= Element_IsControlSizeBound_SizeChanged; if (IsSet) { SetOneWayControlWidth(Element, Element.ActualWidth); SetOneWayControlHeight(Element, Element.ActualHeight); Element.SizeChanged += Element_IsControlSizeBound_SizeChanged; } } private static void Element_IsControlSizeBound_SizeChanged(object sender, EventArgs e) { var Element = sender as Control; if (Element == null) return; //Due to some weirdness with the scrollviewer, subtracting 4 prevents the program //from taking full CPU usage when maximized. SetOneWayControlWidth(Element, Element.ActualWidth - Element.Padding.Left - Element.Padding.Right - 4d); SetOneWayControlHeight(Element, Element.ActualHeight - Element.Padding.Top - Element.Padding.Bottom - 4d); } private static void LaunchHyperlink_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Element = o as Hyperlink; if (Element == null) return; var IsSet = (bool)e.NewValue; Element.RequestNavigate -= Element_RequestNavigate; if (IsSet) { Element.RequestNavigate += Element_RequestNavigate; } } private static void Element_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e) { System.Diagnostics.Process.Start(e.Uri.AbsoluteUri); e.Handled = true; } private static void IsAutoCenterItem_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Element = o as ListBox; if (Element == null) return; var IsSet = (bool)e.NewValue; Element.SelectionChanged -= IsAutoCenterItem_ListBox_SelectedItemChanged; if (IsSet) { Element.SelectionChanged += IsAutoCenterItem_ListBox_SelectedItemChanged; } } private static void IsAutoCenterItem_ListBox_SelectedItemChanged(object sender, SelectionChangedEventArgs e) { var ListBox = sender as ListBox; if (ListBox == null) return; ListBox.ScrollIntoViewCentered(ListBox.SelectedItem); } private static void BubbleMouseWheelProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Element = o as FrameworkElement; if (Element == null) throw new ArgumentException("Type mismatch", "o"); var Value = (bool)e.NewValue; Element.PreviewMouseWheel -= BubbleMouseWheelProperty_Element_PreviewMouseWheel; if (Value) { Element.PreviewMouseWheel += BubbleMouseWheelProperty_Element_PreviewMouseWheel; } } private static void BubbleMouseWheelProperty_Element_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { var Element = sender as FrameworkElement; if (Element == null) return; var RequireControl = GetBubbleMouseWheelRequireControl(Element); if (RequireControl && (Keyboard.Modifiers & ModifierKeys.Control) == 0) return; //Relaunch the mouse wheel event e.Handled = true; var e2 = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta); e2.RoutedEvent = UIElement.MouseWheelEvent; Element.RaiseEvent(e2); } #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.Threading; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices { // These are the types of handles used by the EE. // IMPORTANT: These must match the definitions in ObjectHandle.h in the EE. // IMPORTANT: If new values are added to the enum the GCHandle::MaxHandleType // constant must be updated. public enum GCHandleType { Weak = 0, WeakTrackResurrection = 1, Normal = 2, Pinned = 3 } // This class allows you to create an opaque, GC handle to any // COM+ object. A GC handle is used when an object reference must be // reachable from unmanaged memory. There are 3 kinds of roots: // Normal - keeps the object from being collected. // Weak - allows object to be collected and handle contents will be zeroed. // Weak references are zeroed before the finalizer runs, so if the // object is resurrected in the finalizer the weak reference is // still zeroed. // WeakTrackResurrection - Same as weak, but stays until after object is // really gone. // Pinned - same as normal, but allows the address of the actual object // to be taken. // [StructLayout(LayoutKind.Sequential)] public struct GCHandle { // IMPORTANT: This must be kept in sync with the GCHandleType enum. private const GCHandleType MaxHandleType = GCHandleType.Pinned; // Allocate a handle storing the object and the type. internal GCHandle(Object value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) { throw new ArgumentOutOfRangeException(); // "type", SR.ArgumentOutOfRange_Enum; } if (type == GCHandleType.Pinned) GCHandleValidatePinnedObject(value); _handle = RuntimeImports.RhHandleAlloc(value, type); // Record if the handle is pinned. if (type == GCHandleType.Pinned) SetIsPinned(); } // Used in the conversion functions below. internal GCHandle(IntPtr handle) { _handle = handle; } // Creates a new GC handle for an object. // // value - The object that the GC handle is created for. // type - The type of GC handle to create. // // returns a new GC handle that protects the object. public static GCHandle Alloc(Object value) { return new GCHandle(value, GCHandleType.Normal); } public static GCHandle Alloc(Object value, GCHandleType type) { return new GCHandle(value, type); } // Frees a GC handle. [MethodImplAttribute(MethodImplOptions.NoInlining)] public void Free() { // Copy the handle instance member to a local variable. This is required to prevent // race conditions releasing the handle. IntPtr handle = _handle; // Free the handle if it hasn't already been freed. if (handle != default(IntPtr) && Interlocked.CompareExchange(ref _handle, default(IntPtr), handle) == handle) { #if BIT64 RuntimeImports.RhHandleFree((IntPtr)(((long)handle) & ~1L)); #else RuntimeImports.RhHandleFree((IntPtr)(((int)handle) & ~1)); #endif } else { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } } // Target property - allows getting / updating of the handle's referent. public Object Target { get { // Check if the handle was never initialized or was freed. if (_handle == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } return RuntimeImports.RhHandleGet(GetHandleValue()); } set { // Check if the handle was never initialized or was freed. if (_handle == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } RuntimeImports.RhHandleSet(GetHandleValue(), value); } } // Retrieve the address of an object in a Pinned handle. This throws // an exception if the handle is any type other than Pinned. public IntPtr AddrOfPinnedObject() { // Check if the handle was not a pinned handle. if (!IsPinned()) { // Check if the handle was never initialized for was freed. if (_handle == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } // You can only get the address of pinned handles. throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotPinned); } unsafe { // Get the address of the pinned object. // The layout of String and Array is different from Object Object target = this.Target; if (target == null) return default(IntPtr); String targetAsString = target as String; if (targetAsString != null) { fixed (char* ptr = targetAsString) { return (IntPtr)ptr; } } Array targetAsArray = target as Array; if (targetAsArray != null) { fixed (IntPtr* pTargetEEType = &targetAsArray.m_pEEType) { return (IntPtr)Array.GetAddrOfPinnedArrayFromEETypeField(pTargetEEType); } } else { fixed (IntPtr* pTargetEEType = &target.m_pEEType) { return (IntPtr)Object.GetAddrOfPinnedObjectFromEETypeField(pTargetEEType); } } } } // Determine whether this handle has been allocated or not. public bool IsAllocated { get { return _handle != default(IntPtr); } } // Used to create a GCHandle from an int. This is intended to // be used with the reverse conversion. public static explicit operator GCHandle(IntPtr value) { return FromIntPtr(value); } public static GCHandle FromIntPtr(IntPtr value) { if (value == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } return new GCHandle(value); } // Used to get the internal integer representation of the handle out. public static explicit operator IntPtr(GCHandle value) { return ToIntPtr(value); } public static IntPtr ToIntPtr(GCHandle value) { return value._handle; } public override int GetHashCode() { return _handle.GetHashCode(); } public override bool Equals(Object o) { GCHandle hnd; // Check that o is a GCHandle first if (o == null || !(o is GCHandle)) return false; else hnd = (GCHandle)o; return _handle == hnd._handle; } public static bool operator ==(GCHandle a, GCHandle b) { return a._handle == b._handle; } public static bool operator !=(GCHandle a, GCHandle b) { return a._handle != b._handle; } internal IntPtr GetHandleValue() { #if BIT64 return new IntPtr(((long)_handle) & ~1L); #else return new IntPtr(((int)_handle) & ~1); #endif } internal bool IsPinned() { #if BIT64 return (((long)_handle) & 1) != 0; #else return (((int)_handle) & 1) != 0; #endif } internal void SetIsPinned() { #if BIT64 _handle = new IntPtr(((long)_handle) | 1L); #else _handle = new IntPtr(((int)_handle) | 1); #endif } // // C# port of GCHandleValidatePinnedObject(OBJECTREF) in MarshalNative.cpp. // private static void GCHandleValidatePinnedObject(Object obj) { if (obj == null) return; if (obj is String) return; EETypePtr eeType = obj.EETypePtr; if (eeType.IsArray) { EETypePtr elementEEType = eeType.ArrayElementType; if (elementEEType.IsPrimitive) return; if (elementEEType.IsValueType && elementEEType.MightBeBlittable()) return; } else if (eeType.MightBeBlittable()) { return; } throw new ArgumentException(SR.Argument_NotIsomorphic); } // The actual integer handle value that the EE uses internally. private IntPtr _handle; } }
// ---------------------------------------------------------------------------------- // // 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. // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; using Microsoft.Azure.Commands.Aks.Generated.Version2017_08_31; using Microsoft.Azure.Commands.Aks.Generated.Version2017_08_31.Models; using Microsoft.Azure.Commands.Aks.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Graph.RBAC.Version1_6; using Microsoft.Azure.Graph.RBAC.Version1_6.Models; using Microsoft.Azure.Management.Authorization.Version2015_07_01; using Microsoft.Azure.Management.Authorization.Version2015_07_01.Models; using Microsoft.Azure.Management.Internal.Resources; using Microsoft.Rest.Azure; using Newtonsoft.Json; using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Commands.Aks.Properties; using Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.Azure.Commands.Aks { public abstract class CreateOrUpdateKubeBase : KubeCmdletBase { protected const string DefaultParamSet = "defaultParameterSet"; protected const string SpParamSet = "servicePrincipalParameterSet"; protected readonly Regex DnsRegex = new Regex("[^A-Za-z0-9-]"); [Parameter( Position = 0, Mandatory = true, ParameterSetName = DefaultParamSet, HelpMessage = "Resource Group Name.")] [ResourceGroupCompleter()] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Position = 1, Mandatory = true, ParameterSetName = DefaultParamSet, HelpMessage = "Kubernetes managed cluster Name.")] [ValidateNotNullOrEmpty] [ValidatePattern("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$")] [ValidateLength(2, 64)] public string Name { get; set; } [Parameter( Position = 2, Mandatory = false, ParameterSetName = DefaultParamSet, HelpMessage = "The client id and client secret associated with the AAD application / service principal.")] public PSCredential ClientIdAndSecret { get; set; } [Parameter(Mandatory = false, HelpMessage = "Azure location for the cluster. Defaults to the location of the resource group.")] [LocationCompleter("Microsoft.ContainerService/managedClusters")] public string Location { get; set; } [Parameter(Mandatory = false, HelpMessage = "User name for the Linux Virtual Machines.")] public string AdminUserName { get; set; } = "azureuser"; [Parameter(Mandatory = false, HelpMessage = "The DNS name prefix for the cluster.")] public string DnsNamePrefix { get; set; } [Parameter(Mandatory = false, HelpMessage = "The version of Kubernetes to use for creating the cluster.")] [PSArgumentCompleter("1.7.7", "1.8.1")] public string KubernetesVersion { get; set; } = "1.8.1"; [Parameter(Mandatory = false, HelpMessage = "The default number of nodes for the node pools.")] public int NodeCount { get; set; } = 3; [Parameter(Mandatory = false, HelpMessage = "The default number of nodes for the node pools.")] public int NodeOsDiskSize { get; set; } [Parameter(Mandatory = false, HelpMessage = "The size of the Virtual Machine.")] public string NodeVmSize { get; set; } = "Standard_D2_v2"; [Parameter( Mandatory = false, HelpMessage = "SSH key file value or key file path. Defaults to {HOME}/.ssh/id_rsa.pub.")] [Alias("SshKeyPath")] public string SshKeyValue { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } [Parameter(Mandatory = false)] public Hashtable Tag { get; set; } protected ManagedCluster BuildNewCluster() { if (!string.IsNullOrEmpty(ResourceGroupName) && string.IsNullOrEmpty(Location)) { var rg = RmClient.ResourceGroups.Get(ResourceGroupName); Location = rg.Location; var validLocations = RmClient.Providers.Get("Microsoft.ContainerService").ResourceTypes.ToList().Find(x => x.ResourceType.Equals("managedClusters")).Locations; validLocations = validLocations.Select(l => l.Replace(" ", string.Empty).Replace("-", string.Empty).ToLower()).ToList(); // If the ResourceGroup location name is not valid, use "East US" if (!validLocations.Contains(rg.Location)) { // Add check in case East US is removed from the list of valid locations if (validLocations.Contains("eastus")) { Location = "eastus"; } else { Location = validLocations[0]; } WriteVerbose(string.Format(Resources.UsingDefaultLocation, Location)); } else { WriteVerbose(string.Format(Resources.UsingLocationFromTheResourceGroup, Location, ResourceGroupName)); } } if (string.IsNullOrEmpty(DnsNamePrefix)) { DnsNamePrefix = DefaultDnsPrefix(); } WriteVerbose(string.Format(Resources.UsingDnsNamePrefix, DnsNamePrefix)); SshKeyValue = GetSshKey(SshKeyValue); var defaultAgentPoolProfile = new ContainerServiceAgentPoolProfile( "default", NodeVmSize, NodeCount, NodeOsDiskSize, DnsNamePrefix); var pubKey = new List<ContainerServiceSshPublicKey> {new ContainerServiceSshPublicKey(SshKeyValue)}; var linuxProfile = new ContainerServiceLinuxProfile(AdminUserName, new ContainerServiceSshConfiguration(pubKey)); var acsServicePrincipal = EnsureServicePrincipal(ClientIdAndSecret?.UserName, ClientIdAndSecret?.Password?.ToString()); var spProfile = new ContainerServiceServicePrincipalProfile( acsServicePrincipal.SpId, acsServicePrincipal.ClientSecret); WriteVerbose(string.Format(Resources.DeployingYourManagedKubeCluster, AcsSpFilePath)); var managedCluster = new ManagedCluster( Location, name: Name, tags: TagsConversionHelper.CreateTagDictionary(Tag, true), dnsPrefix: DnsNamePrefix, kubernetesVersion: KubernetesVersion, agentPoolProfiles: new List<ContainerServiceAgentPoolProfile> {defaultAgentPoolProfile}, linuxProfile: linuxProfile, servicePrincipalProfile: spProfile); return managedCluster; } /// <summary> /// Fetch SSH public key string /// </summary> /// <param name="sshKeyOrFile">a string representing either the file location, the ssh key pub data or null.</param> /// <returns>SSH public key data</returns> /// <exception cref="ArgumentException">The SSH key or file argument was null and there was no default pub key in path.</exception> protected string GetSshKey(string sshKeyOrFile) { const string helpLink = "https://docs.microsoft.com/en-us/azure/virtual-machines/linux/mac-create-ssh-keys"; // SSH key was specified as either a file or as key data if (!string.IsNullOrEmpty(SshKeyValue)) { if (File.Exists(sshKeyOrFile)) { WriteVerbose(string.Format(Resources.FetchSshPublicKeyFromFile, sshKeyOrFile)); return File.ReadAllText(sshKeyOrFile); } WriteVerbose(Resources.UsingSshPublicKeyDataAsCommandLineString); return sshKeyOrFile; } // SSH key value was not specified, so look in the home directory for the default pub key var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh", "id_rsa.pub"); if (!AzureSession.Instance.DataStore.FileExists(path)) { throw new ArgumentException(string.Format(Resources.CouldNotFindSshPublicKeyInError, path, helpLink)); } WriteVerbose(string.Format(Resources.FetchSshPublicKeyFromFile, path)); return AzureSession.Instance.DataStore.ReadFileAsText(path); // we didn't find an SSH key and there was no SSH public key in the home directory } protected AcsServicePrincipal EnsureServicePrincipal(string spId = null, string clientSecret = null) { var acsServicePrincipal = LoadServicePrincipal(); if (acsServicePrincipal == null) { WriteVerbose(string.Format( Resources.NoServicePrincipalFoundCreatingANewServicePrincipal, AcsSpFilePath)); // if nothing to load, make one if (clientSecret == null) { clientSecret = RandomBase64String(16); } var salt = RandomBase64String(3); var url = $"http://{salt}.{DnsNamePrefix}.{Location}.cloudapp.azure.com"; acsServicePrincipal = BuildServicePrincipal(Name, url, clientSecret); WriteVerbose(Resources.CreatedANewServicePrincipalAndAssignedTheContributorRole); StoreServicePrincipal(acsServicePrincipal); } return acsServicePrincipal; } private AcsServicePrincipal BuildServicePrincipal(string name, string url, string clientSecret) { var pwCreds = new PasswordCredential( value: clientSecret, startDate: DateTime.UtcNow, endDate: DateTime.UtcNow.AddYears(2)); var app = GraphClient.Applications.Create(new ApplicationCreateParameters( false, name, new List<string> { url }, url, passwordCredentials: new List<PasswordCredential> { pwCreds })); ServicePrincipal sp = null; var success = RetryAction(() => { var spCreateParams = new ServicePrincipalCreateParameters( app.AppId, true, passwordCredentials: new List<PasswordCredential> { pwCreds }); sp = GraphClient.ServicePrincipals.Create(spCreateParams); }, Resources.ServicePrincipalCreate); if (!success) { throw new CmdletInvocationException(Resources.CouldNotCreateAServicePrincipalWithTheRightPermissionsAreYouAnOwner); } AddSubscriptionRoleAssignment("Contributor", sp.ObjectId); return new AcsServicePrincipal { SpId = app.AppId, ClientSecret = clientSecret }; } protected bool Exists() { try { var exists = Client.ManagedClusters.Get(ResourceGroupName, Name) != null; WriteVerbose(string.Format(Resources.ClusterExists, exists)); return exists; } catch (CloudException) { WriteVerbose(Resources.ClusterDoesNotExist); return false; } } protected void AddSubscriptionRoleAssignment(string role, string appId) { var scope = $"/subscriptions/{DefaultContext.Subscription.Id}"; var roleId = GetRoleId(role, scope); var success = RetryAction(() => AuthClient.RoleAssignments.Create(scope, appId, new RoleAssignmentCreateParameters() { Properties = new RoleAssignmentProperties(roleId, appId) }), Resources.AddRoleAssignment); if (!success) { throw new CmdletInvocationException( Resources.CouldNotCreateAServicePrincipalWithTheRightPermissionsAreYouAnOwner); } } protected string GetRoleId(string roleName, string scope) { return AuthClient.RoleDefinitions.List(scope, $"roleName eq '{roleName}'").First().Id; } protected bool RetryAction(Action action, string actionName = null) { var success = false; foreach (var i in Enumerable.Range(1, 10)) { try { action(); success = true; break; } catch (Exception ex) { WriteVerbose(string.Format(Resources.RetryAfterActionError, i, actionName ?? "action", ex.Message)); TestMockSupport.Delay(1000 * i); } } return success; } protected AcsServicePrincipal LoadServicePrincipal() { var config = LoadServicePrincipals(); return config?[DefaultContext.Subscription.Id]; } protected Dictionary<string, AcsServicePrincipal> LoadServicePrincipals() { return AzureSession.Instance.DataStore.FileExists(AcsSpFilePath) ? JsonConvert.DeserializeObject<Dictionary<string, AcsServicePrincipal>>( AzureSession.Instance.DataStore.ReadFileAsText(AcsSpFilePath)) : null; } protected void StoreServicePrincipal(AcsServicePrincipal acsServicePrincipal) { var config = LoadServicePrincipals() ?? new Dictionary<string, AcsServicePrincipal>(); config[DefaultContext.Subscription.Id] = acsServicePrincipal; AzureSession.Instance.DataStore.CreateDirectory(Path.GetDirectoryName(AcsSpFilePath)); AzureSession.Instance.DataStore.WriteFile(AcsSpFilePath, JsonConvert.SerializeObject(config)); } protected static string RandomBase64String(int size) { var rnd = new Random(); var secretBytes = new byte[size]; rnd.NextBytes(secretBytes); return Convert.ToBase64String(secretBytes); } /// <summary> /// Build a semi-random DNS prefix based on the name of the cluster, resource group, and last 6 digits of the subscription /// </summary> /// <returns>Default DNS prefix string</returns> protected string DefaultDnsPrefix() { var namePart = string.Join("", DnsRegex.Replace(Name, "").Take(10)); if (char.IsDigit(namePart[0])) { namePart = "a" + string.Join("", namePart.Skip(1)); } var rgPart = DnsRegex.Replace(ResourceGroupName, ""); var subPart = string.Join("", DefaultContext.Subscription.Id.Take(6)); return $"{namePart}-{rgPart}-{subPart}"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System { // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [Runtime.Versioning.NonVersionable] // This only applies to field layout [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid> { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; // Do not rename (binary serialization) private short _b; // Do not rename (binary serialization) private short _c; // Do not rename (binary serialization) private byte _d; // Do not rename (binary serialization) private byte _e; // Do not rename (binary serialization) private byte _f; // Do not rename (binary serialization) private byte _g; // Do not rename (binary serialization) private byte _h; // Do not rename (binary serialization) private byte _i; // Do not rename (binary serialization) private byte _j; // Do not rename (binary serialization) private byte _k; // Do not rename (binary serialization) //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. public Guid(byte[] b) : this(new ReadOnlySpan<byte>(b ?? throw new ArgumentNullException(nameof(b)))) { } // Creates a new guid from a read-only span. public Guid(ReadOnlySpan<byte> b) { if (b.Length != 16) throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b)); _a = b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0]; _b = (short)(b[5] << 8 | b[4]); _c = (short)(b[7] << 8 | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant(false)] public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. // public Guid(int a, short b, short c, byte[] d) { if (d == null) throw new ArgumentNullException(nameof(d)); // Check that array is not too big if (d.Length != 8) throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d)); _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } [Flags] private enum GuidStyles { None = 0x00000000, AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces AllowDashes = 0x00000004, //Allow the guid to contain dash group separators AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd} RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens RequireBraces = 0x00000020, //Require the guid to be enclosed in braces RequireDashes = 0x00000040, //Require the guid to contain dash group separators RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd} HexFormat = RequireBraces | RequireHexPrefix, /* X */ NumberFormat = None, /* N */ DigitFormat = RequireDashes, /* D */ BraceFormat = RequireBraces | RequireDashes, /* B */ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix, } private enum GuidParseThrowStyle { None = 0, All = 1, AllButOverflow = 2 } private enum ParseFailureKind { None = 0, ArgumentNull = 1, Format = 2, FormatWithParameter = 3, NativeException = 4, FormatWithInnerException = 5 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { internal Guid _parsedGuid; internal GuidParseThrowStyle _throwStyle; private ParseFailureKind _failure; private string _failureMessageID; private object _failureMessageFormatArgument; private string _failureArgumentName; private Exception _innerException; internal void Init(GuidParseThrowStyle canThrow) { _throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { _failure = ParseFailureKind.NativeException; _innerException = nativeException; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { SetFailure(failure, failureMessageID, null, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); _failure = failure; _failureMessageID = failureMessageID; _failureMessageFormatArgument = failureMessageFormatArgument; _failureArgumentName = failureArgumentName; _innerException = innerException; if (_throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(_failureArgumentName, SR.GetResourceString(_failureMessageID)); case ParseFailureKind.FormatWithInnerException: return new FormatException(SR.GetResourceString(_failureMessageID), _innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(SR.Format(SR.GetResourceString(_failureMessageID), _failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(SR.GetResourceString(_failureMessageID)); case ParseFailureKind.NativeException: return _innerException; default: Debug.Fail("Unknown GuidParseFailure: " + _failure); return new FormatException(SR.Format_GuidUnrecognized); } } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" // public Guid(string g) { if (g == null) { throw new ArgumentNullException(nameof(g)); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g.AsReadOnlySpan(), GuidStyles.Any, ref result)) { this = result._parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(string input) => Parse(input != null ? input.AsReadOnlySpan() : throw new ArgumentNullException(nameof(input))); public static Guid Parse(ReadOnlySpan<char> input) { GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, GuidStyles.Any, ref result)) { return result._parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParse(string input, out Guid result) { if (input == null) { result = default(Guid); return false; } return TryParse(input.AsReadOnlySpan(), out result); } public static bool TryParse(ReadOnlySpan<char> input, out Guid result) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult._parsedGuid; return true; } else { result = default(Guid); return false; } } public static Guid ParseExact(string input, string format) => ParseExact(input != null ? input.AsReadOnlySpan() : throw new ArgumentNullException(nameof(input)), format); public static Guid ParseExact(ReadOnlySpan<char> input, string format) { if (format == null) { throw new ArgumentNullException(nameof(format)); } if (format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } GuidStyles style; switch (format[0]) { case 'D': case 'd': style = GuidStyles.DigitFormat; break; case 'N': case 'n': style = GuidStyles.NumberFormat; break; case 'B': case 'b': style = GuidStyles.BraceFormat; break; case 'P': case 'p': style = GuidStyles.ParenthesisFormat; break; case 'X': case 'x': style = GuidStyles.HexFormat; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, style, ref result)) { return result._parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParseExact(string input, string format, out Guid result) { if (input == null) { result = default(Guid); return false; } return TryParseExact(input.AsReadOnlySpan(), format, out result); } public static bool TryParseExact(ReadOnlySpan<char> input, string format, out Guid result) { if (format == null || format.Length != 1) { result = default(Guid); return false; } GuidStyles style; switch (format[0]) { case 'D': case 'd': style = GuidStyles.DigitFormat; break; case 'N': case 'n': style = GuidStyles.NumberFormat; break; case 'B': case 'b': style = GuidStyles.BraceFormat; break; case 'P': case 'p': style = GuidStyles.ParenthesisFormat; break; case 'X': case 'x': style = GuidStyles.HexFormat; break; default: // invalid guid format specification result = default(Guid); return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult._parsedGuid; return true; } else { result = default(Guid); return false; } } private static bool TryParseGuid(ReadOnlySpan<char> guidString, GuidStyles flags, ref GuidResult result) { guidString = guidString.Trim(); // Remove whitespace from beginning and end if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } // Check for dashes bool dashesExistInString = guidString.IndexOf('-') >= 0; if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } // Check for braces bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); if (bracesExistInString) { if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) { // braces are not allowed result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } // Check for parenthesis bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); if (parenthesisExistInString) { if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) { // parenthesis are not allowed result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized)); return false; } } try { // let's get on with the parsing if (dashesExistInString) { // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] return TryParseGuidWithDashes(guidString, ref result); } else if (bracesExistInString) { // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} return TryParseGuidWithHexPrefix(guidString, ref result); } else { // Check if it's of the form dddddddddddddddddddddddddddddddd return TryParseGuidWithNoStyle(guidString, ref result); } } catch (IndexOutOfRangeException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex); return false; } } // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} private static bool TryParseGuidWithHexPrefix(ReadOnlySpan<char> guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if (guidString.Length == 0 || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace)); return false; } // Check for '0x' if (!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, etc}"); return false; } // Find the end of this hex number (since it is not fixed length) numStart = 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } if (!StringToInt(guidString.Slice(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result)) return false; // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } // Read in the number if (!StringToShort(guidString.Slice(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result)) return false; // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } // Read in the number if (!StringToShort(guidString.Slice(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result)) return false; // Check for '{' if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace)); return false; } // Prepare for loop numLen++; Span<byte> bytes = stackalloc byte[8]; for (int i = 0; i < bytes.Length; i++) { // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{... { ... 0xdd, ...}}"); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if (i < 7) // first 7 cases { numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma)); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBraceAfterLastNumber)); return false; } } // Read in the number int signedNumber; if (!StringToInt(guidString.Slice(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result)) { return false; } uint number = (uint)signedNumber; // check for overflow if (number > 255) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Overflow_Byte)); return false; } bytes[i] = (byte)number; } result._parsedGuid._d = bytes[0]; result._parsedGuid._e = bytes[1]; result._parsedGuid._f = bytes[2]; result._parsedGuid._g = bytes[3]; result._parsedGuid._h = bytes[4]; result._parsedGuid._i = bytes[5]; result._parsedGuid._j = bytes[6]; result._parsedGuid._k = bytes[7]; // Check for last '}' if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidEndBrace)); return false; } // Check if we have extra characters at the end if (numStart + numLen + 1 != guidString.Length - 1) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_ExtraJunkAtEnd)); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(ReadOnlySpan<char> guidString, ref GuidResult result) { int startPos = 0; int temp; long templ; int currentPos = 0; if (guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } for (int i = 0; i < guidString.Length; i++) { char ch = guidString[i]; if (ch >= '0' && ch <= '9') { continue; } else { char upperCaseCh = char.ToUpperInvariant(ch); if (upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar)); return false; } if (!StringToInt(guidString.Slice(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Slice(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Slice(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Slice(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result)) return false; startPos += 4; currentPos = startPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } result._parsedGuid._d = (byte)(temp >> 8); result._parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result._parsedGuid._f = (byte)(temp >> 8); result._parsedGuid._g = (byte)(temp); temp = (int)(templ); result._parsedGuid._h = (byte)(temp >> 24); result._parsedGuid._i = (byte)(temp >> 16); result._parsedGuid._j = (byte)(temp >> 8); result._parsedGuid._k = (byte)(temp); return true; } // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] private static bool TryParseGuidWithDashes(ReadOnlySpan<char> guidString, ref GuidResult result) { int startPos = 0; int temp; long templ; int currentPos = 0; // check to see that it's the proper length if (guidString[0] == '{') { if (guidString.Length != 38 || guidString[37] != '}') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } startPos = 1; } else if (guidString[0] == '(') { if (guidString.Length != 38 || guidString[37] != ')') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } startPos = 1; } else if (guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } if (guidString[8 + startPos] != '-' || guidString[13 + startPos] != '-' || guidString[18 + startPos] != '-' || guidString[23 + startPos] != '-') { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidDashes)); return false; } currentPos = startPos; if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result)) return false; result._parsedGuid._a = temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result._parsedGuid._b = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result._parsedGuid._c = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; ++currentPos; //Increment past the '-'; startPos = currentPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen)); return false; } result._parsedGuid._d = (byte)(temp >> 8); result._parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result._parsedGuid._f = (byte)(temp >> 8); result._parsedGuid._g = (byte)(temp); temp = (int)(templ); result._parsedGuid._h = (byte)(temp >> 24); result._parsedGuid._i = (byte)(temp >> 16); result._parsedGuid._j = (byte)(temp >> 8); result._parsedGuid._k = (byte)(temp); return true; } private static bool StringToShort(ReadOnlySpan<char> str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { int parsePos = 0; return StringToShort(str, ref parsePos, requiredLength, flags, out result, ref parseResult); } private static bool StringToShort(ReadOnlySpan<char> str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, ref parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } private static bool StringToInt(ReadOnlySpan<char> str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { int parsePos = 0; return StringToInt(str, ref parsePos, requiredLength, flags, out result, ref parseResult); } private static bool StringToInt(ReadOnlySpan<char> str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = parsePos; try { result = ParseNumbers.StringToInt(str, 16, flags, ref parsePos); } catch (OverflowException ex) { if (parseResult._throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(SR.Format_GuidUnrecognized, ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult._throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } //If we didn't parse enough characters, there's clearly an error. if (requiredLength != -1 && parsePos - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar)); return false; } return true; } private static unsafe bool StringToLong(ReadOnlySpan<char> str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, ref parsePos); } catch (OverflowException ex) { if (parseResult._throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(SR.Format_GuidUnrecognized, ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult._throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } return true; } private static ReadOnlySpan<char> EatAllWhitespace(ReadOnlySpan<char> str) { // Find the first whitespace character. If there is none, just return the input. int i; for (i = 0; i < str.Length && !char.IsWhiteSpace(str[i]); i++) ; if (i == str.Length) { return str; } // There was at least one whitespace. Copy over everything prior to it to a new array. var chArr = new char[str.Length]; int newLength = 0; if (i > 0) { newLength = i; str.Slice(0, i).CopyTo(chArr); } // Loop through the remaining chars, copying over non-whitespace. for (; i < str.Length; i++) { char c = str[i]; if (!char.IsWhiteSpace(c)) { chArr[newLength++] = c; } } // Return the string with the whitespace removed. return new ReadOnlySpan<char>(chArr, 0, newLength); } private static bool IsHexPrefix(ReadOnlySpan<char> str, int i) => i + 1 < str.Length && str[i] == '0' && (str[i + 1] == 'x' || char.ToLowerInvariant(str[i + 1]) == 'x'); [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteByteHelper(Span<byte> destination) { destination[0] = (byte)(_a); destination[1] = (byte)(_a >> 8); destination[2] = (byte)(_a >> 16); destination[3] = (byte)(_a >> 24); destination[4] = (byte)(_b); destination[5] = (byte)(_b >> 8); destination[6] = (byte)(_c); destination[7] = (byte)(_c >> 8); destination[8] = _d; destination[9] = _e; destination[10] = _f; destination[11] = _g; destination[12] = _h; destination[13] = _i; destination[14] = _j; destination[15] = _k; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { var g = new byte[16]; WriteByteHelper(g); return g; } // Returns whether bytes are sucessfully written to given span. public bool TryWriteBytes(Span<byte> destination) { if (destination.Length < 16) return false; WriteByteHelper(destination); return true; } // Returns the guid in "registry" format. public override string ToString() { return ToString("D", null); } public override int GetHashCode() { // Simply XOR all the bits of the GUID 32 bits at a time. return _a ^ Unsafe.Add(ref _a, 1) ^ Unsafe.Add(ref _a, 2) ^ Unsafe.Add(ref _a, 3); } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(object o) { Guid g; // Check that o is a Guid first if (o == null || !(o is Guid)) return false; else g = (Guid)o; // Now compare each of the elements return g._a == _a && Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) && Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) && Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3); } public bool Equals(Guid g) { // Now compare each of the elements return g._a == _a && Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) && Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) && Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3); } private int GetResult(uint me, uint them) { if (me < them) { return -1; } return 1; } public int CompareTo(object value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value)); } Guid g = (Guid)value; if (g._a != _a) { return GetResult((uint)_a, (uint)g._a); } if (g._b != _b) { return GetResult((uint)_b, (uint)g._b); } if (g._c != _c) { return GetResult((uint)_c, (uint)g._c); } if (g._d != _d) { return GetResult(_d, g._d); } if (g._e != _e) { return GetResult(_e, g._e); } if (g._f != _f) { return GetResult(_f, g._f); } if (g._g != _g) { return GetResult(_g, g._g); } if (g._h != _h) { return GetResult(_h, g._h); } if (g._i != _i) { return GetResult(_i, g._i); } if (g._j != _j) { return GetResult(_j, g._j); } if (g._k != _k) { return GetResult(_k, g._k); } return 0; } public int CompareTo(Guid value) { if (value._a != _a) { return GetResult((uint)_a, (uint)value._a); } if (value._b != _b) { return GetResult((uint)_b, (uint)value._b); } if (value._c != _c) { return GetResult((uint)_c, (uint)value._c); } if (value._d != _d) { return GetResult(_d, value._d); } if (value._e != _e) { return GetResult(_e, value._e); } if (value._f != _f) { return GetResult(_f, value._f); } if (value._g != _g) { return GetResult(_g, value._g); } if (value._h != _h) { return GetResult(_h, value._h); } if (value._i != _i) { return GetResult(_i, value._i); } if (value._j != _j) { return GetResult(_j, value._j); } if (value._k != _k) { return GetResult(_k, value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements return a._a == b._a && Unsafe.Add(ref a._a, 1) == Unsafe.Add(ref b._a, 1) && Unsafe.Add(ref a._a, 2) == Unsafe.Add(ref b._a, 2) && Unsafe.Add(ref a._a, 3) == Unsafe.Add(ref b._a, 3); } public static bool operator !=(Guid a, Guid b) { // Now compare each of the elements return a._a != b._a || Unsafe.Add(ref a._a, 1) != Unsafe.Add(ref b._a, 1) || Unsafe.Add(ref a._a, 2) != Unsafe.Add(ref b._a, 2) || Unsafe.Add(ref a._a, 3) != Unsafe.Add(ref b._a, 3); } public string ToString(string format) { return ToString(format, null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static char HexToChar(int a) { a = a & 0xf; return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30); } unsafe private static int HexsToChars(char* guidChars, int a, int b) { guidChars[0] = HexToChar(a >> 4); guidChars[1] = HexToChar(a); guidChars[2] = HexToChar(b >> 4); guidChars[3] = HexToChar(b); return 4; } unsafe private static int HexsToCharsHexOutput(char* guidChars, int a, int b) { guidChars[0] = '0'; guidChars[1] = 'x'; guidChars[2] = HexToChar(a >> 4); guidChars[3] = HexToChar(a); guidChars[4] = ','; guidChars[5] = '0'; guidChars[6] = 'x'; guidChars[7] = HexToChar(b >> 4); guidChars[8] = HexToChar(b); return 9; } // IFormattable interface // We currently ignore provider public string ToString(string format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; // all acceptable format strings are of length 1 if (format.Length != 1) throw new FormatException(SR.Format_InvalidGuidFormatSpecification); int guidSize; switch (format[0]) { case 'D': case 'd': guidSize = 36; break; case 'N': case 'n': guidSize = 32; break; case 'B': case 'b': case 'P': case 'p': guidSize = 38; break; case 'X': case 'x': guidSize = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } string guidString = string.FastAllocateString(guidSize); int bytesWritten; bool result = TryFormat(new Span<char>(ref guidString.GetRawStringData(), guidString.Length), out bytesWritten, format); Debug.Assert(result && bytesWritten == guidString.Length, "Formatting guid should have succeeded."); return guidString; } // Returns whether the guid is successfully formatted as a span. public bool TryFormat(Span<char> destination, out int charsWritten, string format = null) { if (format == null || format.Length == 0) format = "D"; // all acceptable format strings are of length 1 if (format.Length != 1) throw new FormatException(SR.Format_InvalidGuidFormatSpecification); bool dash = true; bool hex = false; int braces = 0; int guidSize; switch (format[0]) { case 'D': case 'd': guidSize = 36; break; case 'N': case 'n': dash = false; guidSize = 32; break; case 'B': case 'b': braces = '{' + ('}' << 16); guidSize = 38; break; case 'P': case 'p': braces = '(' + (')' << 16); guidSize = 38; break; case 'X': case 'x': braces = '{' + ('}' << 16); dash = false; hex = true; guidSize = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } if (destination.Length < guidSize) { charsWritten = 0; return false; } unsafe { fixed (char* guidChars = &destination.DangerousGetPinnableReference()) { char * p = guidChars; if (braces != 0) *p++ = (char)braces; if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _a >> 24, _a >> 16); p += HexsToChars(p, _a >> 8, _a); *p++ = ','; *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _b >> 8, _b); *p++ = ','; *p++ = '0'; *p++ = 'x'; p += HexsToChars(p, _c >> 8, _c); *p++ = ','; *p++ = '{'; p += HexsToCharsHexOutput(p, _d, _e); *p++ = ','; p += HexsToCharsHexOutput(p, _f, _g); *p++ = ','; p += HexsToCharsHexOutput(p, _h, _i); *p++ = ','; p += HexsToCharsHexOutput(p, _j, _k); *p++ = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] p += HexsToChars(p, _a >> 24, _a >> 16); p += HexsToChars(p, _a >> 8, _a); if (dash) *p++ = '-'; p += HexsToChars(p, _b >> 8, _b); if (dash) *p++ = '-'; p += HexsToChars(p, _c >> 8, _c); if (dash) *p++ = '-'; p += HexsToChars(p, _d, _e); if (dash) *p++ = '-'; p += HexsToChars(p, _f, _g); p += HexsToChars(p, _h, _i); p += HexsToChars(p, _j, _k); } if (braces != 0) *p++ = (char)(braces >> 16); Debug.Assert(p - guidChars == guidSize); } } charsWritten = guidSize; return true; } } }
using StructureMap.Building; using StructureMap.Building.Interception; using StructureMap.TypeRules; using System; using System.Linq.Expressions; using System.Reflection; namespace StructureMap.Pipeline { public class SmartInstance<T> : SmartInstance<T, T> { public SmartInstance(Expression<Func<T>> constructorSelection = null) : base(constructorSelection) { } } /// <summary> /// Instance that builds objects with by calling constructor functions and using setter properties /// </summary> /// <typeparam name="T">The concrete type constructed by SmartInstance</typeparam> /// <typeparam name="TPluginType">The "PluginType" that this instance satisfies</typeparam> public class SmartInstance<T, TPluginType> : ExpressedInstance<SmartInstance<T, TPluginType>, T, TPluginType>, IConfiguredInstance, IOverridableInstance where T : TPluginType { private readonly ConstructorInstance _inner = new ConstructorInstance(typeof(T)); public SmartInstance(Expression<Func<T>> constructorSelection = null) { if (constructorSelection != null) { SelectConstructor(constructorSelection); } typeof(T).GetTypeInfo().ForAttribute<StructureMapAttribute>(x => x.Alter(this)); } public SmartInstance<T, TPluginType> SelectConstructor(Expression<Func<T>> constructor) { var finder = new ConstructorFinderVisitor(typeof(T)); finder.Visit(constructor); _inner.Constructor = finder.Constructor; return this; } protected override SmartInstance<T, TPluginType> thisInstance { get { return this; } } public override Instance ToNamedClone(string name) { return _inner.ToNamedClone(name); } public override string Name { get { return _inner.Name; } set { _inner.Name = value; } } public override bool HasExplicitName() { return _inner.HasExplicitName(); } /// <summary> /// Set simple setter properties /// </summary> /// <param name="action"></param> /// <returns></returns> public SmartInstance<T, TPluginType> SetProperty(Action<T> action) { AddInterceptor(InterceptorFactory.ForAction("Setting property", action)); return this; } /// <summary> /// Inline definition of a setter dependency. The property name is specified with an Expression /// </summary> /// <typeparam name="TSettertype"></typeparam> /// <param name="expression"></param> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TSettertype> Setter<TSettertype>( Expression<Func<T, TSettertype>> expression) { var propertyName = ReflectionHelper.GetProperty(expression).Name; return new DependencyExpression<SmartInstance<T, TPluginType>, TSettertype>(this, propertyName); } public override IDependencySource ToDependencySource(Type pluginType) { return _inner.ToDependencySource(pluginType); } public override IDependencySource ToBuilder(Type pluginType, Policies policies) { return _inner.ToBuilder(pluginType, policies); } public override string Description { get { return _inner.Description; } } public override Type ReturnedType { get { return typeof(T); } } Type IConfiguredInstance.PluggedType { get { return typeof(T); } } DependencyCollection IConfiguredInstance.Dependencies { get { return _inner.Dependencies; } } Instance IOverridableInstance.Override(ExplicitArguments arguments) { return _inner.Override(arguments); } ConstructorInfo IConfiguredInstance.Constructor { get { return _inner.Constructor; } set { _inner.Constructor = value; } } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type. Do not /// use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="TCtorType"></typeparam> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TCtorType> Ctor<TCtorType>() { return Ctor<TCtorType>(null); } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type and constructor name. /// Use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="TCtorType"></typeparam> /// <param name="constructorArg"></param> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TCtorType> Ctor<TCtorType>(string constructorArg) { return new DependencyExpression<SmartInstance<T, TPluginType>, TCtorType>(this, constructorArg); } /// <summary> /// Inline definition of a setter dependency. Only use this method if there /// is only a single property of the TSetterType /// </summary> /// <typeparam name="TSetterType"></typeparam> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TSetterType> Setter<TSetterType>() { return Ctor<TSetterType>(); } /// <summary> /// Inline definition of a setter dependency. Only use this method if there /// is only a single property of the TSetterType /// </summary> /// <typeparam name="TSetterType"></typeparam> /// <param name="setterName">The name of the property</param> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TSetterType> Setter<TSetterType>(string setterName) { return Ctor<TSetterType>(setterName); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="TElement"></typeparam> /// <returns></returns> public ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement> EnumerableOf<TElement>() { if (typeof(TElement).IsArray) { throw new ArgumentException("Please specify the element type in the call to TheArrayOf"); } return new ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement>(this, null); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type and the specified setter property or constructor argument name. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="TElement"></typeparam> /// <param name="ctorOrPropertyName"></param> /// <returns></returns> public ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement> EnumerableOf<TElement>(string ctorOrPropertyName) { return new ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement>(this, ctorOrPropertyName); } } }
/* * ErrObject.cs - Implementation of the * "Microsoft.VisualBasic.ErrObject" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Microsoft.VisualBasic { using System; using System.IO; using System.ComponentModel; using System.Runtime.InteropServices; using Microsoft.VisualBasic.CompilerServices; public sealed class ErrObject { // Internal state. private Exception exception; private String description; private int erl; private int helpContext; private String helpFile; private int number; private String source; // Constructor. internal ErrObject() { Clear(); } // Clear the error information. public void Clear() { exception = null; description = String.Empty; erl = 0; helpContext = 0; helpFile = String.Empty; number = -1; source = String.Empty; } // Get the exception within this error object. public Exception GetException() { return exception; } // Set the exception within this error object. internal void SetException(Exception e) { exception = e; } internal void SetException(Exception e, int erl) { exception = e; this.erl = erl; } // Raise a particular error. public void Raise(int Number, [Optional] [DefaultValue(null)] Object Source, [Optional] [DefaultValue(null)] Object Description, [Optional] [DefaultValue(null)] Object HelpFile, [Optional] [DefaultValue(null)] Object HelpContext) { if(Number == 0) { throw new ArgumentException (S._("VB_InvalidErrorNumber"), "Number"); } this.Number = Number; this.Source = StringType.FromObject(Source); this.Description = StringType.FromObject(Description); this.HelpFile = StringType.FromObject(HelpFile); this.HelpContext = IntegerType.FromObject(HelpContext); this.exception = CreateExceptionFromNumber (Number, this.Description); #if !ECMA_COMPAT this.exception.Source = this.Source; this.exception.HelpLink = this.HelpFile; #endif throw this.exception; } // Get or set the error's description. public String Description { get { return description; } set { description = value; } } // Get the error's ERL value. public int Erl { get { return erl; } } // Get or set the error's help context. public int HelpContext { get { return helpContext; } set { helpContext = value; } } // Get or set the error's help file. public String HelpFile { get { return helpFile; } set { helpFile = value; #if !ECMA_COMPAT if(exception != null) { exception.HelpLink = helpFile; } #endif } } // Get the last-occurring Win32 error code. public int LastDllError { get { return Marshal.GetLastWin32Error(); } } // Get a standard number for an exception. internal static int GetNumberForException(Exception exception) { if(exception is OverflowException) { return 6; } if(exception is OutOfMemoryException) { return 7; } if(exception is IndexOutOfRangeException || exception is RankException || exception is ArrayTypeMismatchException) { return 9; } if(exception is DivideByZeroException) { return 11; } if(exception is InvalidCastException || exception is NotSupportedException || exception is FormatException) { return 13; } if(exception is NotFiniteNumberException) { if(((NotFiniteNumberException)exception).OffendingNumber != 0.0) { return 6; } else { return 11; } } if(exception is StackOverflowException) { return 28; } #if !ECMA_COMPAT if(exception is DllNotFoundException) { return 53; } #endif if(exception is FileNotFoundException) { return 53; } if(exception is IOException) { return 57; } if(exception is EndOfStreamException) { return 62; } if(exception is DirectoryNotFoundException) { return 76; } if(exception is NullReferenceException) { return 91; } #if CONFIG_COM_INTEROP if(exception is COMException) { return ((COMException)exception).ErrorCode; } if(exception is SEHException) { return 99; } if(exception is InvalidOleVariantTypeException) { return 458; } #endif if(exception is TypeLoadException) { return 429; } if(exception is MissingFieldException) { return 422; } if(exception is MissingMemberException) { return 438; } if(exception is EntryPointNotFoundException) { return 453; } return 5; } // Convert a number into an exception. internal static Exception CreateExceptionFromNumber (int number, String message) { switch(number) { case 3: case 20: case 94: case 100: return new InvalidOperationException(message); case 5: case 446: case 448: case 449: return new ArgumentException(message); case 6: return new OverflowException(message); case 7: case 14: return new OutOfMemoryException(message); case 9: return new IndexOutOfRangeException(message); case 11: return new DivideByZeroException(message); case 13: return new InvalidCastException(message); case 28: return new StackOverflowException(message); case 48: case 429: return new TypeLoadException(message); case 52: case 54: case 55: case 57: case 58: case 59: case 61: case 63: case 67: case 68: case 70: case 71: case 74: case 75: return new IOException(message); case 53: case 432: return new FileNotFoundException(message); case 62: return new EndOfStreamException(message); case 76: return new DirectoryNotFoundException(message); case 91: return new NullReferenceException(message); #if CONFIG_COM_INTEROP case 99: return new SEHException(message); case 458: return new InvalidOleVariantTypeException(message); #endif case 422: return new MissingFieldException(message); case 438: return new MissingMemberException(message); case 453: return new EntryPointNotFoundException(message); default: return new Exception(message); } } // Convert a HRESULT value into an error number. internal static int HResultToNumber(int hr) { if((((uint)hr) & 0xFFFF0000) == 0x800A0000) { return (hr & 0xFFFF); } switch((uint)hr) { case 0x80004001: return 445; case 0x80004002: return 430; case 0x80004004: return 287; case 0x80020001: return 438; case 0x80020003: return 438; case 0x80020004: return 448; case 0x80020005: return 13; case 0x80020006: return 438; case 0x80020007: return 446; case 0x80020008: return 458; case 0x8002000A: return 6; case 0x8002000B: return 9; case 0x8002000C: return 447; case 0x8002000D: return 10; case 0x8002000E: return 450; case 0x8002000F: return 449; case 0x80020011: return 451; case 0x80020012: return 11; case 0x80028016: return 32790; case 0x80028017: return 461; case 0x80028018: return 32792; case 0x80028019: return 32793; case 0x8002801C: return 32796; case 0x8002801D: return 32797; case 0x80028027: return 32807; case 0x80028028: return 32808; case 0x80028029: return 32809; case 0x8002802A: return 32810; case 0x8002802B: return 32811; case 0x8002802C: return 32812; case 0x8002802D: return 32813; case 0x8002802E: return 32814; case 0x8002802F: return 453; case 0x800288BD: return 35005; case 0x800288C5: return 35013; case 0x80028CA0: return 13; case 0x80028CA1: return 9; case 0x80028CA2: return 57; case 0x80028CA3: return 322; case 0x80029C4A: return 48; case 0x80029C83: return 40067; case 0x80029C84: return 40068; case 0x80030001: return 32774; case 0x80030002: return 53; case 0x80030003: return 76; case 0x80030004: return 67; case 0x80030005: return 70; case 0x80030006: return 32772; case 0x80030008: return 7; case 0x80030012: return 67; case 0x80030013: return 70; case 0x80030019: return 32771; case 0x8003001D: return 32773; case 0x8003001E: return 32772; case 0x80030020: return 75; case 0x80030021: return 70; case 0x80030050: return 58; case 0x80030070: return 61; case 0x800300FB: return 32792; case 0x800300FC: return 53; case 0x800300FD: return 32792; case 0x800300FE: return 32768; case 0x80030100: return 70; case 0x80030101: return 70; case 0x80030102: return 32773; case 0x80030103: return 57; case 0x80030104: return 32793; case 0x80030105: return 32793; case 0x80030106: return 32789; case 0x80030107: return 32793; case 0x80030108: return 32793; case 0x80040112: return 429; case 0x80040154: return 429; case 0x800401E3: return 429; case 0x800401E6: return 432; case 0x800401EA: return 432; case 0x800401F3: return 429; case 0x800401F5: return 429; case 0x800401FE: return 429; case 0x80070005: return 70; case 0x8007000E: return 7; case 0x80070057: return 5; case 0x800706BA: return 462; case 0x80080005: return 429; } return hr; } // Get or set the error's number. public int Number { get { if(number == -1) { if(exception != null) { number = GetNumberForException(exception); } else { return 0; } } return number; } set { number = value; } } // Get or set the error's source. public String Source { get { return source; } set { source = value; #if !ECMA_COMPAT if(exception != null) { exception.Source = value; } #endif } } }; // class ErrObject }; // namespace Microsoft.VisualBasic
// Copyright 2017, Google LLC 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. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Debugger.V2 { /// <summary> /// Settings for a <see cref="Debugger2Client"/>. /// </summary> public sealed partial class Debugger2Settings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="Debugger2Settings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="Debugger2Settings"/>. /// </returns> public static Debugger2Settings GetDefault() => new Debugger2Settings(); /// <summary> /// Constructs a new <see cref="Debugger2Settings"/> object with default settings. /// </summary> public Debugger2Settings() { } private Debugger2Settings(Debugger2Settings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); SetBreakpointSettings = existing.SetBreakpointSettings; GetBreakpointSettings = existing.GetBreakpointSettings; DeleteBreakpointSettings = existing.DeleteBreakpointSettings; ListBreakpointsSettings = existing.ListBreakpointsSettings; ListDebuggeesSettings = existing.ListDebuggeesSettings; OnCopy(existing); } partial void OnCopy(Debugger2Settings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="Debugger2Client"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="Debugger2Client"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="Debugger2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="Debugger2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="Debugger2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="Debugger2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="Debugger2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="Debugger2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 60000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(60000), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Debugger2Client.SetBreakpoint</c> and <c>Debugger2Client.SetBreakpointAsync</c>. /// </summary> /// <remarks> /// The default <c>Debugger2Client.SetBreakpoint</c> and /// <c>Debugger2Client.SetBreakpointAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings SetBreakpointSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Debugger2Client.GetBreakpoint</c> and <c>Debugger2Client.GetBreakpointAsync</c>. /// </summary> /// <remarks> /// The default <c>Debugger2Client.GetBreakpoint</c> and /// <c>Debugger2Client.GetBreakpointAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings GetBreakpointSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Debugger2Client.DeleteBreakpoint</c> and <c>Debugger2Client.DeleteBreakpointAsync</c>. /// </summary> /// <remarks> /// The default <c>Debugger2Client.DeleteBreakpoint</c> and /// <c>Debugger2Client.DeleteBreakpointAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings DeleteBreakpointSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Debugger2Client.ListBreakpoints</c> and <c>Debugger2Client.ListBreakpointsAsync</c>. /// </summary> /// <remarks> /// The default <c>Debugger2Client.ListBreakpoints</c> and /// <c>Debugger2Client.ListBreakpointsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListBreakpointsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Debugger2Client.ListDebuggees</c> and <c>Debugger2Client.ListDebuggeesAsync</c>. /// </summary> /// <remarks> /// The default <c>Debugger2Client.ListDebuggees</c> and /// <c>Debugger2Client.ListDebuggeesAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListDebuggeesSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="Debugger2Settings"/> object.</returns> public Debugger2Settings Clone() => new Debugger2Settings(this); } /// <summary> /// Debugger2 client wrapper, for convenient use. /// </summary> public abstract partial class Debugger2Client { /// <summary> /// The default endpoint for the Debugger2 service, which is a host of "clouddebugger.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouddebugger.googleapis.com", 443); /// <summary> /// The default Debugger2 scopes. /// </summary> /// <remarks> /// The default Debugger2 scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// <item><description>"https://www.googleapis.com/auth/cloud_debugger"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud_debugger", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="Debugger2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="Debugger2Settings"/>.</param> /// <returns>The task representing the created <see cref="Debugger2Client"/>.</returns> public static async Task<Debugger2Client> CreateAsync(ServiceEndpoint endpoint = null, Debugger2Settings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="Debugger2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="Debugger2Settings"/>.</param> /// <returns>The created <see cref="Debugger2Client"/>.</returns> public static Debugger2Client Create(ServiceEndpoint endpoint = null, Debugger2Settings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="Debugger2Client"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="Debugger2Settings"/>.</param> /// <returns>The created <see cref="Debugger2Client"/>.</returns> public static Debugger2Client Create(Channel channel, Debugger2Settings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); Debugger2.Debugger2Client grpcClient = new Debugger2.Debugger2Client(channel); return new Debugger2ClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, Debugger2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, Debugger2Settings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, Debugger2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, Debugger2Settings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC Debugger2 client. /// </summary> public virtual Debugger2.Debugger2Client GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Sets the breakpoint to the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee where the breakpoint is to be set. /// </param> /// <param name="breakpoint"> /// Breakpoint specification to set. /// The field `location` of the breakpoint must be set. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<SetBreakpointResponse> SetBreakpointAsync( string debuggeeId, Breakpoint breakpoint, string clientVersion, CallSettings callSettings = null) => SetBreakpointAsync( new SetBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), Breakpoint = GaxPreconditions.CheckNotNull(breakpoint, nameof(breakpoint)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Sets the breakpoint to the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee where the breakpoint is to be set. /// </param> /// <param name="breakpoint"> /// Breakpoint specification to set. /// The field `location` of the breakpoint must be set. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<SetBreakpointResponse> SetBreakpointAsync( string debuggeeId, Breakpoint breakpoint, string clientVersion, CancellationToken cancellationToken) => SetBreakpointAsync( debuggeeId, breakpoint, clientVersion, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Sets the breakpoint to the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee where the breakpoint is to be set. /// </param> /// <param name="breakpoint"> /// Breakpoint specification to set. /// The field `location` of the breakpoint must be set. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual SetBreakpointResponse SetBreakpoint( string debuggeeId, Breakpoint breakpoint, string clientVersion, CallSettings callSettings = null) => SetBreakpoint( new SetBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), Breakpoint = GaxPreconditions.CheckNotNull(breakpoint, nameof(breakpoint)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Sets the breakpoint to the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<SetBreakpointResponse> SetBreakpointAsync( SetBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Sets the breakpoint to the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual SetBreakpointResponse SetBreakpoint( SetBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets breakpoint information. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoint to get. /// </param> /// <param name="breakpointId"> /// ID of the breakpoint to get. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<GetBreakpointResponse> GetBreakpointAsync( string debuggeeId, string breakpointId, string clientVersion, CallSettings callSettings = null) => GetBreakpointAsync( new GetBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Gets breakpoint information. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoint to get. /// </param> /// <param name="breakpointId"> /// ID of the breakpoint to get. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<GetBreakpointResponse> GetBreakpointAsync( string debuggeeId, string breakpointId, string clientVersion, CancellationToken cancellationToken) => GetBreakpointAsync( debuggeeId, breakpointId, clientVersion, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets breakpoint information. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoint to get. /// </param> /// <param name="breakpointId"> /// ID of the breakpoint to get. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual GetBreakpointResponse GetBreakpoint( string debuggeeId, string breakpointId, string clientVersion, CallSettings callSettings = null) => GetBreakpoint( new GetBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Gets breakpoint information. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<GetBreakpointResponse> GetBreakpointAsync( GetBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets breakpoint information. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual GetBreakpointResponse GetBreakpoint( GetBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes the breakpoint from the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoint to delete. /// </param> /// <param name="breakpointId"> /// ID of the breakpoint to delete. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteBreakpointAsync( string debuggeeId, string breakpointId, string clientVersion, CallSettings callSettings = null) => DeleteBreakpointAsync( new DeleteBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Deletes the breakpoint from the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoint to delete. /// </param> /// <param name="breakpointId"> /// ID of the breakpoint to delete. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteBreakpointAsync( string debuggeeId, string breakpointId, string clientVersion, CancellationToken cancellationToken) => DeleteBreakpointAsync( debuggeeId, breakpointId, clientVersion, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the breakpoint from the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoint to delete. /// </param> /// <param name="breakpointId"> /// ID of the breakpoint to delete. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void DeleteBreakpoint( string debuggeeId, string breakpointId, string clientVersion, CallSettings callSettings = null) => DeleteBreakpoint( new DeleteBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), BreakpointId = GaxPreconditions.CheckNotNullOrEmpty(breakpointId, nameof(breakpointId)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Deletes the breakpoint from the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteBreakpointAsync( DeleteBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes the breakpoint from the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void DeleteBreakpoint( DeleteBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists all breakpoints for the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoints to list. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListBreakpointsResponse> ListBreakpointsAsync( string debuggeeId, string clientVersion, CallSettings callSettings = null) => ListBreakpointsAsync( new ListBreakpointsRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Lists all breakpoints for the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoints to list. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListBreakpointsResponse> ListBreakpointsAsync( string debuggeeId, string clientVersion, CancellationToken cancellationToken) => ListBreakpointsAsync( debuggeeId, clientVersion, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Lists all breakpoints for the debuggee. /// </summary> /// <param name="debuggeeId"> /// ID of the debuggee whose breakpoints to list. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ListBreakpointsResponse ListBreakpoints( string debuggeeId, string clientVersion, CallSettings callSettings = null) => ListBreakpoints( new ListBreakpointsRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Lists all breakpoints for the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListBreakpointsResponse> ListBreakpointsAsync( ListBreakpointsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists all breakpoints for the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ListBreakpointsResponse ListBreakpoints( ListBreakpointsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists all the debuggees that the user has access to. /// </summary> /// <param name="project"> /// Project number of a Google Cloud project whose debuggees to list. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListDebuggeesResponse> ListDebuggeesAsync( string project, string clientVersion, CallSettings callSettings = null) => ListDebuggeesAsync( new ListDebuggeesRequest { Project = GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Lists all the debuggees that the user has access to. /// </summary> /// <param name="project"> /// Project number of a Google Cloud project whose debuggees to list. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListDebuggeesResponse> ListDebuggeesAsync( string project, string clientVersion, CancellationToken cancellationToken) => ListDebuggeesAsync( project, clientVersion, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Lists all the debuggees that the user has access to. /// </summary> /// <param name="project"> /// Project number of a Google Cloud project whose debuggees to list. /// </param> /// <param name="clientVersion"> /// The client version making the call. /// Schema: `domain/type/version` (e.g., `google.com/intellij/v1`). /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ListDebuggeesResponse ListDebuggees( string project, string clientVersion, CallSettings callSettings = null) => ListDebuggees( new ListDebuggeesRequest { Project = GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), ClientVersion = GaxPreconditions.CheckNotNullOrEmpty(clientVersion, nameof(clientVersion)), }, callSettings); /// <summary> /// Lists all the debuggees that the user has access to. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListDebuggeesResponse> ListDebuggeesAsync( ListDebuggeesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists all the debuggees that the user has access to. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ListDebuggeesResponse ListDebuggees( ListDebuggeesRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// Debugger2 client wrapper implementation, for convenient use. /// </summary> public sealed partial class Debugger2ClientImpl : Debugger2Client { private readonly ApiCall<SetBreakpointRequest, SetBreakpointResponse> _callSetBreakpoint; private readonly ApiCall<GetBreakpointRequest, GetBreakpointResponse> _callGetBreakpoint; private readonly ApiCall<DeleteBreakpointRequest, Empty> _callDeleteBreakpoint; private readonly ApiCall<ListBreakpointsRequest, ListBreakpointsResponse> _callListBreakpoints; private readonly ApiCall<ListDebuggeesRequest, ListDebuggeesResponse> _callListDebuggees; /// <summary> /// Constructs a client wrapper for the Debugger2 service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="Debugger2Settings"/> used within this client </param> public Debugger2ClientImpl(Debugger2.Debugger2Client grpcClient, Debugger2Settings settings) { GrpcClient = grpcClient; Debugger2Settings effectiveSettings = settings ?? Debugger2Settings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callSetBreakpoint = clientHelper.BuildApiCall<SetBreakpointRequest, SetBreakpointResponse>( GrpcClient.SetBreakpointAsync, GrpcClient.SetBreakpoint, effectiveSettings.SetBreakpointSettings); _callGetBreakpoint = clientHelper.BuildApiCall<GetBreakpointRequest, GetBreakpointResponse>( GrpcClient.GetBreakpointAsync, GrpcClient.GetBreakpoint, effectiveSettings.GetBreakpointSettings); _callDeleteBreakpoint = clientHelper.BuildApiCall<DeleteBreakpointRequest, Empty>( GrpcClient.DeleteBreakpointAsync, GrpcClient.DeleteBreakpoint, effectiveSettings.DeleteBreakpointSettings); _callListBreakpoints = clientHelper.BuildApiCall<ListBreakpointsRequest, ListBreakpointsResponse>( GrpcClient.ListBreakpointsAsync, GrpcClient.ListBreakpoints, effectiveSettings.ListBreakpointsSettings); _callListDebuggees = clientHelper.BuildApiCall<ListDebuggeesRequest, ListDebuggeesResponse>( GrpcClient.ListDebuggeesAsync, GrpcClient.ListDebuggees, effectiveSettings.ListDebuggeesSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(Debugger2.Debugger2Client grpcClient, Debugger2Settings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC Debugger2 client. /// </summary> public override Debugger2.Debugger2Client GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_SetBreakpointRequest(ref SetBreakpointRequest request, ref CallSettings settings); partial void Modify_GetBreakpointRequest(ref GetBreakpointRequest request, ref CallSettings settings); partial void Modify_DeleteBreakpointRequest(ref DeleteBreakpointRequest request, ref CallSettings settings); partial void Modify_ListBreakpointsRequest(ref ListBreakpointsRequest request, ref CallSettings settings); partial void Modify_ListDebuggeesRequest(ref ListDebuggeesRequest request, ref CallSettings settings); /// <summary> /// Sets the breakpoint to the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<SetBreakpointResponse> SetBreakpointAsync( SetBreakpointRequest request, CallSettings callSettings = null) { Modify_SetBreakpointRequest(ref request, ref callSettings); return _callSetBreakpoint.Async(request, callSettings); } /// <summary> /// Sets the breakpoint to the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override SetBreakpointResponse SetBreakpoint( SetBreakpointRequest request, CallSettings callSettings = null) { Modify_SetBreakpointRequest(ref request, ref callSettings); return _callSetBreakpoint.Sync(request, callSettings); } /// <summary> /// Gets breakpoint information. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<GetBreakpointResponse> GetBreakpointAsync( GetBreakpointRequest request, CallSettings callSettings = null) { Modify_GetBreakpointRequest(ref request, ref callSettings); return _callGetBreakpoint.Async(request, callSettings); } /// <summary> /// Gets breakpoint information. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override GetBreakpointResponse GetBreakpoint( GetBreakpointRequest request, CallSettings callSettings = null) { Modify_GetBreakpointRequest(ref request, ref callSettings); return _callGetBreakpoint.Sync(request, callSettings); } /// <summary> /// Deletes the breakpoint from the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task DeleteBreakpointAsync( DeleteBreakpointRequest request, CallSettings callSettings = null) { Modify_DeleteBreakpointRequest(ref request, ref callSettings); return _callDeleteBreakpoint.Async(request, callSettings); } /// <summary> /// Deletes the breakpoint from the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override void DeleteBreakpoint( DeleteBreakpointRequest request, CallSettings callSettings = null) { Modify_DeleteBreakpointRequest(ref request, ref callSettings); _callDeleteBreakpoint.Sync(request, callSettings); } /// <summary> /// Lists all breakpoints for the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<ListBreakpointsResponse> ListBreakpointsAsync( ListBreakpointsRequest request, CallSettings callSettings = null) { Modify_ListBreakpointsRequest(ref request, ref callSettings); return _callListBreakpoints.Async(request, callSettings); } /// <summary> /// Lists all breakpoints for the debuggee. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override ListBreakpointsResponse ListBreakpoints( ListBreakpointsRequest request, CallSettings callSettings = null) { Modify_ListBreakpointsRequest(ref request, ref callSettings); return _callListBreakpoints.Sync(request, callSettings); } /// <summary> /// Lists all the debuggees that the user has access to. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<ListDebuggeesResponse> ListDebuggeesAsync( ListDebuggeesRequest request, CallSettings callSettings = null) { Modify_ListDebuggeesRequest(ref request, ref callSettings); return _callListDebuggees.Async(request, callSettings); } /// <summary> /// Lists all the debuggees that the user has access to. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override ListDebuggeesResponse ListDebuggees( ListDebuggeesRequest request, CallSettings callSettings = null) { Modify_ListDebuggeesRequest(ref request, ref callSettings); return _callListDebuggees.Sync(request, callSettings); } } // Partial classes to enable page-streaming }
using System; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using CollectionStatistics = Lucene.Net.Search.CollectionStatistics; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using LineFileDocs = Lucene.Net.Util.LineFileDocs; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using PerFieldSimilarityWrapper = Lucene.Net.Search.Similarities.PerFieldSimilarityWrapper; using Similarity = Lucene.Net.Search.Similarities.Similarity; using TermStatistics = Lucene.Net.Search.TermStatistics; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; using TFIDFSimilarity = Lucene.Net.Search.Similarities.TFIDFSimilarity; /// <summary> /// Test that norms info is preserved during index life - including /// separate norms, addDocument, addIndexes, forceMerge. /// </summary> [SuppressCodecs("Memory", "Direct", "SimpleText")] //[Slow] // LUCENENET specific - not slow in .NET [TestFixture] public class TestNorms : LuceneTestCase { private readonly string byteTestField = "normsTestByte"; internal class CustomNormEncodingSimilarity : TFIDFSimilarity { private readonly TestNorms outerInstance; public CustomNormEncodingSimilarity(TestNorms outerInstance) { this.outerInstance = outerInstance; } public override long EncodeNormValue(float f) { return (long)f; } public override float DecodeNormValue(long norm) { return norm; } public override float LengthNorm(FieldInvertState state) { return state.Length; } public override float Coord(int overlap, int maxOverlap) { return 0; } public override float QueryNorm(float sumOfSquaredWeights) { return 0; } public override float Tf(float freq) { return 0; } public override float Idf(long docFreq, long numDocs) { return 0; } public override float SloppyFreq(int distance) { return 0; } public override float ScorePayload(int doc, int start, int end, BytesRef payload) { return 0; } } // LUCENE-1260 [Test] public virtual void TestCustomEncoder() { Directory dir = NewDirectory(); MockAnalyzer analyzer = new MockAnalyzer(Random); IndexWriterConfig config = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer); config.SetSimilarity(new CustomNormEncodingSimilarity(this)); RandomIndexWriter writer = new RandomIndexWriter(Random, dir, config); Document doc = new Document(); Field foo = NewTextField("foo", "", Field.Store.NO); Field bar = NewTextField("bar", "", Field.Store.NO); doc.Add(foo); doc.Add(bar); for (int i = 0; i < 100; i++) { bar.SetStringValue("singleton"); writer.AddDocument(doc); } IndexReader reader = writer.GetReader(); writer.Dispose(); NumericDocValues fooNorms = MultiDocValues.GetNormValues(reader, "foo"); for (int i = 0; i < reader.MaxDoc; i++) { Assert.AreEqual(0, fooNorms.Get(i)); } NumericDocValues barNorms = MultiDocValues.GetNormValues(reader, "bar"); for (int i = 0; i < reader.MaxDoc; i++) { Assert.AreEqual(1, barNorms.Get(i)); } reader.Dispose(); dir.Dispose(); } [Test] public virtual void TestMaxByteNorms() { Directory dir = NewFSDirectory(CreateTempDir("TestNorms.testMaxByteNorms")); BuildIndex(dir); AtomicReader open = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir)); NumericDocValues normValues = open.GetNormValues(byteTestField); Assert.IsNotNull(normValues); for (int i = 0; i < open.MaxDoc; i++) { Document document = open.Document(i); int expected = Convert.ToInt32(document.Get(byteTestField)); Assert.AreEqual(expected, normValues.Get(i) & 0xff); } open.Dispose(); dir.Dispose(); } // TODO: create a testNormsNotPresent ourselves by adding/deleting/merging docs public virtual void BuildIndex(Directory dir) { Random random = Random; MockAnalyzer analyzer = new MockAnalyzer(LuceneTestCase.Random); analyzer.MaxTokenLength = TestUtil.NextInt32(LuceneTestCase.Random, 1, IndexWriter.MAX_TERM_LENGTH); IndexWriterConfig config = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer); Similarity provider = new MySimProvider(this); config.SetSimilarity(provider); RandomIndexWriter writer = new RandomIndexWriter(random, dir, config); LineFileDocs docs = new LineFileDocs(random, DefaultCodecSupportsDocValues); int num = AtLeast(100); for (int i = 0; i < num; i++) { Document doc = docs.NextDoc(); int boost = LuceneTestCase.Random.Next(255); Field f = new TextField(byteTestField, "" + boost, Field.Store.YES); f.Boost = boost; doc.Add(f); writer.AddDocument(doc); doc.RemoveField(byteTestField); if (Rarely()) { writer.Commit(); } } writer.Commit(); writer.Dispose(); docs.Dispose(); } public class MySimProvider : PerFieldSimilarityWrapper { private readonly TestNorms outerInstance; public MySimProvider(TestNorms outerInstance) { this.outerInstance = outerInstance; } internal Similarity @delegate = new DefaultSimilarity(); public override float QueryNorm(float sumOfSquaredWeights) { return @delegate.QueryNorm(sumOfSquaredWeights); } public override Similarity Get(string field) { if (outerInstance.byteTestField.Equals(field, StringComparison.Ordinal)) { return new ByteEncodingBoostSimilarity(); } else { return @delegate; } } public override float Coord(int overlap, int maxOverlap) { return @delegate.Coord(overlap, maxOverlap); } } public class ByteEncodingBoostSimilarity : Similarity { public override long ComputeNorm(FieldInvertState state) { int boost = (int)state.Boost; return (sbyte)boost; } public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { throw new NotSupportedException(); } public override SimScorer GetSimScorer(SimWeight weight, AtomicReaderContext context) { throw new NotSupportedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; //////////////////////////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////////////////////////// public class FastTailCallCandidates { //////////////////////////////////////////////////////////////////////////// // Globals //////////////////////////////////////////////////////////////////////////// public static int s_ret_value = 100; //////////////////////////////////////////////////////////////////////////// // Helpers //////////////////////////////////////////////////////////////////////////// /// <summary> /// Check the return value of the test and set s_ret_value if incorrect /// </summary> public static void CheckOutput(int code) { // If there has been a previous failure then do not reset the first // failure this will be the return value. if (s_ret_value != 100) { return; } if (code != 100) { s_ret_value = code; } } /// <summary> /// Run each individual test case /// </summary> /// /// <remarks> /// If you add any new test case scenarios please use reuse code and follow /// the pattern below. Please increment the return value so it /// is easy to determine in the future which scenario is failing. /// </remarks> public static int Tester(int a) { CheckOutput(SimpleTestCase()); CheckOutput(IntegerArgs(10, 11, 12, 13, 14, 15)); CheckOutput(FloatArgs(10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f)); CheckOutput(IntAndFloatArgs(10, 11, 12, 13, 14, 15, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f)); CheckOutput(CallerGithubIssue12468(1, 2, 3, 4, 5, 6, 7, 8, new StructSizeSixteenNotExplicit(1, 2))); CheckOutput(DoNotFastTailCallSimple(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)); CheckOutput(StackBasedCaller(16, new StructSizeTwentyFour(1, 2, 3))); CheckOutput(CallerSimpleHFACase(new HFASize32(1.0, 2.0, 3.0, 4.0), 1.0, 2.0, 3.0, 4.0)); CheckOutput(CallerHFACaseWithStack(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, new HFASize32(1.0, 2.0, 3.0, 4.0))); CheckOutput(CallerHFACaseCalleeOnly(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)); CheckOutput(CallerHFaCaseCalleeStackArgs(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)); CheckOutput(DoubleCountRetBuffCaller(1)); return s_ret_value; } //////////////////////////////////////////////////////////////////////////// // Simple fast tail call case //////////////////////////////////////////////////////////////////////////// /// <summary> /// Simple fast tail call case. /// </summary> /// /// <remarks> /// This is mostly supposed to be a smoke test. It can also be seen as a /// constant /// /// Return 100 is a pass. /// /// </remarks> public static int SimpleTestCase(int retValue = 10) { retValue += 1; if (retValue == 100) { return retValue; } else { return SimpleTestCase(retValue); } } //////////////////////////////////////////////////////////////////////////// // Integer args //////////////////////////////////////////////////////////////////////////// /// <summary> /// Simple fast tail call case that includes integer args /// </summary> /// <remarks> /// /// Return 100 is a pass. /// Return 101 is a failure. /// /// </remarks> public static int IntegerArgs(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int retValue = 10) { retValue += 1; if (retValue == 100) { if (arg1 != 10 || arg2 != 11 || arg3 != 12 || arg4 != 13 || arg5 != 14 || arg6 != 15) { return 101; } return retValue; } else { return IntegerArgs(arg1, arg2, arg3, arg4, arg5, arg6, retValue); } } //////////////////////////////////////////////////////////////////////////// // Float args //////////////////////////////////////////////////////////////////////////// /// <summary> /// Simple fast tail call case that includes floating point args /// </summary> /// <remarks> /// /// Return 100 is a pass. /// Return 102 is a failure. /// /// </remarks> public static int FloatArgs(float arg1, float arg2, float arg3, float arg4, float arg5, float arg6, int retValue = 10) { retValue += 1; if (retValue == 100) { if (arg1 != 10.0f || arg2 != 11.0f || arg3 != 12.0f || arg4 != 13.0f || arg5 != 14.0f || arg6 != 15.0f) { return 102; } return retValue; } else { return FloatArgs(arg1, arg2, arg3, arg4, arg5, arg6, retValue); } } //////////////////////////////////////////////////////////////////////////// // Integer and Float args //////////////////////////////////////////////////////////////////////////// /// <summary> /// Simple fast tail call case that includes integer and floating point args /// </summary> /// <remarks> /// /// Return 100 is a pass. /// Return 103 is a failure. /// /// </remarks> public static int IntAndFloatArgs(int argi1, int argi2, int argi3, int argi4, int argi5, int argi6, float argf1, float argf2, float argf3, float argf4, float argf5, float argf6, int retValue = 10) { retValue += 1; if (retValue == 100) { if (argi1 != 10 || argi2 != 11 || argi3 != 12 || argi4 != 13 || argi5 != 14 || argi6 != 15 || argf1 != 10.0f || argf2 != 11.0f || argf3 != 12.0f || argf4 != 13.0f || argf5 != 14.0f || argf6 != 15.0f) { return 103; } return retValue; } else { return IntAndFloatArgs(argi1, argi2, argi3, argi4, argi5, argi6, argf1, argf2, argf3, argf4, argf5, argf6, retValue); } } /// <summary> /// Decision not to tail call. See DoNotFastTailCallSimple for more info /// </summary> public static int DoNotFastTailCallHelper(int one, int two, int three, int four, int five, int six, int seven, int eight, int nine, int ten, int eleven, int twelve, int thirteen, int fourteen) { if (one == 1) { two = one + two; } if (two == 3) { three = two + three; } if (three == 6) { four = four + three; } if (four != 10) { return 104; } if (five != 5) { return 104; } if (six != 6) { return 104; } if (seven != 7) { return 104; } if (eight != 8) { return 104; } if (nine != 9) { return 104; } if (ten != 10) { return 104; } if (eleven != 11) { return 104; } if (twelve != 12) { return 104; } if (thirteen != 13) { return 104; } if (fourteen != 14) { return 104; } return 100; } /// <summary> /// Decision not to tail call. /// </summary> /// <remarks> /// /// The callee has 6 int register arguments on x64 linux. /// With 8 * 8 (64) bytes stack size /// /// Return 100 is a pass. /// Return 104 is a failure. /// /// </remarks> public static int DoNotFastTailCallSimple(float one, float two, float three, float four, float five, float six, float seven, float eight, int first, int second, int third, int fourth, int fifth, int sixth) { if (one % 2 == 0) { return DoNotFastTailCallHelper((int) two, (int) one, (int) three, (int) four, (int) five, (int) six, (int) seven, (int) eight, first, second, third, fourth, fifth, sixth); // Cannot fast tail call } else { return DoNotFastTailCallHelper((int) one, (int) two, (int) three, (int) four, (int) five, (int) six, (int) seven, (int) eight, first, second, third, fourth, fifth, sixth); // Cannot fast tail call } } //////////////////////////////////////////////////////////////////////////// // HFAs //////////////////////////////////////////////////////////////////////////// public struct HFASize16 { public double a; public double b; public HFASize16(double a, double b) { this.a = a; this.b = b; } } public struct HFASize24 { public double a; public double b; public double c; public HFASize24(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } } public struct HFASize32 { public double a; public double b; public double c; public double d; public HFASize32(double a, double b, double c, double d) { this.a = a; this.b = b; this.c = c; this.d = d; } } /// <summary> /// Possible to fast tail call only on arm64. See CallerSimpleHFACase for /// more information. /// </summary> public static int CalleeSimpleHFACase(double one, double two, double three, double four, double five, double six, double seven, double eight) { int count = 0; for (double i = 0; i < one; ++i) { if (i % 2 == 0) { ++count; } } if (count == 1) { return 100; } else { return 107; } } /// <summary> /// Possible to fast tail call only on arm64 /// </summary> /// <remarks> /// /// This test case is really only interesting on arm64 /// /// Arm64: /// caller has 8 register arguments and no stack space /// callee has 8 register arguments and no stack space /// /// x64 Linux: /// caller has 4 register arguments and 64 bytes of stack space /// callee has 8 register arguments /// /// Arm64 and linux x64 can both fast tail call /// /// Return 100 is a pass. /// Return 107 is a failure. /// /// </remarks> public static int CallerSimpleHFACase(HFASize32 s1, double one, double two, double three, double four) { if (one % 2 == 0) { double a = one * 100; double b = one + 1100; return CalleeSimpleHFACase(one, two, three, four, a, b, one, two); } else { double b = one + 1599; double a = one + 16; return CalleeSimpleHFACase(two, one, three, four, a, b, two, one); } } /// <summary> /// Possible to fast tail call only on arm64. See CallerHFACaseWithStack /// for more information. /// </summary> public static int CalleeHFAStackSpace(double one, double two, double three, double four, double five, double six, double seven, double eight, double nine, double ten) { int count = 0; for (double i = 0; i < one; ++i) { if (i % 2 == 0) { ++count; } } if (count == 1) { return 100; } else { return 108; } } /// <summary> /// Possible to fast tail call only on arm64 /// </summary> /// <remarks> /// /// This test case is really only interesting on arm64 /// /// Arm64: /// caller has 8 register arguments and 32 bytes of stack space /// callee has 8 register arguments and 16 bytes of stack space /// /// x64 linix: /// caller has 8 register arguments and 32 bytes of stack space /// callee has 8 register arguments and 16 bytes of stack space /// /// Arm64 can fast tail call while x64 linux will not. /// Note that this is due to a bug in LowerFastTailCall that assumes /// nCallerArgs <= nCalleeArgs /// /// Return 100 is a pass. /// Return 108 is a failure. /// /// </remarks> public static int CallerHFACaseWithStack(double one, double two, double three, double four, double five, double six, double seven, double eight, HFASize32 s1) { if (one % 2 == 0) { double a = one * 100; double b = one + 1100; return CalleeHFAStackSpace(one, two, three, four, a, b, five, six, seven, eight); } else { double b = one + 1599; double a = one + 16; return CalleeHFAStackSpace(one, two, three, four, a, b, six, five, seven, eight); } } /// <summary> /// Possible to fast tail call only on arm64. See CallerHFACaseCalleeOnly /// for more information. /// </summary> public static int CalleeWithHFA(double one, double two, double three, double four, HFASize32 s1) { int count = 0; for (double i = 0; i < one; ++i) { if (i % 2 == 0) { ++count; } } if (count == 1) { return 100; } else { return 109; } } /// <summary> /// Possible to fast tail call only on arm64 /// </summary> /// <remarks> /// /// This test case is really only interesting on arm64 /// /// Arm64: /// caller has 8 register arguments /// callee has 8 register arguments /// /// x64 Linux: /// caller has 8 register arguments /// callee has 4 register arguments and 32 bytes of stack space /// /// Arm64 can fast tail call while x64 linux cannot /// /// Return 100 is a pass. /// Return 109 is a failure. /// /// </remarks> public static int CallerHFACaseCalleeOnly(double one, double two, double three, double four, double five, double six, double seven, double eight) { if (one % 2 == 0) { double a = one * 100; double b = one + 1100; return CalleeWithHFA(one, a, b, four, new HFASize32(a, b, five, six)); } else { double b = one + 1599; double a = one + 16; return CalleeWithHFA(one, b, a, four, new HFASize32(a, b, five, six)); } } /// <summary> /// Possible to fast tail call on all targets. See /// CallerHFaCaseCalleeStackArgs for info. /// </summary> /// <remarks> public static int CalleeWithStackHFA(double one, double two, double three, double four, double five, double six, double seven, double eight, HFASize16 s1) { int count = 0; for (double i = 0; i < one; ++i) { if (i % 2 == 0) { ++count; } } if (count == 1) { return 100; } else { return 110; } } /// <summary> /// Possible to fast tail call on all targets /// </summary> /// <remarks> /// /// This test case is really only interesting on arm64 and Linux x64 /// because the decision to fast tail call will be reported as false. /// /// On arm64 this is because callee has stack args and has an hfa arg. /// While on x64 Linux this is because the callee has stack args and has /// a special 16 byte struct. /// /// Arm64: /// caller has 8 register arguments and 16 bytes of stack space /// callee has 8 register arguments and 16 bytes of stack space /// /// x64 Linux: /// caller has 8 register arguments and 16 bytes of stack space /// callee has 8 register arguments and 16 bytes of stack space /// /// Arm64 can fast tail call while x64 linux cannot. Note that this is /// due to an implementation limitation. fgCanFastTail call relies on /// fgMorphArgs, but fgMorphArgs relies on fgCanfast tail call. Therefore, /// fgCanFastTailCall will not fast tail call if there is a 16 byte /// struct and stack usage. /// /// Return 100 is a pass. /// Return 110 is a failure. /// /// </remarks> public static int CallerHFaCaseCalleeStackArgs(double one, double two, double three, double four, double five, double six, double seven, double eight, double nine, double ten) { if (one % 2 == 0) { double a = one * 100; double b = one + 1100; return CalleeWithStackHFA(one, a, b, four, five, six, seven, eight, new HFASize16(a, b)); } else { double b = one + 1599; double a = one + 16; return CalleeWithStackHFA(one, a, b, four, five, six, seven, eight, new HFASize16(a, b)); } } //////////////////////////////////////////////////////////////////////////// // Stack Based args. //////////////////////////////////////////////////////////////////////////// public struct StructSizeEightNotExplicit { public long a; public StructSizeEightNotExplicit(long a) { this.a = a; } } public struct StructSizeEightIntNotExplicit { public int a; public int b; public StructSizeEightIntNotExplicit(int a, int b) { this.a = a; this.b = b; } } public struct StructSizeSixteenNotExplicit { public long a; public long b; public StructSizeSixteenNotExplicit(long a, long b) { this.a = a; this.b = b; } } /// <summary> /// Possible to fast tail call. See CallerGithubIssue12468 for more info. /// </summary> public static int CalleeGithubIssue12468(int one, int two, int three, int four, int five, int six, int seven, int eight, StructSizeEightNotExplicit s1, StructSizeEightNotExplicit s2) { int count = 0; for (int i = 0; i < s1.a; ++i) { if (i % 10 == 0) { ++count; } } if (count == 160) { return 100; } else { return 106; } } /// <summary> /// Possible to fast tail call /// </summary> /// <remarks> /// /// Caller has 6 register arguments and 1 stack argument (size 16) /// Callee has 6 register arguments and 2 stack arguments (size 16) /// /// It is possible to fast tail call but will not due to a bug in /// LowerFastTailCall which assumes nCallerArgs <= nCalleeArgs /// /// /// Return 100 is a pass. /// Return 106 is a failure. /// /// </remarks> public static int CallerGithubIssue12468(int one, int two, int three, int four, int five, int six, int seven, int eight, StructSizeSixteenNotExplicit s1) { if (one % 2 == 0) { long a = one * 100; long b = one + 1100; return CalleeGithubIssue12468(two, one, three, four, five, six, seven, eight, new StructSizeEightNotExplicit(a), new StructSizeEightNotExplicit(b)); } else { long b = one + 1599; long a = one + 16; return CalleeGithubIssue12468(one, two, three, four, five, six, seven, eight, new StructSizeEightNotExplicit(b), new StructSizeEightNotExplicit(a)); } } [StructLayout(LayoutKind.Explicit, Size=8, CharSet=CharSet.Ansi)] public struct StructSizeThirtyTwo { [FieldOffset(0)] public int a; [FieldOffset(8)] public int b; [FieldOffset(16)] public int c; [FieldOffset(24)] public int d; public StructSizeThirtyTwo(int a, int b, int c, int d) { this.a = a; this.b = b; this.c = c; this.d = d; } }; [StructLayout(LayoutKind.Explicit, Size=8, CharSet=CharSet.Ansi)] public struct StructSizeTwentyFour { [FieldOffset(0)] public int a; [FieldOffset(8)] public int b; [FieldOffset(16)] public int c; public StructSizeTwentyFour(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } /// <summary> /// Decision to fast tail call. See StackBasedCaller for more /// information. /// </summary> public static int StackBasedCallee(int a, int b, StructSizeThirtyTwo sstt) { int count = 0; for (int i = 0; i < sstt.a; ++i) { if (i % 10 == 0) { ++count; } } if (count == 160) { return 100; } else { return 105; } } /// <summary> /// Decision to fast tail call /// </summary> /// <remarks> /// /// On x64 linux this will not fast tail call. /// /// The caller has one stack argument of size 24 /// The callee has one stack argument of size 32 /// /// On Arm64 this will fast tail call /// /// Both caller and callee have two register args. /// /// Return 100 is a pass. /// Return 105 is a failure. /// /// </remarks> public static int StackBasedCaller(int i, StructSizeTwentyFour sstf) { if (i % 2 == 0) { int a = i * 100; int b = i + 1100; return StackBasedCallee(a, b, new StructSizeThirtyTwo(a, b, b, a)); } else { int b = i + 829; int a = i + 16; return StackBasedCallee(b, a, new StructSizeThirtyTwo(b, a, a, b)); } } /// <summary> /// Decision to fast tail call. See DoubleCountRetBuffCaller for more /// information. /// </summary> public static StructSizeThirtyTwo DoubleCountRetBuffCallee(StructSizeEightIntNotExplicit sstf, StructSizeEightIntNotExplicit sstf2, StructSizeEightIntNotExplicit sstf3, StructSizeEightIntNotExplicit sstf4, StructSizeEightIntNotExplicit sstf5) { int a = sstf.a; int b = sstf.b; StructSizeThirtyTwo retVal = new StructSizeThirtyTwo(b, a, a, b); int count = 0; for (int i = 0; i < b; ++i) { if (i % 2 == 0) { ++count; } } return retVal; } /// <summary> /// Decision to fast tail call. See DoubleCountRetBuffCaller for more /// information. /// </summary> public static StructSizeThirtyTwo DoubleCountRetBuffCallerWrapper(int a, int b) { if (a % 2 == 0) { StructSizeEightIntNotExplicit eightBytes = new StructSizeEightIntNotExplicit(a, a); a = 1; b = b + 2; return DoubleCountRetBuffCallee(eightBytes, eightBytes, eightBytes, eightBytes, eightBytes); } else { StructSizeEightIntNotExplicit eightBytes = new StructSizeEightIntNotExplicit(b, b); a = 4; b = b + 1; return DoubleCountRetBuffCallee(eightBytes, eightBytes, eightBytes, eightBytes, eightBytes); } } /// <summary> /// Decision to fast tail call /// </summary> /// <remarks> /// /// On x64 linux this will fast tail call. /// /// The caller uses 3 integer registers (2 args, one ret buf) /// The callee uses 6 integer registers (5 args, one ret buf) /// /// Return 100 is a pass. /// Return 112 is a failure. /// /// </remarks> public static int DoubleCountRetBuffCaller(int i) { if (i % 2 == 0) { StructSizeThirtyTwo retVal = DoubleCountRetBuffCallerWrapper(4, 2); if (retVal.b == 4.0) { return 100; } else { return 112; } } else { StructSizeThirtyTwo retVal = DoubleCountRetBuffCallerWrapper(3, 1); if (retVal.b == 1.0) { return 100; } else { return 112; } } } //////////////////////////////////////////////////////////////////////////// // Main //////////////////////////////////////////////////////////////////////////// public static int Main() { return Tester(1); } }
using System; using System.Collections; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace AutoCompleteTextBox.Editors { [TemplatePart(Name = PartEditor, Type = typeof(TextBox))] [TemplatePart(Name = PartPopup, Type = typeof(Popup))] [TemplatePart(Name = PartSelector, Type = typeof(Selector))] public class AutoCompleteTextBox : Control { #region "Fields" public const string PartEditor = "PART_Editor"; public const string PartPopup = "PART_Popup"; public const string PartSelector = "PART_Selector"; public static readonly DependencyProperty DelayProperty = DependencyProperty.Register("Delay", typeof(int), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(200)); public static readonly DependencyProperty DisplayMemberProperty = DependencyProperty.Register("DisplayMember", typeof(string), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty IconPlacementProperty = DependencyProperty.Register("IconPlacement", typeof(IconPlacement), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(IconPlacement.Left)); public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(object), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty IconVisibilityProperty = DependencyProperty.Register("IconVisibility", typeof(Visibility), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(Visibility.Visible)); public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register("IsDropDownOpen", typeof(bool), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty IsLoadingProperty = DependencyProperty.Register("IsLoading", typeof(bool), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty ItemTemplateSelectorProperty = DependencyProperty.Register("ItemTemplateSelector", typeof(DataTemplateSelector), typeof(AutoCompleteTextBox)); public static readonly DependencyProperty LoadingContentProperty = DependencyProperty.Register("LoadingContent", typeof(object), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty ProviderProperty = DependencyProperty.Register("Provider", typeof(ISuggestionProvider), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(null, OnSelectedItemChanged)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(string.Empty, propertyChangedCallback:null,coerceValueCallback:null, isAnimationProhibited:false, defaultUpdateSourceTrigger: UpdateSourceTrigger.LostFocus, flags: FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public static readonly DependencyProperty FilterProperty = DependencyProperty.Register("Filter", typeof(string), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.Register("MaxLength", typeof(int), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(0)); public static readonly DependencyProperty CharacterCasingProperty = DependencyProperty.Register("CharacterCasing", typeof(CharacterCasing), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(CharacterCasing.Normal)); public static readonly DependencyProperty MaxPopUpHeightProperty = DependencyProperty.Register("MaxPopUpHeight", typeof(int), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(600)); public static readonly DependencyProperty MaxPopUpWidthProperty = DependencyProperty.Register("MaxPopUpWidth", typeof(int), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(2000)); public static readonly DependencyProperty WatermarkProperty = DependencyProperty.Register("Watermark", typeof(string), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty SuggestionBackgroundProperty = DependencyProperty.Register("SuggestionBackground", typeof(Brush), typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(Brushes.White)); private bool _isUpdatingText; private bool _selectionCancelled; private SuggestionsAdapter _suggestionsAdapter; #endregion #region "Constructors" static AutoCompleteTextBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoCompleteTextBox), new FrameworkPropertyMetadata(typeof(AutoCompleteTextBox))); } #endregion #region "Properties" public int MaxPopupHeight { get => (int)GetValue(MaxPopUpHeightProperty); set => SetValue(MaxPopUpHeightProperty, value); } public int MaxPopupWidth { get => (int)GetValue(MaxPopUpWidthProperty); set => SetValue(MaxPopUpWidthProperty, value); } public BindingEvaluator BindingEvaluator { get; set; } public CharacterCasing CharacterCasing { get => (CharacterCasing)GetValue(CharacterCasingProperty); set => SetValue(CharacterCasingProperty, value); } public int MaxLength { get => (int)GetValue(MaxLengthProperty); set => SetValue(MaxLengthProperty, value); } public int Delay { get => (int)GetValue(DelayProperty); set => SetValue(DelayProperty, value); } public string DisplayMember { get => (string)GetValue(DisplayMemberProperty); set => SetValue(DisplayMemberProperty, value); } public TextBox Editor { get; set; } public DispatcherTimer FetchTimer { get; set; } public string Filter { get => (string)GetValue(FilterProperty); set => SetValue(FilterProperty, value); } public object Icon { get => GetValue(IconProperty); set => SetValue(IconProperty, value); } public IconPlacement IconPlacement { get => (IconPlacement)GetValue(IconPlacementProperty); set => SetValue(IconPlacementProperty, value); } public Visibility IconVisibility { get => (Visibility)GetValue(IconVisibilityProperty); set => SetValue(IconVisibilityProperty, value); } public bool IsDropDownOpen { get => (bool)GetValue(IsDropDownOpenProperty); set => SetValue(IsDropDownOpenProperty, value); } public bool IsLoading { get => (bool)GetValue(IsLoadingProperty); set => SetValue(IsLoadingProperty, value); } public bool IsReadOnly { get => (bool)GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } public Selector ItemsSelector { get; set; } public DataTemplate ItemTemplate { get => (DataTemplate)GetValue(ItemTemplateProperty); set => SetValue(ItemTemplateProperty, value); } public DataTemplateSelector ItemTemplateSelector { get => ((DataTemplateSelector)(GetValue(ItemTemplateSelectorProperty))); set => SetValue(ItemTemplateSelectorProperty, value); } public object LoadingContent { get => GetValue(LoadingContentProperty); set => SetValue(LoadingContentProperty, value); } public Popup Popup { get; set; } public ISuggestionProvider Provider { get => (ISuggestionProvider)GetValue(ProviderProperty); set => SetValue(ProviderProperty, value); } public object SelectedItem { get => GetValue(SelectedItemProperty); set => SetValue(SelectedItemProperty, value); } public SelectionAdapter SelectionAdapter { get; set; } public string Text { get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value); } public string Watermark { get => (string)GetValue(WatermarkProperty); set => SetValue(WatermarkProperty, value); } public Brush SuggestionBackground { get => (Brush)GetValue(SuggestionBackgroundProperty); set => SetValue(SuggestionBackgroundProperty, value); } #endregion #region "Methods" public static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AutoCompleteTextBox act = null; act = d as AutoCompleteTextBox; if (act != null) { if (act.Editor != null & !act._isUpdatingText) { act._isUpdatingText = true; act.Editor.Text = act.BindingEvaluator.Evaluate(e.NewValue); act._isUpdatingText = false; } } } private void ScrollToSelectedItem() { if (ItemsSelector is ListBox listBox && listBox.SelectedItem != null) listBox.ScrollIntoView(listBox.SelectedItem); } public new BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding){ var res = base.SetBinding(dp, binding); CheckForParentTextBindingChange(); return res; } public new BindingExpressionBase SetBinding(DependencyProperty dp, String path) { var res = base.SetBinding(dp, path); CheckForParentTextBindingChange(); return res; } public new void ClearValue(DependencyPropertyKey key) { base.ClearValue(key); CheckForParentTextBindingChange(); } public new void ClearValue(DependencyProperty dp) { base.ClearValue(dp); CheckForParentTextBindingChange(); } private void CheckForParentTextBindingChange(bool force=false) { var CurrentBindingMode = BindingOperations.GetBinding(this, TextProperty)?.UpdateSourceTrigger ?? UpdateSourceTrigger.Default; if (CurrentBindingMode != UpdateSourceTrigger.PropertyChanged)//preventing going any less frequent than property changed CurrentBindingMode = UpdateSourceTrigger.Default; if (CurrentBindingMode == CurrentTextboxTextBindingUpdateMode && force == false) return; var binding = new Binding { Mode = BindingMode.TwoWay, UpdateSourceTrigger = CurrentBindingMode, Path = new PropertyPath(nameof(Text)), RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent), }; CurrentTextboxTextBindingUpdateMode = CurrentBindingMode; Editor?.SetBinding(TextBox.TextProperty, binding); } private UpdateSourceTrigger CurrentTextboxTextBindingUpdateMode; public override void OnApplyTemplate() { base.OnApplyTemplate(); Editor = Template.FindName(PartEditor, this) as TextBox; Popup = Template.FindName(PartPopup, this) as Popup; ItemsSelector = Template.FindName(PartSelector, this) as Selector; BindingEvaluator = new BindingEvaluator(new Binding(DisplayMember)); if (Editor != null) { Editor.TextChanged += OnEditorTextChanged; Editor.PreviewKeyDown += OnEditorKeyDown; Editor.LostFocus += OnEditorLostFocus; CheckForParentTextBindingChange(true); if (SelectedItem != null) { _isUpdatingText = true; Editor.Text = BindingEvaluator.Evaluate(SelectedItem); _isUpdatingText = false; } } GotFocus += AutoCompleteTextBox_GotFocus; if (Popup != null) { Popup.StaysOpen = false; Popup.Opened += OnPopupOpened; Popup.Closed += OnPopupClosed; } if (ItemsSelector != null) { SelectionAdapter = new SelectionAdapter(ItemsSelector); SelectionAdapter.Commit += OnSelectionAdapterCommit; SelectionAdapter.Cancel += OnSelectionAdapterCancel; SelectionAdapter.SelectionChanged += OnSelectionAdapterSelectionChanged; ItemsSelector.PreviewMouseDown += ItemsSelector_PreviewMouseDown; } } private void ItemsSelector_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if ((e.OriginalSource as FrameworkElement)?.DataContext == null) return; if (!ItemsSelector.Items.Contains(((FrameworkElement)e.OriginalSource)?.DataContext)) return; ItemsSelector.SelectedItem = ((FrameworkElement)e.OriginalSource)?.DataContext; OnSelectionAdapterCommit(SelectionAdapter.EventCause.MouseDown); e.Handled = true; } private void AutoCompleteTextBox_GotFocus(object sender, RoutedEventArgs e) { Editor?.Focus(); } private string GetDisplayText(object dataItem) { if (BindingEvaluator == null) { BindingEvaluator = new BindingEvaluator(new Binding(DisplayMember)); } if (dataItem == null) { return string.Empty; } if (string.IsNullOrEmpty(DisplayMember)) { return dataItem.ToString(); } return BindingEvaluator.Evaluate(dataItem); } private void OnEditorKeyDown(object sender, KeyEventArgs e) { if (SelectionAdapter != null) { if (IsDropDownOpen) SelectionAdapter.HandleKeyDown(e); else IsDropDownOpen = e.Key == Key.Down || e.Key == Key.Up; } } private void OnEditorLostFocus(object sender, RoutedEventArgs e) { if (!IsKeyboardFocusWithin) { IsDropDownOpen = false; } } private void OnEditorTextChanged(object sender, TextChangedEventArgs e) { Text = Editor.Text; if (_isUpdatingText) return; if (FetchTimer == null) { FetchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(Delay) }; FetchTimer.Tick += OnFetchTimerTick; } FetchTimer.IsEnabled = false; FetchTimer.Stop(); SetSelectedItem(null); if (Editor.Text.Length > 0) { FetchTimer.IsEnabled = true; FetchTimer.Start(); } else { IsDropDownOpen = false; } } private void OnFetchTimerTick(object sender, EventArgs e) { FetchTimer.IsEnabled = false; FetchTimer.Stop(); if (Provider != null && ItemsSelector != null) { Filter = Editor.Text; if (_suggestionsAdapter == null) { _suggestionsAdapter = new SuggestionsAdapter(this); } _suggestionsAdapter.GetSuggestions(Filter); } } private void OnPopupClosed(object sender, EventArgs e) { if (!_selectionCancelled) { OnSelectionAdapterCommit(SelectionAdapter.EventCause.PopupClosed); } } private void OnPopupOpened(object sender, EventArgs e) { _selectionCancelled = false; ItemsSelector.SelectedItem = SelectedItem; } private void OnSelectionAdapterCancel(SelectionAdapter.EventCause cause) { if (PreSelectionEventSomeoneHandled(cause, true)) return; _isUpdatingText = true; Editor.Text = SelectedItem == null ? Filter : GetDisplayText(SelectedItem); Editor.SelectionStart = Editor.Text.Length; Editor.SelectionLength = 0; _isUpdatingText = false; IsDropDownOpen = false; _selectionCancelled = true; } public event EventHandler<SelectionAdapter.PreSelectionAdapterFinishArgs> PreSelectionAdapterFinish; private bool PreSelectionEventSomeoneHandled(SelectionAdapter.EventCause cause, bool is_cancel) { if (PreSelectionAdapterFinish == null) return false; var args = new SelectionAdapter.PreSelectionAdapterFinishArgs { cause = cause, is_cancel = is_cancel }; PreSelectionAdapterFinish?.Invoke(this, args); return args.handled; } private void OnSelectionAdapterCommit(SelectionAdapter.EventCause cause) { if (PreSelectionEventSomeoneHandled(cause, false)) return; if (ItemsSelector.SelectedItem != null) { SelectedItem = ItemsSelector.SelectedItem; _isUpdatingText = true; Editor.Text = GetDisplayText(ItemsSelector.SelectedItem); SetSelectedItem(ItemsSelector.SelectedItem); _isUpdatingText = false; IsDropDownOpen = false; } } private void OnSelectionAdapterSelectionChanged() { _isUpdatingText = true; Editor.Text = ItemsSelector.SelectedItem == null ? Filter : GetDisplayText(ItemsSelector.SelectedItem); Editor.SelectionStart = Editor.Text.Length; Editor.SelectionLength = 0; ScrollToSelectedItem(); _isUpdatingText = false; } private void SetSelectedItem(object item) { _isUpdatingText = true; SelectedItem = item; _isUpdatingText = false; } #endregion #region "Nested Types" private class SuggestionsAdapter { #region "Fields" private readonly AutoCompleteTextBox _actb; private string _filter; #endregion #region "Constructors" public SuggestionsAdapter(AutoCompleteTextBox actb) { _actb = actb; } #endregion #region "Methods" public void GetSuggestions(string searchText) { _filter = searchText; _actb.IsLoading = true; // Do not open drop down if control is not focused if (_actb.IsKeyboardFocusWithin) _actb.IsDropDownOpen = true; _actb.ItemsSelector.ItemsSource = null; ParameterizedThreadStart thInfo = GetSuggestionsAsync; Thread th = new Thread(thInfo); th.Start(new object[] { searchText, _actb.Provider }); } private void DisplaySuggestions(IEnumerable suggestions, string filter) { if (_filter != filter) { return; } _actb.IsLoading = false; _actb.ItemsSelector.ItemsSource = suggestions; // Close drop down if there are no items if (_actb.IsDropDownOpen) { _actb.IsDropDownOpen = _actb.ItemsSelector.HasItems; } } private void GetSuggestionsAsync(object param) { if (param is object[] args) { string searchText = Convert.ToString(args[0]); if (args[1] is ISuggestionProvider provider) { IEnumerable list = provider.GetSuggestions(searchText); _actb.Dispatcher.BeginInvoke(new Action<IEnumerable, string>(DisplaySuggestions), DispatcherPriority.Background, list, searchText); } } } #endregion } #endregion } }
// // Copyright (c) 2004-2016 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. // #if !SILVERLIGHT namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using System.Linq; using NLog.Targets; using Xunit; using Xunit.Extensions; public class ColoredConsoleTargetTests : NLogTestBase { [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextTest(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " At The Bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextIgnoreCase(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " ", "At", " The Bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextWholeWords(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", WholeWords = true, CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The cat sat ", "at", " the bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingRegex(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The ", "cat", " ", "sat", " at the bar." }); } /// <summary> /// With or wihout CompileRegex, CompileRegex is never null, even if not used when CompileRegex=false. (needed for backwardscomp) /// </summary> /// <param name="compileRegex"></param> [Theory] [InlineData(true)] [InlineData(false)] public void CompiledRegexPropertyNotNull(bool compileRegex) { var rule = new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }; Assert.NotNull(rule.CompiledRegex); } [Theory] [InlineData(true)] [InlineData(false)] public void DonRemoveIfRegexIsEmpty(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = null, IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } #if !NET3_5 && !MONO [Fact] public void ColoredConsoleRaceCondtionIgnoreTest() { var configXml = @" <nlog throwExceptions='true'> <targets> <target name='console' type='coloredConsole' layout='${message}' /> <target name='console2' type='coloredConsole' layout='${message}' /> <target name='console3' type='coloredConsole' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='Trace' writeTo='console,console2,console3' /> </rules> </nlog>"; ConsoleTargetTests.ConsoleRaceCondtionIgnoreInnerTest(configXml); } #endif private static void AssertOutput(Target target, string message, string[] expectedParts) { var consoleOutWriter = new PartsWriter(); TextWriter oldConsoleOutWriter = Console.Out; Console.SetOut(consoleOutWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger", message).WithContinuation(exceptions.Add)); target.Close(); Assert.Equal(1, exceptions.Count); Assert.True(exceptions.TrueForAll(e => e == null)); } finally { Console.SetOut(oldConsoleOutWriter); } var expected = Enumerable.Repeat("Logger " + expectedParts[0], 1).Concat(expectedParts.Skip(1)); Assert.Equal(expected, consoleOutWriter.Values); } private class PartsWriter : StringWriter { public PartsWriter() { Values = new List<string>(); } public List<string> Values { get; private set; } public override void Write(string value) { Values.Add(value); } } } } #endif
using System; using System.Web; using EPiServerAlloySite.Models.Pages; using EPiServer.Find.UnifiedSearch; using EPiServerAlloySite.Models.ViewModels; using EPiServer.ServiceLocation; using EPiServer.Find.Framework.Statistics; using EPiServer; namespace EPiServerAlloySite.Models.ViewModels { public class FindSearchContentModel : PageViewModel<FindSearchPage> { public FindSearchContentModel(FindSearchPage currentPage) : base(currentPage) { } /// <summary> /// Search hits /// </summary> public UnifiedSearchResults Hits { get; set; } /// <summary> /// Public proxy path mainly used for constructing url's in javascript /// </summary> public string PublicProxyPath { get; set; } /// <summary> /// Flag to indicate if both Find serviceUrl and defaultIndex are configured /// </summary> public bool IsConfigured { get; set; } /// <summary> /// Constructs a url for a section group /// </summary> /// <param name="groupName">Name of group</param> /// <returns>Url</returns> public string GetSectionGroupUrl(string groupName) { return UriSupport.AddQueryString(RemoveQueryStringByKey(HttpContext.Current.Request.Url.AbsoluteUri,"p"), "t", HttpContext.Current.Server.UrlEncode(groupName)); } /// <summary> /// Removes specified query string from url /// </summary> /// <param name="url">Url from which to remove query string</param> /// <param name="key">Key of query string to remove</param> /// <returns>New url that excludes the specified query string</returns> private string RemoveQueryStringByKey(string url, string key) { var uri = new Uri(url); var newQueryString = HttpUtility.ParseQueryString(uri.Query); newQueryString.Remove(key); string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path); return newQueryString.Count > 0 ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString) : pagePathWithoutQueryString; } /// <summary> /// Number of matching hits /// </summary> public int NumberOfHits { get { return Hits.TotalMatching; } } /// <summary> /// Current active section filter /// </summary> public string SectionFilter { get { return HttpContext.Current.Request.QueryString["t"] ?? string.Empty; } } /// <summary> /// Retrieve the paging page from the query string parameter "p". /// If no parameter exists, default to the first page. /// </summary> public int PagingPage { get { int pagingPage; if (!int.TryParse(HttpContext.Current.Request.QueryString["p"], out pagingPage)) { pagingPage = 1; } return pagingPage; } } /// <summary> /// Retrieve the paging section from the query string parameter "ps". /// If no parameter exists, default to the first paging section. /// </summary> public int PagingSection { get { return 1 + (PagingPage - 1) / PagingSectionSize; } } /// <summary> /// Calculate the number of pages required to list results /// </summary> public int TotalPagingPages { get { if (CurrentPage.PageSize > 0) { return 1 + (Hits.TotalMatching - 1)/CurrentPage.PageSize; } return 0; } } public int PagingSectionSize { get { return 10; } } /// <summary> /// Calculate the number of paging sections required to list page links /// </summary> public int TotalPagingSections { get { return 1 + (TotalPagingPages - 1) / PagingSectionSize; } } /// <summary> /// Number of first page in current paging section /// </summary> public int PagingSectionFirstPage { get { return 1 + (PagingSection - 1) * PagingSectionSize; } } /// <summary> /// Number of last page in current paging section /// </summary> public int PagingSectionLastPage { get { return Math.Min((PagingSection * PagingSectionSize), TotalPagingPages); } } /// <summary> /// Create URL for a specified paging page. /// </summary> /// <param name="pageNumber">Number of page for which to get a url</param> /// <returns>Url for specified page</returns> public string GetPagingUrl(int pageNumber) { return UriSupport.AddQueryString(HttpContext.Current.Request.RawUrl, "p", pageNumber.ToString()); } /// <summary> /// Create URL for the next paging section. /// </summary> /// <returns>Url for next paging section</returns> public string GetNextPagingSectionUrl() { return UriSupport.AddQueryString(HttpContext.Current.Request.RawUrl, "p", ((PagingSection * PagingSectionSize) + 1).ToString()); } /// <summary> /// Create URL for the previous paging section. /// </summary> /// <returns>Url for previous paging section</returns> public string GetPreviousPagingSectionUrl() { return UriSupport.AddQueryString(HttpContext.Current.Request.RawUrl, "p", ((PagingSection - 1) * PagingSectionSize).ToString()); } /// <summary> /// User query to search /// </summary> public string Query { get { return (HttpContext.Current.Request.QueryString["q"] ?? string.Empty).Trim(); } } /// <summary> /// Search tags like language and site /// </summary> public string Tags { get { return string.Join(",", ServiceLocator.Current.GetInstance<IStatisticTagsHelper>().GetTags()); } } /// <summary> /// Length of excerpt /// </summary> public int ExcerptLength { get { return CurrentPage.ExcerptLength; } } /// <summary> /// Height of hit images /// </summary> public int HitImagesHeight { get { return CurrentPage.HitImagesHeight; } } /// <summary> /// Flag retrieved from editor settings to determine if it should /// use AND as the operator for multiple search terms /// </summary> public bool UseAndForMultipleSearchTerms { get { return CurrentPage.UseAndForMultipleSearchTerms; } } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonView.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // // </summary> // <author>[email protected]</author> // ---------------------------------------------------------------------------- using System; using UnityEngine; using System.Reflection; using System.Collections.Generic; using ExitGames.Client.Photon; #if UNITY_EDITOR using UnityEditor; #endif public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange } public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All } public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All } /// <summary> /// Options to define how Ownership Transfer is handled per PhotonView. /// </summary> /// <remarks> /// This setting affects how RequestOwnership and TransferOwnership work at runtime. /// </remarks> public enum OwnershipOption { /// <summary> /// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client. /// </summary> Fixed, /// <summary> /// Ownership can be taken away from the current owner who can't object. /// </summary> Takeover, /// <summary> /// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership. /// </summary> /// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks> Request } /// <summary> /// PUN's NetworkView replacement class for networking. Use it like a NetworkView. /// </summary> /// \ingroup publicApi [AddComponentMenu("Photon Networking/Photon View &v")] public class PhotonView : Photon.MonoBehaviour { #if UNITY_EDITOR [ContextMenu("Open PUN Wizard")] void OpenPunWizard() { EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking"); } #endif public int ownerId; public int group = 0; protected internal bool mixedModeIsReliable = false; /// <summary> /// Flag to check if ownership of this photonView was set during the lifecycle. Used for checking when joining late if event with mismatched owner and sender needs addressing. /// </summary> /// <value><c>true</c> if owner ship was transfered; otherwise, <c>false</c>.</value> public bool OwnerShipWasTransfered; // NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though! // NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore) public int prefix { get { if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null) { this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix; } return this.prefixBackup; } set { this.prefixBackup = value; } } // this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene public int prefixBackup = -1; /// <summary> /// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab) /// </summary> public object[] instantiationData { get { if (!this.didAwake) { // even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId); } return this.instantiationDataField; } set { this.instantiationDataField = value; } } internal object[] instantiationDataField; /// <summary> /// For internal use only, don't use /// </summary> protected internal object[] lastOnSerializeDataSent = null; /// <summary> /// For internal use only, don't use /// </summary> protected internal object[] lastOnSerializeDataReceived = null; public ViewSynchronization synchronization; public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation; public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All; /// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary> /// <remarks> /// Note that you can't edit this value at runtime. /// The options are described in enum OwnershipOption. /// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// </remarks> public OwnershipOption ownershipTransfer = OwnershipOption.Fixed; public List<Component> ObservedComponents; Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>(3); #if UNITY_EDITOR // Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor #pragma warning disable 0414 [SerializeField] bool ObservedComponentsFoldoutOpen = true; #pragma warning restore 0414 #endif [SerializeField] private int viewIdField = 0; /// <summary> /// The ID of the PhotonView. Identifies it in a networked game (per room). /// </summary> /// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks> public int viewID { get { return this.viewIdField; } set { // if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup bool viewMustRegister = this.didAwake && this.viewIdField == 0; // TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea // check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object) // PhotonNetwork.networkingPeer.RemovePhotonView(this, true); this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS; this.viewIdField = value; if (viewMustRegister) { PhotonNetwork.networkingPeer.RegisterPhotonView(this); } //Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId); } } public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID) /// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary> /// <remarks> /// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their /// creator leaves the game and the current Master Client can control them (whoever that is). /// The ownerId is 0 (player IDs are 1 and up). /// </remarks> public bool isSceneView { get { return this.CreatorActorNr == 0; } } /// <summary> /// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// /// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request /// ownership by calling the PhotonView's RequestOwnership method. /// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// </remarks> public PhotonPlayer owner { get { return PhotonPlayer.Find(this.ownerId); } } public int OwnerActorNr { get { return this.ownerId; } } public bool isOwnerActive { get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); } } public int CreatorActorNr { get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; } } /// <summary> /// True if the PhotonView is "mine" and can be controlled by this client. /// </summary> /// <remarks> /// PUN has an ownership concept that defines who can control and destroy each PhotonView. /// True in case the owner matches the local PhotonPlayer. /// True if this is a scene photonview on the Master client. /// </remarks> public bool isMine { get { return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient); } } /// <summary> /// The current master ID so that we can compare when we receive OnMasterClientSwitched() callback /// It's public so that we can check it during ownerId assignments in networkPeer script /// TODO: Maybe we can have the networkPeer always aware of the previous MasterClient? /// </summary> public int currentMasterID = -1; protected internal bool didAwake; [SerializeField] protected internal bool isRuntimeInstantiated; protected internal bool removedFromLocalViewList; internal MonoBehaviour[] RpcMonoBehaviours; private MethodInfo OnSerializeMethodInfo; private bool failedToFindOnSerialize; /// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary> protected internal void Awake() { if (this.viewID != 0) { // registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case PhotonNetwork.networkingPeer.RegisterPhotonView(this); this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId); } this.didAwake = true; } /// <summary> /// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView. /// </summary> /// <remarks> /// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that. /// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request. /// /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void RequestOwnership() { PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId); } /// <summary> /// Transfers the ownership of this PhotonView (and GameObject) to another player. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void TransferOwnership(PhotonPlayer newOwner) { this.TransferOwnership(newOwner.ID); } /// <summary> /// Transfers the ownership of this PhotonView (and GameObject) to another player. /// </summary> /// <remarks> /// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject. /// </remarks> public void TransferOwnership(int newOwnerId) { PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId); this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client. } /// <summary> ///Check ownerId assignment for sceneObjects to keep being owned by the MasterClient. /// </summary> /// <param name="newMasterClient">New master client.</param> public void OnMasterClientSwitched(PhotonPlayer newMasterClient) { if (this.CreatorActorNr == 0 && !this.OwnerShipWasTransfered && (this.currentMasterID== -1 || this.ownerId==this.currentMasterID)) { this.ownerId = newMasterClient.ID; } this.currentMasterID = newMasterClient.ID; } protected internal void OnDestroy() { if (!this.removedFromLocalViewList) { bool wasInList = PhotonNetwork.networkingPeer.LocalCleanPhotonView(this); bool loading = false; #if !UNITY_5 || UNITY_5_0 || UNITY_5_1 loading = Application.isLoadingLevel; #endif if (wasInList && !loading && this.instantiationId > 0 && !PhotonHandler.AppQuits && PhotonNetwork.logLevel >= PhotonLogLevel.Informational) { Debug.Log("PUN-instantiated '" + this.gameObject.name + "' got destroyed by engine. This is OK when loading levels. Otherwise use: PhotonNetwork.Destroy()."); } } } public void SerializeView(PhotonStream stream, PhotonMessageInfo info) { if (this.ObservedComponents != null && this.ObservedComponents.Count > 0) { for (int i = 0; i < this.ObservedComponents.Count; ++i) { SerializeComponent(this.ObservedComponents[i], stream, info); } } } public void DeserializeView(PhotonStream stream, PhotonMessageInfo info) { if (this.ObservedComponents != null && this.ObservedComponents.Count > 0) { for (int i = 0; i < this.ObservedComponents.Count; ++i) { DeserializeComponent(this.ObservedComponents[i], stream, info); } } } protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info) { if (component == null) { return; } // Use incoming data according to observed type if (component is MonoBehaviour) { ExecuteComponentOnSerialize(component, stream, info); } else if (component is Transform) { Transform trans = (Transform) component; switch (this.onSerializeTransformOption) { case OnSerializeTransform.All: trans.localPosition = (Vector3) stream.ReceiveNext(); trans.localRotation = (Quaternion) stream.ReceiveNext(); trans.localScale = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyPosition: trans.localPosition = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyRotation: trans.localRotation = (Quaternion) stream.ReceiveNext(); break; case OnSerializeTransform.OnlyScale: trans.localScale = (Vector3) stream.ReceiveNext(); break; case OnSerializeTransform.PositionAndRotation: trans.localPosition = (Vector3) stream.ReceiveNext(); trans.localRotation = (Quaternion) stream.ReceiveNext(); break; } } else if (component is Rigidbody) { Rigidbody rigidB = (Rigidbody) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: rigidB.velocity = (Vector3) stream.ReceiveNext(); rigidB.angularVelocity = (Vector3) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyAngularVelocity: rigidB.angularVelocity = (Vector3) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyVelocity: rigidB.velocity = (Vector3) stream.ReceiveNext(); break; } } else if (component is Rigidbody2D) { Rigidbody2D rigidB = (Rigidbody2D) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: rigidB.velocity = (Vector2) stream.ReceiveNext(); rigidB.angularVelocity = (float) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyAngularVelocity: rigidB.angularVelocity = (float) stream.ReceiveNext(); break; case OnSerializeRigidBody.OnlyVelocity: rigidB.velocity = (Vector2) stream.ReceiveNext(); break; } } else { Debug.LogError("Type of observed is unknown when receiving."); } } protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info) { if (component == null) { return; } if (component is MonoBehaviour) { ExecuteComponentOnSerialize(component, stream, info); } else if (component is Transform) { Transform trans = (Transform) component; switch (this.onSerializeTransformOption) { case OnSerializeTransform.All: stream.SendNext(trans.localPosition); stream.SendNext(trans.localRotation); stream.SendNext(trans.localScale); break; case OnSerializeTransform.OnlyPosition: stream.SendNext(trans.localPosition); break; case OnSerializeTransform.OnlyRotation: stream.SendNext(trans.localRotation); break; case OnSerializeTransform.OnlyScale: stream.SendNext(trans.localScale); break; case OnSerializeTransform.PositionAndRotation: stream.SendNext(trans.localPosition); stream.SendNext(trans.localRotation); break; } } else if (component is Rigidbody) { Rigidbody rigidB = (Rigidbody) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: stream.SendNext(rigidB.velocity); stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyAngularVelocity: stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyVelocity: stream.SendNext(rigidB.velocity); break; } } else if (component is Rigidbody2D) { Rigidbody2D rigidB = (Rigidbody2D) component; switch (this.onSerializeRigidBodyOption) { case OnSerializeRigidBody.All: stream.SendNext(rigidB.velocity); stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyAngularVelocity: stream.SendNext(rigidB.angularVelocity); break; case OnSerializeRigidBody.OnlyVelocity: stream.SendNext(rigidB.velocity); break; } } else { Debug.LogError("Observed type is not serializable: " + component.GetType()); } } protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info) { IPunObservable observable = component as IPunObservable; if (observable != null) { observable.OnPhotonSerializeView(stream, info); } else if (component != null) { MethodInfo method = null; bool found = this.m_OnSerializeMethodInfos.TryGetValue(component, out method); if (!found) { bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out method); if (foundMethod == false) { Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!"); method = null; } this.m_OnSerializeMethodInfos.Add(component, method); } if (method != null) { method.Invoke(component, new object[] {stream, info}); } } } /// <summary> /// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true. /// </summary> /// <remarks> /// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching. /// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially). /// /// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect, /// because the list is refreshed when a RPC gets called. /// </remarks> public void RefreshRpcMonoBehaviourCache() { this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>(); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// RPC calls can target "All" or the "Others". /// Usually, the target "All" gets executed locally immediately after sending the RPC. /// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> /// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param> /// <param name="target">The group of targets and the way the RPC gets sent.</param> /// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RPC(string methodName, PhotonTargets target, params object[] parameters) { PhotonNetwork.RPC(this, methodName, target, false, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// RPC calls can target "All" or the "Others". /// Usually, the target "All" gets executed locally immediately after sending the RPC. /// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> ///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param> ///<param name="target">The group of targets and the way the RPC gets sent.</param> ///<param name="encrypt"> </param> ///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters) { PhotonNetwork.RPC(this, methodName, target, encrypt, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// This method allows you to make an RPC calls on a specific player's client. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> /// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param> /// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param> /// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters) { PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters); } /// <summary> /// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client). /// </summary> /// <remarks> /// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN. /// It enables you to make every client in a room call a specific method. /// /// This method allows you to make an RPC calls on a specific player's client. /// Of course, calls are affected by this client's lag and that of remote clients. /// /// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the /// originating client. /// /// See: [Remote Procedure Calls](@ref rpcManual). /// </remarks> ///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param> ///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param> ///<param name="encrypt"> </param> ///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param> public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters) { PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters); } public static PhotonView Get(Component component) { return component.GetComponent<PhotonView>(); } public static PhotonView Get(GameObject gameObj) { return gameObj.GetComponent<PhotonView>(); } public static PhotonView Find(int viewID) { return PhotonNetwork.networkingPeer.GetPhotonView(viewID); } public override string ToString() { return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { private sealed partial class WorkCoordinator { private sealed class SemanticChangeProcessor : IdleProcessor { private static readonly Func<int, DocumentId, bool, string> s_enqueueLogger = (t, i, b) => string.Format("[{0}] {1} - hint: {2}", t, i.ToString(), b); private readonly AsyncSemaphore _gate; private readonly Registration _registration; private readonly ProjectProcessor _processor; private readonly NonReentrantLock _workGate; private readonly Dictionary<DocumentId, Data> _pendingWork; public SemanticChangeProcessor( IAsynchronousOperationListener listener, Registration registration, IncrementalAnalyzerProcessor documentWorkerProcessor, int backOffTimeSpanInMS, int projectBackOffTimeSpanInMS, CancellationToken cancellationToken) : base(listener, backOffTimeSpanInMS, cancellationToken) { _gate = new AsyncSemaphore(initialCount: 0); _registration = registration; _processor = new ProjectProcessor(listener, registration, documentWorkerProcessor, projectBackOffTimeSpanInMS, cancellationToken); _workGate = new NonReentrantLock(); _pendingWork = new Dictionary<DocumentId, Data>(); Start(); } public override Task AsyncProcessorTask { get { return Task.WhenAll(base.AsyncProcessorTask, _processor.AsyncProcessorTask); } } protected override Task WaitAsync(CancellationToken cancellationToken) { return _gate.WaitAsync(cancellationToken); } protected override async Task ExecuteAsync() { var data = Dequeue(); // we have a hint. check whether we can take advantage of it if (await TryEnqueueFromHint(data.Document, data.ChangedMember).ConfigureAwait(continueOnCapturedContext: false)) { data.AsyncToken.Dispose(); return; } EnqueueFullProjectDependency(data.Document); data.AsyncToken.Dispose(); } private Data Dequeue() { return DequeueWorker(_workGate, _pendingWork, this.CancellationToken); } private async Task<bool> TryEnqueueFromHint(Document document, SyntaxPath changedMember) { if (changedMember == null) { return false; } // see whether we already have semantic model. otherwise, use the expansive full project dependency one // TODO: if there is a reliable way to track changed member, we could use GetSemanticModel here which could // rebuild compilation from scratch SemanticModel model; SyntaxNode declarationNode; if (!document.TryGetSemanticModel(out model) || !changedMember.TryResolve(await document.GetSyntaxRootAsync(this.CancellationToken).ConfigureAwait(false), out declarationNode)) { return false; } var symbol = model.GetDeclaredSymbol(declarationNode, this.CancellationToken); if (symbol == null) { return false; } return await TryEnqueueFromMemberAsync(document, symbol).ConfigureAwait(false) || await TryEnqueueFromTypeAsync(document, symbol).ConfigureAwait(false); } private async Task<bool> TryEnqueueFromTypeAsync(Document document, ISymbol symbol) { if (!IsType(symbol)) { return false; } if (symbol.DeclaredAccessibility == Accessibility.Private) { await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false); Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromType, symbol.Name); return true; } if (IsInternal(symbol)) { var assembly = symbol.ContainingAssembly; EnqueueFullProjectDependency(document, assembly); return true; } return false; } private async Task<bool> TryEnqueueFromMemberAsync(Document document, ISymbol symbol) { if (!IsMember(symbol)) { return false; } var typeSymbol = symbol.ContainingType; if (symbol.DeclaredAccessibility == Accessibility.Private) { await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false); Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromMember, symbol.Name); return true; } if (typeSymbol == null) { return false; } return await TryEnqueueFromTypeAsync(document, typeSymbol).ConfigureAwait(false); } private Task EnqueueWorkItemAsync(Document document, ISymbol symbol) { return EnqueueWorkItemAsync(document, symbol.ContainingType != null ? symbol.ContainingType.Locations : symbol.Locations); } private async Task EnqueueWorkItemAsync(Document thisDocument, ImmutableArray<Location> locations) { var solution = thisDocument.Project.Solution; var projectId = thisDocument.Id.ProjectId; foreach (var location in locations) { Contract.Requires(location.IsInSource); var document = solution.GetDocument(location.SourceTree, projectId); Contract.Requires(document != null); if (thisDocument == document) { continue; } await _processor.EnqueueWorkItemAsync(document).ConfigureAwait(false); } } private bool IsInternal(ISymbol symbol) { return symbol.DeclaredAccessibility == Accessibility.Internal || symbol.DeclaredAccessibility == Accessibility.ProtectedAndInternal || symbol.DeclaredAccessibility == Accessibility.ProtectedOrInternal; } private bool IsType(ISymbol symbol) { return symbol.Kind == SymbolKind.NamedType; } private bool IsMember(ISymbol symbol) { return symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property; } private void EnqueueFullProjectDependency(Document document, IAssemblySymbol internalVisibleToAssembly = null) { var self = document.Project.Id; // if there is no hint (this can happen for cases such as solution/project load and etc), // we can postpond it even further if (internalVisibleToAssembly == null) { _processor.Enqueue(self, needDependencyTracking: true); return; } // most likely we got here since we are called due to typing. // calculate dependency here and register each affected project to the next pipe line var solution = document.Project.Solution; var graph = solution.GetProjectDependencyGraph(); foreach (var projectId in graph.GetProjectsThatTransitivelyDependOnThisProject(self).Concat(self)) { var project = solution.GetProject(projectId); if (project == null) { continue; } Compilation compilation; if (project.TryGetCompilation(out compilation)) { var assembly = compilation.Assembly; if (assembly != null && !assembly.IsSameAssemblyOrHasFriendAccessTo(internalVisibleToAssembly)) { continue; } } _processor.Enqueue(projectId); } Logger.Log(FunctionId.WorkCoordinator_SemanticChange_FullProjects, internalVisibleToAssembly == null ? "full" : "internals"); } public void Enqueue(Document document, SyntaxPath changedMember) { this.UpdateLastAccessTime(); using (_workGate.DisposableWait(this.CancellationToken)) { Data data; if (_pendingWork.TryGetValue(document.Id, out data)) { // create new async token and dispose old one. var newAsyncToken = this.Listener.BeginAsyncOperation("EnqueueSemanticChange"); data.AsyncToken.Dispose(); _pendingWork[document.Id] = new Data(document, data.ChangedMember == changedMember ? changedMember : null, newAsyncToken); return; } _pendingWork.Add(document.Id, new Data(document, changedMember, this.Listener.BeginAsyncOperation("EnqueueSemanticChange"))); _gate.Release(); } Logger.Log(FunctionId.WorkCoordinator_SemanticChange_Enqueue, s_enqueueLogger, Environment.TickCount, document.Id, changedMember != null); } private static TValue DequeueWorker<TKey, TValue>(NonReentrantLock gate, Dictionary<TKey, TValue> map, CancellationToken cancellationToken) { using (gate.DisposableWait(cancellationToken)) { var first = default(KeyValuePair<TKey, TValue>); foreach (var kv in map) { first = kv; break; } // this is only one that removes data from the queue. so, it should always succeed var result = map.Remove(first.Key); Contract.Requires(result); return first.Value; } } private struct Data { public readonly Document Document; public readonly SyntaxPath ChangedMember; public readonly IAsyncToken AsyncToken; public Data(Document document, SyntaxPath changedMember, IAsyncToken asyncToken) { this.AsyncToken = asyncToken; this.Document = document; this.ChangedMember = changedMember; } } private class ProjectProcessor : IdleProcessor { private static readonly Func<int, ProjectId, string> s_enqueueLogger = (t, i) => string.Format("[{0}] {1}", t, i.ToString()); private readonly AsyncSemaphore _gate; private readonly Registration _registration; private readonly IncrementalAnalyzerProcessor _processor; private readonly NonReentrantLock _workGate; private readonly Dictionary<ProjectId, Data> _pendingWork; public ProjectProcessor( IAsynchronousOperationListener listener, Registration registration, IncrementalAnalyzerProcessor processor, int backOffTimeSpanInMS, CancellationToken cancellationToken) : base(listener, backOffTimeSpanInMS, cancellationToken) { _registration = registration; _processor = processor; _gate = new AsyncSemaphore(initialCount: 0); _workGate = new NonReentrantLock(); _pendingWork = new Dictionary<ProjectId, Data>(); Start(); } public void Enqueue(ProjectId projectId, bool needDependencyTracking = false) { this.UpdateLastAccessTime(); using (_workGate.DisposableWait(this.CancellationToken)) { // the project is already in the queue. nothing needs to be done if (_pendingWork.ContainsKey(projectId)) { return; } var data = new Data(projectId, needDependencyTracking, this.Listener.BeginAsyncOperation("EnqueueWorkItemForSemanticChangeAsync")); _pendingWork.Add(projectId, data); _gate.Release(); } Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, projectId); } public async Task EnqueueWorkItemAsync(Document document) { // we are shutting down this.CancellationToken.ThrowIfCancellationRequested(); // call to this method is serialized. and only this method does the writing. var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, this.CancellationToken).ConfigureAwait(false); _processor.Enqueue( new WorkItem(document.Id, document.Project.Language, InvocationReasons.SemanticChanged, isLowPriority, this.Listener.BeginAsyncOperation("Semantic WorkItem"))); } protected override Task WaitAsync(CancellationToken cancellationToken) { return _gate.WaitAsync(cancellationToken); } protected override async Task ExecuteAsync() { var data = Dequeue(); using (data.AsyncToken) { var project = _registration.CurrentSolution.GetProject(data.ProjectId); if (project == null) { return; } if (!data.NeedDependencyTracking) { await EnqueueWorkItemAsync(project).ConfigureAwait(false); return; } // do dependency tracking here with current solution var solution = _registration.CurrentSolution; var graph = solution.GetProjectDependencyGraph(); foreach (var projectId in graph.GetProjectsThatTransitivelyDependOnThisProject(data.ProjectId).Concat(data.ProjectId)) { project = solution.GetProject(projectId); await EnqueueWorkItemAsync(project).ConfigureAwait(false); } } } private Data Dequeue() { return DequeueWorker(_workGate, _pendingWork, this.CancellationToken); } private async Task EnqueueWorkItemAsync(Project project) { if (project == null) { return; } foreach (var documentId in project.DocumentIds) { await EnqueueWorkItemAsync(project.GetDocument(documentId)).ConfigureAwait(false); } } private struct Data { public readonly IAsyncToken AsyncToken; public readonly ProjectId ProjectId; public readonly bool NeedDependencyTracking; public Data(ProjectId projectId, bool needDependencyTracking, IAsyncToken asyncToken) { this.AsyncToken = asyncToken; this.ProjectId = projectId; this.NeedDependencyTracking = needDependencyTracking; } } } } } } }
// // ColorPaletteWidget.cs // // Author: // Jonathan Pobst <[email protected]> // // Copyright (c) 2010 Jonathan Pobst // // 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 Cairo; using Pinta.Core; namespace Pinta { [System.ComponentModel.ToolboxItem (true)] public class ColorPaletteWidget : Gtk.DrawingArea { private Rectangle primary_rect = new Rectangle (7, 7, 30, 30); private Rectangle secondary_rect = new Rectangle (22, 22, 30, 30); private Rectangle swap_rect = new Rectangle (37, 6, 15, 15); private Gdk.Pixbuf swap_icon; private List<Color> palette; public ColorPaletteWidget () { // Insert initialization code here. this.AddEvents ((int)Gdk.EventMask.ButtonPressMask); swap_icon = PintaCore.Resources.GetIcon ("ColorPalette.SwapIcon.png"); palette = new List<Color> (); palette.Add (new Color (255 / 255f, 255 / 255f, 255 / 255f)); palette.Add (new Color (128 / 255f, 128 / 255f, 128 / 255f)); palette.Add (new Color (127 / 255f, 0 / 255f, 0 / 255f)); palette.Add (new Color (127 / 255f, 51 / 255f, 0 / 255f)); palette.Add (new Color (127 / 255f, 106 / 255f, 0 / 255f)); palette.Add (new Color (91 / 255f, 127 / 255f, 0 / 255f)); palette.Add (new Color (38 / 255f, 127 / 255f, 0 / 255f)); palette.Add (new Color (0 / 255f, 127 / 255f, 14 / 255f)); palette.Add (new Color (0 / 255f, 127 / 255f, 70 / 255f)); palette.Add (new Color (0 / 255f, 127 / 255f, 127 / 255f)); palette.Add (new Color (0 / 255f, 74 / 255f, 127 / 255f)); palette.Add (new Color (0 / 255f, 19 / 255f, 127 / 255f)); palette.Add (new Color (33 / 255f, 0 / 255f, 127 / 255f)); palette.Add (new Color (87 / 255f, 0 / 255f, 127 / 255f)); palette.Add (new Color (127 / 255f, 0 / 255f, 110 / 255f)); palette.Add (new Color (127 / 255f, 0 / 255f, 55 / 255f)); palette.Add (new Color (0 / 255f, 0 / 255f, 0 / 255f)); palette.Add (new Color (64 / 255f, 64 / 255f, 64 / 255f)); palette.Add (new Color (255 / 255f, 0 / 255f, 0 / 255f)); palette.Add (new Color (255 / 255f, 106 / 255f, 0 / 255f)); palette.Add (new Color (255 / 255f, 216 / 255f, 0 / 255f)); palette.Add (new Color (182 / 255f, 255 / 255f, 0 / 255f)); palette.Add (new Color (76 / 255f, 255 / 255f, 0 / 255f)); palette.Add (new Color (0 / 255f, 255 / 255f, 33 / 255f)); palette.Add (new Color (0 / 255f, 255 / 255f, 144 / 255f)); palette.Add (new Color (0 / 255f, 255 / 255f, 255 / 255f)); palette.Add (new Color (0 / 255f, 148 / 255f, 255 / 255f)); palette.Add (new Color (0 / 255f, 38 / 255f, 255 / 255f)); palette.Add (new Color (72 / 255f, 0 / 255f, 255 / 255f)); palette.Add (new Color (178 / 255f, 0 / 255f, 255 / 255f)); palette.Add (new Color (255 / 255f, 0 / 255f, 220 / 255f)); palette.Add (new Color (255 / 255f, 0 / 255f, 110 / 255f)); palette.Add (new Color (160 / 255f, 160 / 255f, 160 / 255f)); palette.Add (new Color (48 / 255f, 48 / 255f, 48 / 255f)); palette.Add (new Color (255 / 255f, 127 / 255f, 127 / 255f)); palette.Add (new Color (255 / 255f, 178 / 255f, 127 / 255f)); palette.Add (new Color (255 / 255f, 233 / 255f, 127 / 255f)); palette.Add (new Color (218 / 255f, 255 / 255f, 127 / 255f)); palette.Add (new Color (165 / 255f, 255 / 255f, 127 / 255f)); palette.Add (new Color (127 / 255f, 255 / 255f, 142 / 255f)); palette.Add (new Color (127 / 255f, 255 / 255f, 197 / 255f)); palette.Add (new Color (127 / 255f, 255 / 255f, 255 / 255f)); palette.Add (new Color (127 / 255f, 201 / 255f, 255 / 255f)); palette.Add (new Color (127 / 255f, 146 / 255f, 255 / 255f)); palette.Add (new Color (161 / 255f, 127 / 255f, 255 / 255f)); palette.Add (new Color (214 / 255f, 127 / 255f, 255 / 255f)); palette.Add (new Color (255 / 255f, 127 / 255f, 237 / 255f)); palette.Add (new Color (255 / 255f, 127 / 255f, 182 / 255f)); } public void Initialize () { PintaCore.Palette.PrimaryColorChanged += new EventHandler (Palette_ColorChanged); PintaCore.Palette.SecondaryColorChanged += new EventHandler (Palette_ColorChanged); } private void Palette_ColorChanged (object sender, EventArgs e) { GdkWindow.Invalidate (); } protected override bool OnButtonPressEvent (Gdk.EventButton ev) { if (swap_rect.ContainsPoint (ev.X, ev.Y)) { Color temp = PintaCore.Palette.PrimaryColor; PintaCore.Palette.PrimaryColor = PintaCore.Palette.SecondaryColor; PintaCore.Palette.SecondaryColor = temp; GdkWindow.Invalidate (); } if (primary_rect.ContainsPoint (ev.X, ev.Y)) { Gtk.ColorSelectionDialog csd = new Gtk.ColorSelectionDialog ("Choose Primary Color"); csd.ColorSelection.PreviousColor = PintaCore.Palette.PrimaryColor.ToGdkColor (); csd.ColorSelection.CurrentColor = PintaCore.Palette.PrimaryColor.ToGdkColor (); csd.ColorSelection.CurrentAlpha = PintaCore.Palette.PrimaryColor.GdkColorAlpha (); csd.ColorSelection.HasOpacityControl = true; int response = csd.Run (); if (response == (int)Gtk.ResponseType.Ok) { PintaCore.Palette.PrimaryColor = csd.ColorSelection.GetCairoColor (); } csd.Destroy (); } else if (secondary_rect.ContainsPoint (ev.X, ev.Y)) { Gtk.ColorSelectionDialog csd = new Gtk.ColorSelectionDialog ("Choose Secondary Color"); csd.ColorSelection.PreviousColor = PintaCore.Palette.SecondaryColor.ToGdkColor (); csd.ColorSelection.CurrentColor = PintaCore.Palette.SecondaryColor.ToGdkColor (); csd.ColorSelection.CurrentAlpha = PintaCore.Palette.SecondaryColor.GdkColorAlpha (); csd.ColorSelection.HasOpacityControl = true; int response = csd.Run (); if (response == (int)Gtk.ResponseType.Ok) { PintaCore.Palette.SecondaryColor = csd.ColorSelection.GetCairoColor (); } csd.Destroy (); } int pal = PointToPalette ((int)ev.X, (int)ev.Y); if (pal >= 0) { if (ev.Button == 3) PintaCore.Palette.SecondaryColor = palette[pal]; else PintaCore.Palette.PrimaryColor = palette[pal]; GdkWindow.Invalidate (); } // Insert button press handling code here. return base.OnButtonPressEvent (ev); } protected override bool OnExposeEvent (Gdk.EventExpose ev) { base.OnExposeEvent (ev); using (Context g = Gdk.CairoHelper.Create (GdkWindow)) { g.FillRectangle (secondary_rect, PintaCore.Palette.SecondaryColor); g.DrawRectangle (new Rectangle (secondary_rect.X + 1, secondary_rect.Y + 1, secondary_rect.Width - 2, secondary_rect.Height - 2), new Color (1, 1, 1), 1); g.DrawRectangle (secondary_rect, new Color (0, 0, 0), 1); g.FillRectangle (primary_rect, PintaCore.Palette.PrimaryColor); g.DrawRectangle (new Rectangle (primary_rect.X + 1, primary_rect.Y + 1, primary_rect.Width - 2, primary_rect.Height - 2), new Color (1, 1, 1), 1); g.DrawRectangle (primary_rect, new Color (0, 0, 0), 1); g.DrawPixbuf (swap_icon, swap_rect.Location ()); // Draw swatches int x = 7; for (int i = 0; i < 48; i++) { if (i == 16 || i == 32) x += 15; g.FillRectangle (new Rectangle (x, 60 + ((i % 16) * 15), 15, 15), palette[i]); } } return true; } protected override void OnSizeRequested (ref Gtk.Requisition requisition) { // Calculate desired size here. requisition.Height = 305; requisition.Width = 60; } private int PointToPalette (int x, int y) { int col = -1; int row = 0; if (x >= 7 && x < 22) col = 0; else if (x >= 22 && x < 38) col = 16; else if (x >= 38 && x < 54) col = 32; else return -1; if (y < 60 || y > 60 + (16 * 15)) return -1; row = (y - 60) / 15; return col + row; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using RegPetServer.WebAPI.Areas.HelpPage.ModelDescriptions; using RegPetServer.WebAPI.Areas.HelpPage.Models; namespace RegPetServer.WebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//------------------------------------------------------------------------------ // <copyright file="WizardStepBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.CodeDom.Compiler; using System.Collections; using System.ComponentModel; using System.Web; using System.Web.UI; public sealed class WizardStepControlBuilder : ControlBuilder { internal override void SetParentBuilder(ControlBuilder parentBuilder) { // Do not check containment at designtime or in a skin file. if (Parser.FInDesigner || Parser is PageThemeParser) return; if (parentBuilder.ControlType == null || !(typeof(WizardStepCollection).IsAssignableFrom(parentBuilder.ControlType))) { throw new HttpException(SR.GetString(SR.WizardStep_WrongContainment)); } base.SetParentBuilder(parentBuilder); } } [ Bindable(false), ControlBuilderAttribute(typeof(WizardStepControlBuilder)), ToolboxItem(false) ] public abstract class WizardStepBase : View { private Wizard _owner; [ WebCategory("Behavior"), Themeable(false), Filterable(false), DefaultValue(true), WebSysDescription(SR.WizardStep_AllowReturn) ] public virtual bool AllowReturn { get { object o = ViewState["AllowReturn"]; return o == null? true : (bool)o; } set { ViewState["AllowReturn"] = value; } } /// <devdoc> /// <para>Gets and sets a value indicating whether theme is enabled.</para> /// </devdoc> [ Browsable(true) ] public override bool EnableTheming { get { return base.EnableTheming; } set { base.EnableTheming = value; } } public override string ID { get { return base.ID; } set { // VSWhidbey 407127. Need to validate control ID here since WiardStepBase does not have a designer. if (Owner != null && Owner.DesignMode) { if (!CodeGenerator.IsValidLanguageIndependentIdentifier(value)) { throw new ArgumentException(SR.GetString(SR.Invalid_identifier, value)); } if (value != null && value.Equals(Owner.ID, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.GetString(SR.Id_already_used, value)); } foreach (WizardStepBase step in Owner.WizardSteps) { if (step == this) { continue; } if (step.ID != null && step.ID.Equals(value, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.GetString(SR.Id_already_used, value)); } } } base.ID = value; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), WebCategory("Appearance"), WebSysDescription(SR.WizardStep_Name) ] public virtual String Name { get { if (!String.IsNullOrEmpty(Title)) { return Title; } if (!String.IsNullOrEmpty(ID)) { return ID; } return null; } } internal virtual Wizard Owner { get { return _owner; } set { _owner = value; } } [ WebCategory("Behavior"), DefaultValue(WizardStepType.Auto), WebSysDescription(SR.WizardStep_StepType) ] public virtual WizardStepType StepType { get { object o = ViewState["StepType"]; return o == null? WizardStepType.Auto : (WizardStepType)o; } set { if (value < WizardStepType.Auto || value > WizardStepType.Step) { throw new ArgumentOutOfRangeException("value"); } if (StepType != value) { ViewState["StepType"] = value; if (Owner != null) { Owner.OnWizardStepsChanged(); } } } } /// <devdoc> /// <para>Gets or sets the title on the <see cref='System.Web.UI.WebControls.Wizard/> .</para> /// </devdoc> [ DefaultValue(""), Localizable(true), WebCategory("Appearance"), WebSysDescription(SR.WizardStep_Title) ] public virtual string Title { get { string s = (string)ViewState["Title"]; return((s == null) ? String.Empty : s); } set { if (Title != value) { ViewState["Title"] = value; if (Owner != null) { Owner.OnWizardStepsChanged(); } } } } internal string TitleInternal { get { return (string)ViewState["Title"]; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), WebCategory("Appearance"), ] public Wizard Wizard { get { return Owner; } } // VSWhidbey 397000, need to notify the Owner of type change so // the sidebar can be re-databound correctly. protected override void LoadViewState(object savedState) { if (savedState != null) { base.LoadViewState(savedState); if (Owner != null && (ViewState["Title"] != null || ViewState["StepType"] != null)) { Owner.OnWizardStepsChanged(); } } } protected internal override void OnLoad(EventArgs e) { base.OnLoad(e); if (Owner == null && !DesignMode) { throw new InvalidOperationException(SR.GetString(SR.WizardStep_WrongContainment)); } } protected internal override void RenderChildren(HtmlTextWriter writer) { if (!Owner.ShouldRenderChildControl) { return; } base.RenderChildren(writer); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Newtonsoft.Json.Linq; using Orchard; using Orchard.ContentManagement; using Orchard.Data; using Orchard.DisplayManagement; using Orchard.Forms.Services; using Orchard.Localization; using Orchard.Mvc; using Orchard.Mvc.Extensions; using Orchard.Security; using Orchard.Settings; using Orchard.Themes; using Orchard.UI.Navigation; using Orchard.UI.Notify; using Orchard.Workflows.Models; using Orchard.Workflows.Services; using Orchard.Workflows.ViewModels; namespace ceenq.com.Workflow.Controllers { [ValidateInput(false)] public class AdminController : Controller, IUpdateModel { private readonly ISiteService _siteService; private readonly IRepository<WorkflowDefinitionRecord> _workflowDefinitionRecords; private readonly IRepository<WorkflowRecord> _workflowRecords; private readonly IActivitiesManager _activitiesManager; private readonly IFormManager _formManager; public AdminController( IOrchardServices services, IShapeFactory shapeFactory, ISiteService siteService, IRepository<WorkflowDefinitionRecord> workflowDefinitionRecords, IRepository<WorkflowRecord> workflowRecords, IActivitiesManager activitiesManager, IFormManager formManager ) { _siteService = siteService; _workflowDefinitionRecords = workflowDefinitionRecords; _workflowRecords = workflowRecords; _activitiesManager = activitiesManager; _formManager = formManager; Services = services; T = NullLocalizer.Instance; New = shapeFactory; } dynamic New { get; set; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ActionResult Index(AdminIndexOptions options, PagerParameters pagerParameters) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to list workflows"))) return new HttpUnauthorizedResult(); var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); // default options if (options == null) options = new AdminIndexOptions(); var queries = _workflowDefinitionRecords.Table; switch (options.Filter) { case WorkflowDefinitionFilter.All: break; default: throw new ArgumentOutOfRangeException(); } if (!String.IsNullOrWhiteSpace(options.Search)) { queries = queries.Where(w => w.Name.Contains(options.Search)); } var pagerShape = New.Pager(pager).TotalItemCount(queries.Count()); switch (options.Order) { case WorkflowDefinitionOrder.Name: queries = queries.OrderBy(u => u.Name); break; } if (pager.GetStartIndex() > 0) { queries = queries.Skip(pager.GetStartIndex()); } if (pager.PageSize > 0) { queries = queries.Take(pager.PageSize); } var results = queries.ToList(); var model = new AdminIndexViewModel { WorkflowDefinitions = results.Select(x => new WorkflowDefinitionEntry { WorkflowDefinitionRecord = x, WokflowDefinitionId = x.Id, Name = x.Name }).ToList(), Options = options, Pager = pagerShape }; // maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.Order", options.Order); pagerShape.RouteData(routeData); return View(model); } public ActionResult List(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to list workflows"))) return new HttpUnauthorizedResult(); var contentItem = Services.ContentManager.Get(id, VersionOptions.Latest); if (contentItem == null) { return HttpNotFound(); } var workflows = _workflowRecords.Table.Where(x => x.ContentItemRecord == contentItem.Record).ToList(); var viewModel = New.ViewModel( ContentItem: contentItem, Workflows: workflows ); return View(viewModel); } public ActionResult Create() { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to create workflows"))) return new HttpUnauthorizedResult(); return View(); } [HttpPost, ActionName("Create")] public ActionResult CreatePost(string name) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to create workflows"))) return new HttpUnauthorizedResult(); var workflowDefinitionRecord = new WorkflowDefinitionRecord { Name = name }; _workflowDefinitionRecords.Create(workflowDefinitionRecord); return RedirectToAction("Edit", new { workflowDefinitionRecord.Id }); } public ActionResult Edit(int id, string localId, int? workflowId) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); // convert the workflow definition into its view model var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id); var workflowDefinitionViewModel = CreateWorkflowDefinitionViewModel(workflowDefinitionRecord); var workflow = workflowId.HasValue ? _workflowRecords.Get(workflowId.Value) : null; var viewModel = new AdminEditViewModel { LocalId = String.IsNullOrEmpty(localId) ? Guid.NewGuid().ToString() : localId, IsLocal = !String.IsNullOrEmpty(localId), WorkflowDefinition = workflowDefinitionViewModel, AllActivities = _activitiesManager.GetActivities(), Workflow = workflow }; return View(viewModel); } [HttpPost] public ActionResult Delete(int id) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to manage workflows"))) return new HttpUnauthorizedResult(); var workflowDefinition = _workflowDefinitionRecords.Get(id); if (workflowDefinition != null) { _workflowDefinitionRecords.Delete(workflowDefinition); Services.Notifier.Information(T("Workflow {0} deleted", workflowDefinition.Name)); } return RedirectToAction("Index"); } [HttpPost] public ActionResult DeleteWorkflow(int id, string returnUrl) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to manage workflows"))) return new HttpUnauthorizedResult(); var workflow = _workflowRecords.Get(id); if (workflow != null) { _workflowRecords.Delete(workflow); Services.Notifier.Information(T("Workflow deleted")); } return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); } private WorkflowDefinitionViewModel CreateWorkflowDefinitionViewModel(WorkflowDefinitionRecord workflowDefinitionRecord) { if (workflowDefinitionRecord == null) { throw new ArgumentNullException("workflowDefinitionRecord"); } var workflowDefinitionModel = new WorkflowDefinitionViewModel { Id = workflowDefinitionRecord.Id, Name = workflowDefinitionRecord.Name }; dynamic workflow = new JObject(); workflow.Activities = new JArray(workflowDefinitionRecord.ActivityRecords.Select(x => { dynamic activity = new JObject(); activity.Name = x.Name; activity.Id = x.Id; activity.ClientId = x.Name + "_" + x.Id; activity.Left = x.X; activity.Top = x.Y; activity.Start = x.Start; activity.State = FormParametersHelper.FromJsonString(x.State); return activity; })); workflow.Connections = new JArray(workflowDefinitionRecord.TransitionRecords.Select(x => { dynamic connection = new JObject(); connection.Id = x.Id; connection.SourceId = x.SourceActivityRecord.Name + "_" + x.SourceActivityRecord.Id; connection.TargetId = x.DestinationActivityRecord.Name + "_" + x.DestinationActivityRecord.Id; connection.SourceEndpoint = x.SourceEndpoint; return connection; })); workflowDefinitionModel.JsonData = FormParametersHelper.ToJsonString(workflow); return workflowDefinitionModel; } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Save")] public ActionResult EditPost(int id, string localId, string data) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id); if (workflowDefinitionRecord == null) { return HttpNotFound(); } workflowDefinitionRecord.Enabled = true; var state = FormParametersHelper.FromJsonString(data); var activitiesIndex = new Dictionary<string, ActivityRecord>(); workflowDefinitionRecord.ActivityRecords.Clear(); foreach (var activity in state.Activities) { ActivityRecord activityRecord; workflowDefinitionRecord.ActivityRecords.Add(activityRecord = new ActivityRecord { Name = activity.Name, X = activity.Left, Y = activity.Top, Start = activity.Start, State = FormParametersHelper.ToJsonString(activity.State), WorkflowDefinitionRecord = workflowDefinitionRecord }); activitiesIndex.Add((string)activity.ClientId, activityRecord); } workflowDefinitionRecord.TransitionRecords.Clear(); foreach (var connection in state.Connections) { workflowDefinitionRecord.TransitionRecords.Add(new TransitionRecord { SourceActivityRecord = activitiesIndex[(string)connection.SourceId], DestinationActivityRecord = activitiesIndex[(string)connection.TargetId], SourceEndpoint = connection.SourceEndpoint, WorkflowDefinitionRecord = workflowDefinitionRecord }); } Services.Notifier.Information(T("Workflow saved successfully")); return RedirectToAction("Edit", new { id, localId }); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Cancel")] public ActionResult EditPostCancel() { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); return View(); } [Themed(false)] [HttpPost] public ActionResult RenderActivity(ActivityViewModel model) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(model.Name); if (activity == null) { return HttpNotFound(); } dynamic shape = New.Activity(activity); if (model.State != null) { var state = FormParametersHelper.ToDynamic(FormParametersHelper.ToString(model.State)); shape.State(state); } else { shape.State(FormParametersHelper.FromJsonString("{}")); } shape.Metadata.Alternates.Add("Activity__" + activity.Name); return new ShapeResult(this, shape); } public ActionResult EditActivity(string localId, string clientId, ActivityViewModel model) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(model.Name); if (activity == null) { return HttpNotFound(); } // build the form, and let external components alter it var form = activity.Form == null ? null : _formManager.Build(activity.Form); // form is bound on client side var viewModel = New.ViewModel(LocalId: localId, ClientId: clientId, Form: form); return View(viewModel); } [HttpPost, ActionName("EditActivity")] [FormValueRequired("_submit.Save")] public ActionResult EditActivityPost(int id, string localId, string name, string clientId, FormCollection formValues) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(name); if (activity == null) { return HttpNotFound(); } // validating form values _formManager.Validate(new ValidatingContext { FormName = activity.Form, ModelState = ModelState, ValueProvider = ValueProvider }); // stay on the page if there are validation errors if (!ModelState.IsValid) { // build the form, and let external components alter it var form = activity.Form == null ? null : _formManager.Build(activity.Form); // bind form with existing values. _formManager.Bind(form, ValueProvider); var viewModel = New.ViewModel(Id: id, LocalId: localId, Form: form); return View(viewModel); } var model = new UpdatedActivityModel { ClientId = clientId, Data = HttpUtility.JavaScriptStringEncode(FormParametersHelper.ToJsonString(formValues)) }; TempData["UpdatedViewModel"] = model; return RedirectToAction("Edit", new { id, localId }); } [HttpPost, ActionName("EditActivity")] [FormValueRequired("_submit.Cancel")] public ActionResult EditActivityPostCancel(int id, string localId, string name, string clientId, FormCollection formValues) { if (!Services.Authorizer.Authorize(Permissions.ManageWorkflows, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); return RedirectToAction("Edit", new {id, localId }); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } public void AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene3x { using Lucene.Net.Support; using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory; using Directory = Lucene.Net.Store.Directory; /* * 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 IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexFormatTooNewException = Lucene.Net.Index.IndexFormatTooNewException; using IndexFormatTooOldException = Lucene.Net.Index.IndexFormatTooOldException; using IndexInput = Lucene.Net.Store.IndexInput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using SegmentCommitInfo = Lucene.Net.Index.SegmentCommitInfo; using SegmentInfo = Lucene.Net.Index.SegmentInfo; using SegmentInfos = Lucene.Net.Index.SegmentInfos; /// <summary> /// Lucene 3x implementation of <seealso cref="SegmentInfoReader"/>. /// @lucene.experimental </summary> /// @deprecated Only for reading existing 3.x indexes [Obsolete("Only for reading existing 3.x indexes")] public class Lucene3xSegmentInfoReader : SegmentInfoReader { public static void ReadLegacyInfos(SegmentInfos infos, Directory directory, IndexInput input, int format) { infos.Version = input.ReadLong(); // read version infos.Counter = input.ReadInt(); // read counter Lucene3xSegmentInfoReader reader = new Lucene3xSegmentInfoReader(); for (int i = input.ReadInt(); i > 0; i--) // read segmentInfos { SegmentCommitInfo siPerCommit = reader.ReadLegacySegmentInfo(directory, format, input); SegmentInfo si = siPerCommit.Info; if (si.Version == null) { // Could be a 3.0 - try to open the doc stores - if it fails, it's a // 2.x segment, and an IndexFormatTooOldException will be thrown, // which is what we want. Directory dir = directory; if (Lucene3xSegmentInfoFormat.GetDocStoreOffset(si) != -1) { if (Lucene3xSegmentInfoFormat.GetDocStoreIsCompoundFile(si)) { dir = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(Lucene3xSegmentInfoFormat.GetDocStoreSegment(si), "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION), IOContext.READONCE, false); } } else if (si.UseCompoundFile) { dir = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(si.Name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), IOContext.READONCE, false); } try { Lucene3xStoredFieldsReader.CheckCodeVersion(dir, Lucene3xSegmentInfoFormat.GetDocStoreSegment(si)); } finally { // If we opened the directory, close it if (dir != directory) { dir.Dispose(); } } // Above call succeeded, so it's a 3.0 segment. Upgrade it so the next // time the segment is read, its version won't be null and we won't // need to open FieldsReader every time for each such segment. si.Version = "3.0"; } else if (si.Version.Equals("2.x")) { // If it's a 3x index touched by 3.1+ code, then segments record their // version, whether they are 2.x ones or not. We detect that and throw // appropriate exception. throw new IndexFormatTooOldException("segment " + si.Name + " in resource " + input, si.Version); } infos.Add(siPerCommit); } infos.UserData = input.ReadStringStringMap(); } public override SegmentInfo Read(Directory directory, string segmentName, IOContext context) { // NOTE: this is NOT how 3.x is really written... string fileName = IndexFileNames.SegmentFileName(segmentName, "", Lucene3xSegmentInfoFormat.UPGRADED_SI_EXTENSION); bool success = false; IndexInput input = directory.OpenInput(fileName, context); try { SegmentInfo si = ReadUpgradedSegmentInfo(segmentName, directory, input); success = true; return si; } finally { if (!success) { IOUtils.CloseWhileHandlingException(input); } else { input.Dispose(); } } } private static void AddIfExists(Directory dir, ISet<string> files, string fileName) { if (dir.FileExists(fileName)) { files.Add(fileName); } } /// <summary> /// reads from legacy 3.x segments_N </summary> private SegmentCommitInfo ReadLegacySegmentInfo(Directory dir, int format, IndexInput input) { // check that it is a format we can understand if (format > Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS) { throw new IndexFormatTooOldException(input, format, Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS, Lucene3xSegmentInfoFormat.FORMAT_3_1); } if (format < Lucene3xSegmentInfoFormat.FORMAT_3_1) { throw new IndexFormatTooNewException(input, format, Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS, Lucene3xSegmentInfoFormat.FORMAT_3_1); } string version; if (format <= Lucene3xSegmentInfoFormat.FORMAT_3_1) { version = input.ReadString(); } else { version = null; } string name = input.ReadString(); int docCount = input.ReadInt(); long delGen = input.ReadLong(); int docStoreOffset = input.ReadInt(); IDictionary<string, string> attributes = new Dictionary<string, string>(); // parse the docstore stuff and shove it into attributes string docStoreSegment; bool docStoreIsCompoundFile; if (docStoreOffset != -1) { docStoreSegment = input.ReadString(); docStoreIsCompoundFile = input.ReadByte() == SegmentInfo.YES; attributes[Lucene3xSegmentInfoFormat.DS_OFFSET_KEY] = Convert.ToString(docStoreOffset); attributes[Lucene3xSegmentInfoFormat.DS_NAME_KEY] = docStoreSegment; attributes[Lucene3xSegmentInfoFormat.DS_COMPOUND_KEY] = Convert.ToString(docStoreIsCompoundFile); } else { docStoreSegment = name; docStoreIsCompoundFile = false; } // pre-4.0 indexes write a byte if there is a single norms file byte b = input.ReadByte(); //System.out.println("version=" + version + " name=" + name + " docCount=" + docCount + " delGen=" + delGen + " dso=" + docStoreOffset + " dss=" + docStoreSegment + " dssCFs=" + docStoreIsCompoundFile + " b=" + b + " format=" + format); Debug.Assert(1 == b, "expected 1 but was: " + b + " format: " + format); int numNormGen = input.ReadInt(); IDictionary<int, long> normGen; if (numNormGen == SegmentInfo.NO) { normGen = null; } else { normGen = new Dictionary<int, long>(); for (int j = 0; j < numNormGen; j++) { normGen[j] = input.ReadLong(); } } bool isCompoundFile = input.ReadByte() == SegmentInfo.YES; int delCount = input.ReadInt(); Debug.Assert(delCount <= docCount); bool hasProx = input.ReadByte() == 1; IDictionary<string, string> diagnostics = input.ReadStringStringMap(); if (format <= Lucene3xSegmentInfoFormat.FORMAT_HAS_VECTORS) { // NOTE: unused int hasVectors = input.ReadByte(); } // Replicate logic from 3.x's SegmentInfo.files(): ISet<string> files = new HashSet<string>(); if (isCompoundFile) { files.Add(IndexFileNames.SegmentFileName(name, "", IndexFileNames.COMPOUND_FILE_EXTENSION)); } else { AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xFieldInfosReader.FIELD_INFOS_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.FREQ_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.PROX_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.TERMS_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xNormsProducer.NORMS_EXTENSION)); } if (docStoreOffset != -1) { if (docStoreIsCompoundFile) { files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION)); } else { files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xStoredFieldsReader.FIELDS_INDEX_EXTENSION)); files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION)); } } else if (!isCompoundFile) { files.Add(IndexFileNames.SegmentFileName(name, "", Lucene3xStoredFieldsReader.FIELDS_INDEX_EXTENSION)); files.Add(IndexFileNames.SegmentFileName(name, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION)); AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION)); } // parse the normgen stuff and shove it into attributes if (normGen != null) { attributes[Lucene3xSegmentInfoFormat.NORMGEN_KEY] = Convert.ToString(numNormGen); foreach (KeyValuePair<int, long> ent in normGen) { long gen = ent.Value; if (gen >= SegmentInfo.YES) { // Definitely a separate norm file, with generation: files.Add(IndexFileNames.FileNameFromGeneration(name, "s" + ent.Key, gen)); attributes[Lucene3xSegmentInfoFormat.NORMGEN_PREFIX + ent.Key] = Convert.ToString(gen); } else if (gen == SegmentInfo.NO) { // No separate norm } else { // We should have already hit indexformat too old exception Debug.Assert(false); } } } SegmentInfo info = new SegmentInfo(dir, version, name, docCount, isCompoundFile, null, diagnostics, CollectionsHelper.UnmodifiableMap(attributes)); info.Files = files; SegmentCommitInfo infoPerCommit = new SegmentCommitInfo(info, delCount, delGen, -1); return infoPerCommit; } private SegmentInfo ReadUpgradedSegmentInfo(string name, Directory dir, IndexInput input) { CodecUtil.CheckHeader(input, Lucene3xSegmentInfoFormat.UPGRADED_SI_CODEC_NAME, Lucene3xSegmentInfoFormat.UPGRADED_SI_VERSION_START, Lucene3xSegmentInfoFormat.UPGRADED_SI_VERSION_CURRENT); string version = input.ReadString(); int docCount = input.ReadInt(); IDictionary<string, string> attributes = input.ReadStringStringMap(); bool isCompoundFile = input.ReadByte() == SegmentInfo.YES; IDictionary<string, string> diagnostics = input.ReadStringStringMap(); ISet<string> files = input.ReadStringSet(); SegmentInfo info = new SegmentInfo(dir, version, name, docCount, isCompoundFile, null, diagnostics, CollectionsHelper.UnmodifiableMap(attributes)); info.Files = files; return info; } } }
// // Ztk.Drawing.cs - a simplistic binding of the Cairo API to C#. // // Authors: Duncan Mak ([email protected]) // Hisham Mardam Bey ([email protected]) // John Luke ([email protected]) // Alp Toker ([email protected]) // // (C) Ximian, Inc. 2003 // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // Copyright (C) 2005 John Luke // Copyright (C) 2006 Alp Toker // // 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; namespace Ztk.Drawing { // sort the functions like in the following page so it is easier to find what is missing // http://cairographics.org/manual/index-all.html internal static class NativeMethods { #if MONOTOUCH const string cairo = "__Internal"; #else const string cairo = "libcairo"; #endif //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern void cairo_append_path (IntPtr cr, Path path); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_arc (IntPtr cr, double xc, double yc, double radius, double angle1, double angle2); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_arc_negative (IntPtr cr, double xc, double yc, double radius, double angle1, double angle2); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_atsui_font_face_create_for_atsu_font_id (IntPtr font_id); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_clip (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_clip_preserve (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_clip_extents (IntPtr cr, out double x1, out double y1, out double x2, out double y2); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_close_path (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_copy_page (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_copy_path (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_copy_path_flat (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_append_path (IntPtr cr, IntPtr path); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_create (IntPtr target); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_curve_to (IntPtr cr, double x1, double y1, double x2, double y2, double x3, double y3); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_debug_reset_static_data (); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_destroy (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_device_to_user (IntPtr cr, ref double x, ref double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_device_to_user_distance (IntPtr cr, ref double dx, ref double dy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_fill (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_fill_extents (IntPtr cr, out double x1, out double y1, out double x2, out double y2); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_fill_preserve (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_extents (IntPtr cr, out FontExtents extents); // FontFace [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_face_destroy (IntPtr font_face); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern FontType cairo_font_face_get_type (IntPtr font_face); //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern void cairo_font_face_get_user_data (IntPtr font_face); //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern void cairo_font_face_set_user_data (IntPtr font_face); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_font_face_reference (IntPtr font_face); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_font_face_status (IntPtr font_face); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern uint cairo_font_face_get_reference_count (IntPtr surface); // FontOptions [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_font_options_copy (IntPtr original); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_font_options_create (); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_options_destroy (IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] [return: MarshalAs (UnmanagedType.U1)] internal static extern bool cairo_font_options_equal (IntPtr options, IntPtr other); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Antialias cairo_font_options_get_antialias (IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern HintMetrics cairo_font_options_get_hint_metrics (IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern HintStyle cairo_font_options_get_hint_style (IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern SubpixelOrder cairo_font_options_get_subpixel_order (IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern long cairo_font_options_hash (IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_options_merge (IntPtr options, IntPtr other); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_options_set_antialias (IntPtr options, Antialias aa); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_options_set_hint_metrics (IntPtr options, HintMetrics metrics); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_options_set_hint_style (IntPtr options, HintStyle style); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_font_options_set_subpixel_order (IntPtr options, SubpixelOrder order); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_font_options_status (IntPtr options); // Freetype / FontConfig [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_ft_font_face_create_for_ft_face (IntPtr face, int load_flags); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_ft_font_face_create_for_pattern (IntPtr fc_pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_ft_font_options_substitute (FontOptions options, IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_ft_scaled_font_lock_face (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_ft_scaled_font_unlock_face (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Antialias cairo_get_antialias (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_get_current_point (IntPtr cr, out double x, out double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern FillRule cairo_get_fill_rule (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_get_font_face (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_get_font_matrix (IntPtr cr, out Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_get_font_options (IntPtr cr, IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_get_group_target (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern LineCap cairo_get_line_cap (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern LineJoin cairo_get_line_join (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern double cairo_get_line_width (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_get_matrix (IntPtr cr, Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern double cairo_get_miter_limit (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Operator cairo_get_operator (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern uint cairo_get_reference_count (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_get_source (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_get_target (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern double cairo_get_tolerance (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_glitz_surface_create (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_glyph_extents (IntPtr cr, IntPtr glyphs, int num_glyphs, out TextExtents extents); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_glyph_path (IntPtr cr, IntPtr glyphs, int num_glyphs); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] [return: MarshalAs (UnmanagedType.U1)] internal static extern bool cairo_has_current_point (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_identity_matrix (IntPtr cr); // ImageSurface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_image_surface_create (Ztk.Drawing.Format format, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_image_surface_create_for_data (byte[] data, Ztk.Drawing.Format format, int width, int height, int stride); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_image_surface_create_for_data (IntPtr data, Ztk.Drawing.Format format, int width, int height, int stride); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_image_surface_create_from_png (string filename); //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern IntPtr cairo_image_surface_create_from_png_stream (string filename); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_image_surface_get_data (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Format cairo_image_surface_get_format (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_image_surface_get_height (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_image_surface_get_stride (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_image_surface_get_width (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] [return: MarshalAs (UnmanagedType.U1)] internal static extern bool cairo_in_clip (IntPtr cr, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] [return: MarshalAs (UnmanagedType.U1)] internal static extern bool cairo_in_fill (IntPtr cr, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] [return: MarshalAs (UnmanagedType.U1)] internal static extern bool cairo_in_stroke (IntPtr cr, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_line_to (IntPtr cr, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_mask (IntPtr cr, IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_mask_surface (IntPtr cr, IntPtr surface, double x, double y); // Matrix [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_init (Matrix matrix, double xx, double yx, double xy, double yy, double x0, double y0); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_init_identity (Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_init_rotate (Matrix matrix, double radians); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_init_scale (Matrix matrix, double sx, double sy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_init_translate (Matrix matrix, double tx, double ty); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_matrix_invert (Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_multiply (Matrix result, Matrix a, Matrix b); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_scale (Matrix matrix, double sx, double sy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_rotate (Matrix matrix, double radians); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_transform_distance (Matrix matrix, ref double dx, ref double dy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_transform_point (Matrix matrix, ref double x, ref double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_matrix_translate (Matrix matrix, double tx, double ty); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_move_to (IntPtr cr, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_new_path (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_new_sub_path (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_paint (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_paint_with_alpha (IntPtr cr, double alpha); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_path_destroy (IntPtr path); // Pattern [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pattern_add_color_stop_rgb (IntPtr pattern, double offset, double red, double green, double blue); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pattern_add_color_stop_rgba (IntPtr pattern, double offset, double red, double green, double blue, double alpha); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_pattern_get_color_stop_count (IntPtr pattern, out int count); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_pattern_get_color_stop_rgba (IntPtr pattern, int index, out double offset, out double red, out double green, out double blue, out double alpha); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pattern_create_for_surface (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_pattern_get_surface (IntPtr pattern, out IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pattern_create_linear (double x0, double y0, double x1, double y1); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_pattern_get_linear_points (IntPtr pattern, out double x0, out double y0, out double x1, out double y1); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pattern_create_radial (double cx0, double cy0, double radius0, double cx1, double cy1, double radius1); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_pattern_get_radial_circles (IntPtr pattern, out double x0, out double y0, out double r0, out double x1, out double y1, out double r1); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pattern_create_rgb (double r, double g, double b); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pattern_create_rgba (double r, double g, double b, double a); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_pattern_get_rgba (IntPtr pattern, out double red, out double green, out double blue, out double alpha); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pattern_destroy (IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Extend cairo_pattern_get_extend (IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Filter cairo_pattern_get_filter (IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pattern_get_matrix (IntPtr pattern, Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern PatternType cairo_pattern_get_type (IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pattern_reference (IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pattern_set_extend (IntPtr pattern, Extend extend); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pattern_set_filter (IntPtr pattern, Filter filter); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pattern_set_matrix (IntPtr pattern, Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_pattern_status (IntPtr pattern); // PdfSurface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pdf_surface_create (string filename, double width, double height); //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern IntPtr cairo_pdf_surface_create_for_stream (string filename, double width, double height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pdf_surface_set_size (IntPtr surface, double x, double y); // PostscriptSurface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_ps_surface_create (string filename, double width, double height); //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern IntPtr cairo_ps_surface_create_for_stream (string filename, double width, double height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_ps_surface_dsc_begin_page_setup (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_ps_surface_dsc_begin_setup (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_ps_surface_dsc_comment (IntPtr surface, string comment); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_ps_surface_set_size (IntPtr surface, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_pop_group (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_pop_group_to_source (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_push_group (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_push_group_with_content (IntPtr cr, Content content); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_quartz_surface_create (IntPtr context, bool flipped, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_rectangle (IntPtr cr, double x, double y, double width, double height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_reference (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern bool cairo_region_contains_point (IntPtr region, int x, int y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern RegionOverlap cairo_region_contains_rectangle (IntPtr region, ref RectangleInt rectangle); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_region_copy (IntPtr original); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_region_create (); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_region_create_rectangle (ref RectangleInt rect); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_region_create_rectangles (RectangleInt[] rects, int count); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_region_destroy (IntPtr region); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern bool cairo_region_equal (IntPtr a, IntPtr b); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_region_get_extents (IntPtr region, out RectangleInt extents); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_region_get_rectangle (IntPtr region, int nth, out RectangleInt rectangle); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_intersect (IntPtr dst, IntPtr other); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_intersect_rectangle (IntPtr dst, ref RectangleInt rectangle); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern bool cairo_region_is_empty (IntPtr region); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_region_num_rectangles (IntPtr region); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_region_reference (IntPtr region); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_status (IntPtr region); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_subtract (IntPtr dst, IntPtr other); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_subtract_rectangle (IntPtr dst, ref RectangleInt rectangle); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_region_translate (IntPtr region, int dx, int dy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_union (IntPtr dst, IntPtr other); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_union_rectangle (IntPtr dst, ref RectangleInt rectangle); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_xor (IntPtr dst, IntPtr other); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_region_xor_rectangle (IntPtr dst, ref RectangleInt rectangle); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_rel_curve_to (IntPtr cr, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_rel_line_to (IntPtr cr, double dx, double dy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_rel_move_to (IntPtr cr, double dx, double dy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_reset_clip (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_restore (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_rotate (IntPtr cr, double angle); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_save (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_scale (IntPtr cr, double sx, double sy); // ScaledFont [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_scaled_font_create (IntPtr fontFace, Matrix matrix, Matrix ctm, IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_scaled_font_destroy (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_scaled_font_extents (IntPtr scaled_font, out FontExtents extents); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_scaled_font_get_ctm (IntPtr scaled_font, out Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_scaled_font_get_font_face (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_scaled_font_get_font_matrix (IntPtr scaled_font, out Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_scaled_font_get_font_options (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern FontType cairo_scaled_font_get_type (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_scaled_font_glyph_extents (IntPtr scaled_font, IntPtr glyphs, int num_glyphs, out TextExtents extents); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_scaled_font_reference (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_scaled_font_status (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_scaled_font (IntPtr cr, IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_get_scaled_font (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_scaled_font_text_extents (IntPtr scaled_font, byte[] utf8, out TextExtents extents); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_select_font_face (IntPtr cr, string family, FontSlant slant, FontWeight weight); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_antialias (IntPtr cr, Antialias antialias); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_dash (IntPtr cr, double [] dashes, int ndash, double offset); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_get_dash (IntPtr cr, IntPtr dashes, out double offset); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_get_dash_count (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_fill_rule (IntPtr cr, Ztk.Drawing.FillRule fill_rule); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_font_face (IntPtr cr, IntPtr fontFace); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_font_matrix (IntPtr cr, Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_font_options (IntPtr cr, IntPtr options); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_font_size (IntPtr cr, double size); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_line_cap (IntPtr cr, LineCap line_cap); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_line_join (IntPtr cr, LineJoin line_join); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_line_width (IntPtr cr, double width); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_matrix (IntPtr cr, Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_miter_limit (IntPtr cr, double limit); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_operator (IntPtr cr, Ztk.Drawing.Operator op); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_source (IntPtr cr, IntPtr pattern); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_source_rgb (IntPtr cr, double red, double green, double blue); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_source_rgba (IntPtr cr, double red, double green, double blue, double alpha); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_source_surface (IntPtr cr, IntPtr surface, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_set_tolerance (IntPtr cr, double tolerance); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_show_glyphs (IntPtr ct, IntPtr glyphs, int num_glyphs); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_show_page (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_show_text (IntPtr cr, byte[] utf8); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_status (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_status_to_string (Status status); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_stroke (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_stroke_extents (IntPtr cr, out double x1, out double y1, out double x2, out double y2); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_stroke_preserve (IntPtr cr); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_rectangle_list_destroy (IntPtr rectangle_list); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_copy_clip_rectangle_list (IntPtr cr); // Surface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_surface_create_similar (IntPtr surface, Ztk.Drawing.Content content, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_destroy (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_finish (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_flush (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Content cairo_surface_get_content (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_get_device_offset (IntPtr surface, out double x, out double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_get_font_options (IntPtr surface, IntPtr FontOptions); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern uint cairo_surface_get_reference_count (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern SurfaceType cairo_surface_get_type (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_mark_dirty (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_mark_dirty_rectangle (IntPtr surface, int x, int y, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_surface_reference (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_set_device_offset (IntPtr surface, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_set_fallback_resolution (IntPtr surface, double x, double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_surface_status (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_surface_write_to_png (IntPtr surface, string filename); //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern void cairo_surface_write_to_png_stream (IntPtr surface, WriteFunc writeFunc); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_svg_surface_create (string fileName, double width, double height); //[DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] //internal static extern IntPtr cairo_svg_surface_create_for_stream (double width, double height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_svg_surface_restrict_to_version (IntPtr surface, SvgVersion version); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_text_extents (IntPtr cr, byte[] utf8, out TextExtents extents); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_text_path (IntPtr ct, byte[] utf8); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_transform (IntPtr cr, Matrix matrix); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_translate (IntPtr cr, double tx, double ty); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_user_to_device (IntPtr cr, ref double x, ref double y); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_user_to_device_distance (IntPtr cr, ref double dx, ref double dy); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_version (); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_version_string (); // DirectFBSurface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_directfb_surface_create (IntPtr dfb, IntPtr surface); // win32 fonts [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_win32_font_face_create_for_logfontw (IntPtr logfontw); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_win32_scaled_font_done_font (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern double cairo_win32_scaled_font_get_metrics_factor (IntPtr scaled_font); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern Status cairo_win32_scaled_font_select_font (IntPtr scaled_font, IntPtr hdc); // win32 surface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_win32_surface_create (IntPtr hdc); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_win32_surface_create_with_ddb (IntPtr hdc, Format format, int width, int height); // XcbSurface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xcb_surface_create (IntPtr connection, uint drawable, IntPtr visual, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xcb_surface_create_for_bitmap (IntPtr connection, uint bitmap, IntPtr screen, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_xcb_surface_set_size (IntPtr surface, int width, int height); // XlibSurface [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xlib_surface_create (IntPtr display, IntPtr drawable, IntPtr visual, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xlib_surface_create_for_bitmap (IntPtr display, IntPtr bitmap, IntPtr screen, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_xlib_surface_get_depth (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xlib_surface_get_display (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xlib_surface_get_drawable (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_xlib_surface_get_height (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xlib_surface_get_screen (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr cairo_xlib_surface_get_visual (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern int cairo_xlib_surface_get_width (IntPtr surface); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_xlib_surface_set_drawable (IntPtr surface, IntPtr drawable, int width, int height); [DllImport (cairo, CallingConvention=CallingConvention.Cdecl)] internal static extern void cairo_xlib_surface_set_size (IntPtr surface, int width, int height); } }
// Copyright 2011 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.Data.OData { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; #if ODATALIB_ASYNC using System.Threading.Tasks; #endif #endregion Namespaces /// <summary> /// Class for reading OData batch messages; also verifies the proper sequence of read calls on the reader. /// </summary> public sealed class ODataBatchReader : IODataBatchOperationListener { /// <summary>The input context to read the content from.</summary> private readonly ODataRawInputContext inputContext; /// <summary>The batch stream used by the batch reader to devide a batch payload into parts.</summary> private readonly ODataBatchReaderStream batchStream; /// <summary>True if the writer was created for synchronous operation; false for asynchronous.</summary> private readonly bool synchronous; /// <summary>The batch-specific URL resolver that stores the content IDs found in a changeset and supports resolving cross-referencing URLs.</summary> private readonly ODataBatchUrlResolver urlResolver; /// <summary>The current state of the batch reader.</summary> private ODataBatchReaderState batchReaderState; /// <summary>The current size of the batch message, i.e., how many query operations and changesets have been read.</summary> private uint currentBatchSize; /// <summary>The current size of the active changeset, i.e., how many operations have been read for the changeset.</summary> private uint currentChangeSetSize; /// <summary>An enumeration tracking the state of the current batch operation.</summary> private OperationState operationState; /// <summary>The value of the content ID header of the current part.</summary> /// <remarks> /// The content ID header of the current part should only be visible to subsequent parts /// so we can only add it to the URL resolver once we are done with the current part. /// </remarks> private string contentIdToAddOnNextRead; /// <summary> /// Constructor. /// </summary> /// <param name="inputContext">The input context to read the content from.</param> /// <param name="batchBoundary">The boundary string for the batch structure itself.</param> /// <param name="batchEncoding">The encoding to use to read from the batch stream.</param> /// <param name="synchronous">true if the reader is created for synchronous operation; false for asynchronous.</param> internal ODataBatchReader(ODataRawInputContext inputContext, string batchBoundary, Encoding batchEncoding, bool synchronous) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(inputContext != null, "inputContext != null"); Debug.Assert(!string.IsNullOrEmpty(batchBoundary), "!string.IsNullOrEmpty(batchBoundary)"); this.inputContext = inputContext; this.synchronous = synchronous; this.urlResolver = new ODataBatchUrlResolver(inputContext.UrlResolver); this.batchStream = new ODataBatchReaderStream(inputContext, batchBoundary, batchEncoding); } /// <summary> /// An enumeration to track the state of a batch operation. /// </summary> private enum OperationState { /// <summary>No action has been performed on the operation.</summary> None, /// <summary>The batch message for the operation has been created and returned to the caller.</summary> MessageCreated, /// <summary>The stream of the batch operation message has been requested.</summary> StreamRequested, /// <summary>The stream of the batch operation message has been disposed.</summary> StreamDisposed, } /// <summary> /// The current state of the batch reader. /// </summary> public ODataBatchReaderState State { get { this.inputContext.VerifyNotDisposed(); return this.batchReaderState; } private set { this.batchReaderState = value; } } /// <summary> /// Reads the next part from the batch message payload. /// </summary> /// <returns>true if more items were read; otherwise false.</returns> public bool Read() { this.VerifyCanRead(true); return this.InterceptException((Func<bool>)this.ReadSynchronously); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously reads the next part from the batch message payload. /// </summary> /// <returns>A task that when completed indicates whether more items were read.</returns> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] public Task<bool> ReadAsync() { this.VerifyCanRead(false); return this.ReadAsynchronously().FollowOnFaultWith(t => this.State = ODataBatchReaderState.Exception); } #endif /// <summary> /// Returns an <see cref="ODataBatchOperationRequestMessage"/> for reading the content of a batch operation. /// </summary> /// <returns>A request message for reading the content of a batch operation.</returns> public ODataBatchOperationRequestMessage CreateOperationRequestMessage() { this.VerifyCanCreateOperationRequestMessage(/*synchronousCall*/ true); return this.InterceptException((Func<ODataBatchOperationRequestMessage>)this.CreateOperationRequestMessageImplementation); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously returns an <see cref="ODataBatchOperationRequestMessage"/> for reading the content of a batch operation. /// </summary> /// <returns>A task that when completed returns a request message for reading the content of a batch operation.</returns> public Task<ODataBatchOperationRequestMessage> CreateOperationRequestMessageAsync() { this.VerifyCanCreateOperationRequestMessage(/*synchronousCall*/ false); return TaskUtils.GetTaskForSynchronousOperation<ODataBatchOperationRequestMessage>( this.CreateOperationRequestMessageImplementation) .FollowOnFaultWith(t => this.State = ODataBatchReaderState.Exception); } #endif /// <summary> /// Returns an <see cref="ODataBatchOperationResponseMessage"/> for reading the content of a batch operation. /// </summary> /// <returns>A response message for reading the content of a batch operation.</returns> public ODataBatchOperationResponseMessage CreateOperationResponseMessage() { this.VerifyCanCreateOperationResponseMessage(/*synchronousCall*/ true); return this.InterceptException((Func<ODataBatchOperationResponseMessage>)this.CreateOperationResponseMessageImplementation); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously returns an <see cref="ODataBatchOperationResponseMessage"/> for reading the content of a batch operation. /// </summary> /// <returns>A task that when completed returns a response message for reading the content of a batch operation.</returns> public Task<ODataBatchOperationResponseMessage> CreateOperationResponseMessageAsync() { this.VerifyCanCreateOperationResponseMessage(/*synchronousCall*/ false); return TaskUtils.GetTaskForSynchronousOperation<ODataBatchOperationResponseMessage>( this.CreateOperationResponseMessageImplementation) .FollowOnFaultWith(t => this.State = ODataBatchReaderState.Exception); } #endif /// <summary> /// This method is called to notify that the content stream for a batch operation has been requested. /// </summary> void IODataBatchOperationListener.BatchOperationContentStreamRequested() { this.operationState = OperationState.StreamRequested; } #if ODATALIB_ASYNC /// <summary> /// This method is called to notify that the content stream for a batch operation has been requested. /// </summary> /// <returns> /// A task representing any action that is running as part of the status change of the reader; /// null if no such action exists. /// </returns> Task IODataBatchOperationListener.BatchOperationContentStreamRequestedAsync() { this.operationState = OperationState.StreamRequested; return TaskUtils.CompletedTask; } #endif /// <summary> /// This method is called to notify that the content stream of a batch operation has been disposed. /// </summary> void IODataBatchOperationListener.BatchOperationContentStreamDisposed() { this.operationState = OperationState.StreamDisposed; } /// <summary> /// Returns the next state of the batch reader after an end boundary has been found. /// </summary> /// <returns>The next state of the batch reader.</returns> private ODataBatchReaderState GetEndBoundaryState() { switch (this.batchReaderState) { case ODataBatchReaderState.Initial: // If we find an end boundary when in state 'Initial' it means that we // have an empty batch. The next state will be 'Completed'. return ODataBatchReaderState.Completed; case ODataBatchReaderState.Operation: // If we find an end boundary in state 'Operation' we have finished // processing an operation and found the end boundary of either the // current changeset or the batch. return this.batchStream.ChangeSetBoundary == null ? ODataBatchReaderState.Completed : ODataBatchReaderState.ChangesetEnd; case ODataBatchReaderState.ChangesetStart: // If we find an end boundary when in state 'ChangeSetStart' it means that // we have an empty changeset. The next state will be 'ChangeSetEnd' return ODataBatchReaderState.ChangesetEnd; case ODataBatchReaderState.ChangesetEnd: // If we are at the end of a changeset and find an end boundary // we reached the end of the batch return ODataBatchReaderState.Completed; case ODataBatchReaderState.Completed: // We should never get here when in Completed state. throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReader_GetEndBoundary_Completed)); case ODataBatchReaderState.Exception: // We should never get here when in Exception state. throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReader_GetEndBoundary_Exception)); default: // Invalid enum value throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReader_GetEndBoundary_UnknownValue)); } } /// <summary> /// Reads the next part from the batch message payload. /// </summary> /// <returns>true if more information was read; otherwise false.</returns> private bool ReadSynchronously() { return this.ReadImplementation(); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously reads the next part from the batch message payload. /// </summary> /// <returns>A task that when completed indicates whether more information was read.</returns> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] private Task<bool> ReadAsynchronously() { // We are reading from the fully buffered read stream here; thus it is ok // to use synchronous reads and then return a completed task // NOTE: once we switch to fully async reading this will have to change return TaskUtils.GetTaskForSynchronousOperation<bool>(this.ReadImplementation); } #endif /// <summary> /// Continues reading from the batch message payload. /// </summary> /// <returns>true if more items were read; otherwise false.</returns> private bool ReadImplementation() { Debug.Assert(this.operationState != OperationState.StreamRequested, "Should have verified that no operation stream is still active."); switch (this.State) { case ODataBatchReaderState.Initial: // The stream should be positioned at the beginning of the batch content, // that is before the first boundary (or the preamble if there is one). this.batchReaderState = this.SkipToNextPartAndReadHeaders(); break; case ODataBatchReaderState.Operation: // When reaching this state we already read the MIME headers of the operation. // Clients MUST call CreateOperationRequestMessage // or CreateOperationResponseMessage to read at least the headers of the operation. // This is important since we need to read the ContentId header (if present) and // add it to the URL resolver. if (this.operationState == OperationState.None) { // No message was created; fail throw new ODataException(Strings.ODataBatchReader_NoMessageWasCreatedForOperation); } // Reset the operation state; the operation state only // tracks the state of a batch operation while in state Operation. this.operationState = OperationState.None; // Also add a pending ContentId header to the URL resolver now. We ensured above // that a message has been created for this operation and thus the headers (incl. // a potential content ID header) have been read. if (this.contentIdToAddOnNextRead != null) { this.urlResolver.AddContentId(this.contentIdToAddOnNextRead); this.contentIdToAddOnNextRead = null; } // When we are done with an operation, we have to skip ahead to the next part // when Read is called again. Note that if the operation stream was never requested // and the content of the operation has not been read, we'll skip it here. Debug.Assert(this.operationState == OperationState.None, "Operation state must be 'None' at the end of the operation."); this.batchReaderState = this.SkipToNextPartAndReadHeaders(); break; case ODataBatchReaderState.ChangesetStart: // When at the start of a changeset, skip ahead to the first operation in the // changeset (or the end boundary of the changeset). Debug.Assert(this.batchStream.ChangeSetBoundary != null, "Changeset boundary must have been set by now."); this.batchReaderState = this.SkipToNextPartAndReadHeaders(); break; case ODataBatchReaderState.ChangesetEnd: // When at the end of a changeset, reset the changeset boundary and the // changeset size and then skip to the next part. this.ResetChangeSetSize(); this.batchStream.ResetChangeSetBoundary(); this.batchReaderState = this.SkipToNextPartAndReadHeaders(); break; case ODataBatchReaderState.Exception: // fall through case ODataBatchReaderState.Completed: Debug.Assert(false, "Should have checked in VerifyCanRead that we are not in one of these states."); throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReader_ReadImplementation)); default: Debug.Assert(false, "Unsupported reader state " + this.State + " detected."); throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataBatchReader_ReadImplementation)); } return this.batchReaderState != ODataBatchReaderState.Completed && this.batchReaderState != ODataBatchReaderState.Exception; } /// <summary> /// Skips all data in the stream until the next part is detected; then reads the part's request/response line and headers. /// </summary> /// <returns>The next state of the batch reader after skipping to the next part and reading the part's beginning.</returns> private ODataBatchReaderState SkipToNextPartAndReadHeaders() { bool isEndBoundary, isParentBoundary; bool foundBoundary = this.batchStream.SkipToBoundary(out isEndBoundary, out isParentBoundary); if (!foundBoundary) { // We did not find the expected boundary at all in the payload; // we are done reading. Depending on where we are report changeset end or completed state if (this.batchStream.ChangeSetBoundary == null) { return ODataBatchReaderState.Completed; } else { return ODataBatchReaderState.ChangesetEnd; } } ODataBatchReaderState nextState; if (isEndBoundary || isParentBoundary) { // We detected an end boundary or detected that the end boundary is missing // because we found a parent boundary nextState = this.GetEndBoundaryState(); if (nextState == ODataBatchReaderState.ChangesetEnd) { // Reset the URL resolver at the end of a changeset; Content IDs are // unique within a given changeset. this.urlResolver.Reset(); } } else { bool currentlyInChangeSet = this.batchStream.ChangeSetBoundary != null; // If we did not find an end boundary, we found another part bool isChangeSetPart = this.batchStream.ProcessPartHeader(); // Compute the next reader state if (currentlyInChangeSet) { Debug.Assert(!isChangeSetPart, "Should have validated that nested changesets are not allowed."); nextState = ODataBatchReaderState.Operation; this.IncreaseChangeSetSize(); } else { // We are at the top level (not inside a changeset) nextState = isChangeSetPart ? ODataBatchReaderState.ChangesetStart : ODataBatchReaderState.Operation; this.IncreaseBatchSize(); } } return nextState; } /// <summary> /// Returns the cached <see cref="ODataBatchOperationRequestMessage"/> for reading the content of an operation /// in a batch request. /// </summary> /// <returns>The message that can be used to read the content of the batch request operation from.</returns> private ODataBatchOperationRequestMessage CreateOperationRequestMessageImplementation() { this.operationState = OperationState.MessageCreated; // Read and parse the request line (skip all empty lines) string requestLine = this.batchStream.ReadLine(); while (requestLine.Length == 0) { requestLine = this.batchStream.ReadLine(); } string httpMethod; Uri requestUri; this.ParseRequestLine(requestLine, out httpMethod, out requestUri); // Read all headers and create the request message ODataBatchOperationHeaders headers = this.batchStream.ReadHeaders(); ODataBatchOperationRequestMessage requestMessage = ODataBatchOperationRequestMessage.CreateReadMessage( this.batchStream, httpMethod, requestUri, headers, /*operationListener*/ this, this.urlResolver); // Add a potential Content-ID header to the URL resolver so that it will be available // to subsequent operations. string contentId; if (headers.TryGetValue(ODataConstants.ContentIdHeader, out contentId)) { Debug.Assert(this.contentIdToAddOnNextRead == null, "Must not have a content ID to be added to a part."); if (contentId != null && this.urlResolver.ContainsContentId(contentId)) { throw new ODataException(Strings.ODataBatchReader_DuplicateContentIDsNotAllowed(contentId)); } this.contentIdToAddOnNextRead = contentId; } return requestMessage; } /// <summary> /// Returns the cached <see cref="ODataBatchOperationRequestMessage"/> for reading the content of an operation /// in a batch request. /// </summary> /// <returns>The message that can be used to read the content of the batch request operation from.</returns> private ODataBatchOperationResponseMessage CreateOperationResponseMessageImplementation() { this.operationState = OperationState.MessageCreated; // Read and parse the response line (skip all empty lines) string responseLine = this.batchStream.ReadLine(); while (responseLine.Length == 0) { responseLine = this.batchStream.ReadLine(); } int statusCode = this.ParseResponseLine(responseLine); // Read all headers and create the response message ODataBatchOperationHeaders headers = this.batchStream.ReadHeaders(); // In responses we don't need to use our batch URL resolver, since there are no cross referencing URLs // so use the URL resolver from the batch message instead. ODataBatchOperationResponseMessage responseMessage = ODataBatchOperationResponseMessage.CreateReadMessage( this.batchStream, statusCode, headers, /*operationListener*/ this, this.urlResolver.BatchMessageUrlResolver); //// NOTE: Content-IDs for cross referencing are only supported in request messages; in responses //// we allow a Content-ID header but don't process it (i.e., don't add the content ID to the URL resolver). return responseMessage; } /// <summary> /// Parses the request line of a batch operation request. /// </summary> /// <param name="requestLine">The request line as a string.</param> /// <param name="httpMethod">The parsed HTTP method of the request.</param> /// <param name="requestUri">The parsed <see cref="Uri"/> of the request.</param> private void ParseRequestLine(string requestLine, out string httpMethod, out Uri requestUri) { Debug.Assert(!this.inputContext.ReadingResponse, "Must only be called for requests."); // Batch Request: POST /Customers HTTP/1.1 // Since the uri can contain spaces, the only way to read the request url, is to // check for first space character and last space character and anything between // them. int firstSpaceIndex = requestLine.IndexOf(' '); // Check whether there are enough characters after the first space for the 2nd and 3rd segments // (and a whitespace in between) if (firstSpaceIndex <= 0 || requestLine.Length - 3 <= firstSpaceIndex) { // only 1 segment or empty first segment or not enough left for 2nd and 3rd segments throw new ODataException(Strings.ODataBatchReaderStream_InvalidRequestLine(requestLine)); } int lastSpaceIndex = requestLine.LastIndexOf(' '); if (lastSpaceIndex < 0 || lastSpaceIndex - firstSpaceIndex - 1 <= 0 || requestLine.Length - 1 <= lastSpaceIndex) { // only 2 segments or empty 2nd or 3rd segments // only 1 segment or empty first segment or not enough left for 2nd and 3rd segments throw new ODataException(Strings.ODataBatchReaderStream_InvalidRequestLine(requestLine)); } httpMethod = requestLine.Substring(0, firstSpaceIndex); // Request - Http method string uriSegment = requestLine.Substring(firstSpaceIndex + 1, lastSpaceIndex - firstSpaceIndex - 1); // Request - Request uri string httpVersionSegment = requestLine.Substring(lastSpaceIndex + 1); // Request - Http version // Validate HttpVersion if (string.CompareOrdinal(ODataConstants.HttpVersionInBatching, httpVersionSegment) != 0) { throw new ODataException(Strings.ODataBatchReaderStream_InvalidHttpVersionSpecified(httpVersionSegment, ODataConstants.HttpVersionInBatching)); } // NOTE: this method will throw if the method is not recognized. HttpUtils.ValidateHttpMethod(httpMethod); // Validate the HTTP method when reading a request if (this.batchStream.ChangeSetBoundary == null) { // only allow GET requests for query operations if (string.CompareOrdinal(httpMethod, ODataConstants.MethodGet) != 0) { throw new ODataException(Strings.ODataBatch_InvalidHttpMethodForQueryOperation(httpMethod)); } } else { // allow all methods except for GET if (string.CompareOrdinal(httpMethod, ODataConstants.MethodGet) == 0) { throw new ODataException(Strings.ODataBatch_InvalidHttpMethodForChangeSetRequest(httpMethod)); } } requestUri = new Uri(uriSegment, UriKind.RelativeOrAbsolute); requestUri = ODataBatchUtils.CreateOperationRequestUri(requestUri, this.inputContext.MessageReaderSettings.BaseUri, this.urlResolver); } /// <summary> /// Parses the response line of a batch operation response. /// </summary> /// <param name="responseLine">The response line as a string.</param> /// <returns>The parsed status code from the response line.</returns> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "'this' is used when built in debug")] private int ParseResponseLine(string responseLine) { Debug.Assert(this.inputContext.ReadingResponse, "Must only be called for responses."); // Batch Response: HTTP/1.1 200 Ok // Since the http status code strings have spaces in them, we cannot use the same // logic. We need to check for the second space and anything after that is the error // message. int firstSpaceIndex = responseLine.IndexOf(' '); if (firstSpaceIndex <= 0 || responseLine.Length - 3 <= firstSpaceIndex) { // only 1 segment or empty first segment or not enough left for 2nd and 3rd segments throw new ODataException(Strings.ODataBatchReaderStream_InvalidResponseLine(responseLine)); } int secondSpaceIndex = responseLine.IndexOf(' ', firstSpaceIndex + 1); if (secondSpaceIndex < 0 || secondSpaceIndex - firstSpaceIndex - 1 <= 0 || responseLine.Length - 1 <= secondSpaceIndex) { // only 2 segments or empty 2nd or 3rd segments // only 1 segment or empty first segment or not enough left for 2nd and 3rd segments throw new ODataException(Strings.ODataBatchReaderStream_InvalidResponseLine(responseLine)); } string httpVersionSegment = responseLine.Substring(0, firstSpaceIndex); string statusCodeSegment = responseLine.Substring(firstSpaceIndex + 1, secondSpaceIndex - firstSpaceIndex - 1); // Validate HttpVersion if (string.CompareOrdinal(ODataConstants.HttpVersionInBatching, httpVersionSegment) != 0) { throw new ODataException(Strings.ODataBatchReaderStream_InvalidHttpVersionSpecified(httpVersionSegment, ODataConstants.HttpVersionInBatching)); } int intResult; if (!Int32.TryParse(statusCodeSegment, out intResult)) { throw new ODataException(Strings.ODataBatchReaderStream_NonIntegerHttpStatusCode(statusCodeSegment)); } return intResult; } /// <summary> /// Verifies that calling CreateOperationRequestMessage if valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanCreateOperationRequestMessage(bool synchronousCall) { this.VerifyReaderReady(); this.VerifyCallAllowed(synchronousCall); if (this.inputContext.ReadingResponse) { this.ThrowODataException(Strings.ODataBatchReader_CannotCreateRequestOperationWhenReadingResponse); } if (this.State != ODataBatchReaderState.Operation) { this.ThrowODataException(Strings.ODataBatchReader_InvalidStateForCreateOperationRequestMessage(this.State)); } if (this.operationState != OperationState.None) { this.ThrowODataException(Strings.ODataBatchReader_OperationRequestMessageAlreadyCreated); } } /// <summary> /// Verifies that calling CreateOperationResponseMessage if valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanCreateOperationResponseMessage(bool synchronousCall) { this.VerifyReaderReady(); this.VerifyCallAllowed(synchronousCall); if (!this.inputContext.ReadingResponse) { this.ThrowODataException(Strings.ODataBatchReader_CannotCreateResponseOperationWhenReadingRequest); } if (this.State != ODataBatchReaderState.Operation) { this.ThrowODataException(Strings.ODataBatchReader_InvalidStateForCreateOperationResponseMessage(this.State)); } if (this.operationState != OperationState.None) { this.ThrowODataException(Strings.ODataBatchReader_OperationResponseMessageAlreadyCreated); } } /// <summary> /// Verifies that calling Read is valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanRead(bool synchronousCall) { this.VerifyReaderReady(); this.VerifyCallAllowed(synchronousCall); if (this.State == ODataBatchReaderState.Exception || this.State == ODataBatchReaderState.Completed) { throw new ODataException(Strings.ODataBatchReader_ReadOrReadAsyncCalledInInvalidState(this.State)); } } /// <summary> /// Validates that the batch reader is ready to process a new read or create message request. /// </summary> private void VerifyReaderReady() { this.inputContext.VerifyNotDisposed(); // If the operation stream was requested but not yet disposed, the batch reader can't be used to do anything. if (this.operationState == OperationState.StreamRequested) { throw new ODataException(Strings.ODataBatchReader_CannotUseReaderWhileOperationStreamActive); } } /// <summary> /// Verifies that a call is allowed to the reader. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCallAllowed(bool synchronousCall) { if (synchronousCall) { if (!this.synchronous) { throw new ODataException(Strings.ODataBatchReader_SyncCallOnAsyncReader); } } else { #if ODATALIB_ASYNC if (this.synchronous) { throw new ODataException(Strings.ODataBatchReader_AsyncCallOnSyncReader); } #else Debug.Assert(false, "Async calls are not allowed in this build."); #endif } } /// <summary> /// Increases the size of the current batch message; throws if the allowed limit is exceeded. /// </summary> private void IncreaseBatchSize() { this.currentBatchSize++; if (this.currentBatchSize > this.inputContext.MessageReaderSettings.MessageQuotas.MaxPartsPerBatch) { throw new ODataException(Strings.ODataBatchReader_MaxBatchSizeExceeded(this.inputContext.MessageReaderSettings.MessageQuotas.MaxPartsPerBatch)); } } /// <summary> /// Increases the size of the current change set; throws if the allowed limit is exceeded. /// </summary> private void IncreaseChangeSetSize() { this.currentChangeSetSize++; if (this.currentChangeSetSize > this.inputContext.MessageReaderSettings.MessageQuotas.MaxOperationsPerChangeset) { throw new ODataException(Strings.ODataBatchReader_MaxChangeSetSizeExceeded(this.inputContext.MessageReaderSettings.MessageQuotas.MaxOperationsPerChangeset)); } } /// <summary> /// Resets the size of the current change set to 0. /// </summary> private void ResetChangeSetSize() { this.currentChangeSetSize = 0; } /// <summary> /// Sets the 'Exception' state and then throws an ODataException with the specified error message. /// </summary> /// <param name="errorMessage">The error message for the exception.</param> private void ThrowODataException(string errorMessage) { this.State = ODataBatchReaderState.Exception; throw new ODataException(errorMessage); } /// <summary> /// Catch any exception thrown by the action passed in; in the exception case move the writer into /// state Exception and then rethrow the exception. /// </summary> /// <typeparam name="T">The type of the result returned from the <paramref name="action"/>.</typeparam> /// <param name="action">The action to execute.</param> /// <returns>The result of the <paramref name="action"/>.</returns> private T InterceptException<T>(Func<T> action) { try { return action(); } catch (Exception e) { if (ExceptionUtils.IsCatchableExceptionType(e)) { this.State = ODataBatchReaderState.Exception; } throw; } } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.Project { public class OleServiceProvider : IOleServiceProvider, IDisposable { #region Public Types [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public delegate object ServiceCreatorCallback(Type serviceType); #endregion #region Private Types private class ServiceData : IDisposable { private Type serviceType; private object instance; private ServiceCreatorCallback creator; private bool shouldDispose; public ServiceData(Type serviceType, object instance, ServiceCreatorCallback callback, bool shouldDispose) { if(null == serviceType) { throw new ArgumentNullException("serviceType"); } if((null == instance) && (null == callback)) { throw new ArgumentNullException("instance"); } this.serviceType = serviceType; this.instance = instance; this.creator = callback; this.shouldDispose = shouldDispose; } public object ServiceInstance { get { if(null == instance) { instance = creator(serviceType); } return instance; } } public Guid Guid { get { return serviceType.GUID; } } public void Dispose() { if((shouldDispose) && (null != instance)) { IDisposable disp = instance as IDisposable; if(null != disp) { disp.Dispose(); } instance = null; } creator = null; GC.SuppressFinalize(this); } } #endregion #region fields private Dictionary<Guid, ServiceData> services = new Dictionary<Guid, ServiceData>(); private bool isDisposed; /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); #endregion #region ctors public OleServiceProvider() { } #endregion #region IOleServiceProvider Members public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) { ppvObject = (IntPtr)0; int hr = VSConstants.S_OK; ServiceData serviceInstance = null; if(services != null && services.ContainsKey(guidService)) { serviceInstance = services[guidService]; } if(serviceInstance == null) { return VSConstants.E_NOINTERFACE; } // Now check to see if the user asked for an IID other than // IUnknown. If so, we must do another QI. // if(riid.Equals(NativeMethods.IID_IUnknown)) { ppvObject = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); } else { IntPtr pUnk = IntPtr.Zero; try { pUnk = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); hr = Marshal.QueryInterface(pUnk, ref riid, out ppvObject); } finally { if(pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } } return hr; } #endregion #region Dispose /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Adds the given service to the service container. /// </summary> /// <param name="serviceType">The type of the service to add.</param> /// <param name="serviceInstance">An instance of the service.</param> /// <param name="shouldDisposeServiceInstance">true if the Dipose of the service provider is allowed to dispose the sevice instance.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, object serviceInstance, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, serviceInstance, null, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, ServiceCreatorCallback callback, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, null, callback, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } private void AddService(ServiceData data) { // Make sure that the collection of services is created. if(null == services) { services = new Dictionary<Guid, ServiceData>(); } // Disallow the addition of duplicate services. if(services.ContainsKey(data.Guid)) { throw new InvalidOperationException(); } services.Add(data.Guid, data); } /// <devdoc> /// Removes the given service type from the service container. /// </devdoc> public void RemoveService(Type serviceType) { if(serviceType == null) { throw new ArgumentNullException("serviceType"); } if(services.ContainsKey(serviceType.GUID)) { services.Remove(serviceType.GUID); } } #region helper methods /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { // Everybody can go here. if(!this.isDisposed) { // Synchronize calls to the Dispose simulteniously. lock(Mutex) { if(disposing) { // Remove all our services if(services != null) { foreach(ServiceData data in services.Values) { data.Dispose(); } services.Clear(); services = null; } } this.isDisposed = true; } } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler { public class WorkCoordinatorTests { private const string SolutionCrawler = "SolutionCrawler"; [Fact] public void RegisterService() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var registrationService = new SolutionCrawlerRegistrationService( SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(), AggregateAsynchronousOperationListener.EmptyListeners); // register and unregister workspace to the service registrationService.Register(workspace); registrationService.Unregister(workspace); } } [Fact, WorkItem(747226)] public void SolutionAdded_Simple() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public void SolutionAdded_Complex() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solution)); Assert.Equal(10, worker.SyntaxDocumentIds.Count); } } [Fact] public void Solution_Remove() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var worker = ExecuteOperation(workspace, w => w.OnSolutionRemoved()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public void Solution_Clear() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var worker = ExecuteOperation(workspace, w => w.ClearSolution()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public void Solution_Reload() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var worker = ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public void Solution_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); WaitWaiter(workspace.ExportProvider); var solution = workspace.CurrentSolution; var documentId = solution.Projects.First().DocumentIds[0]; solution = solution.RemoveDocument(documentId); var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution; var worker = ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public void Project_Add() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List<DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } } [Fact] public void Project_Remove() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var projectid = workspace.CurrentSolution.ProjectIds[0]; var worker = ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.InvalidateDocumentIds.Count); } } [Fact] public void Project_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); WaitWaiter(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(); var documentId = project.DocumentIds[0]; var solution = workspace.CurrentSolution.RemoveDocument(documentId); var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public void Project_AssemblyName_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); WaitWaiter(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").WithAssemblyName("newName"); var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public void Project_AnalyzerOptions_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); WaitWaiter(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").AddAdditionalDocument("a1", SourceText.From("")).Project; var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public void Project_Reload() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var project = solution.Projects[0]; var worker = ExecuteOperation(workspace, w => w.OnProjectReloaded(project)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public void Document_Add() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var project = solution.Projects[0]; var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(6, worker.DocumentIds.Count); } } [Fact] public void Document_Remove() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = ExecuteOperation(workspace, w => w.OnDocumentRemoved(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public void Document_Reload() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = solution.Projects[0].Documents[0]; var worker = ExecuteOperation(workspace, w => w.OnDocumentReloaded(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public void Document_Reanalyze() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var info = solution.Projects[0].Documents[0]; var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. TouchEverything(workspace.CurrentSolution); service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id)); TouchEverything(workspace.CurrentSolution); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.DocumentIds.Count); } } [WorkItem(670335)] public void Document_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//"))); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public void Document_AdditionalFileChange() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var project = solution.Projects[0]; var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//"))); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WorkItem(670335)] public void Document_Cancellation() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335)] public void Document_Cancellation_MultipleTimes() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); analyzer.RunningEvent.Reset(); workspace.ChangeDocument(id, SourceText.From("// ")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335)] public void Document_InvocationReasons() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(blockedRun: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // first invocation will block worker workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); var openReady = new ManualResetEventSlim(initialState: false); var closeReady = new ManualResetEventSlim(initialState: false); workspace.DocumentOpened += (o, e) => openReady.Set(); workspace.DocumentClosed += (o, e) => closeReady.Set(); // cause several different request to queue up workspace.ChangeDocument(id, SourceText.From("// ")); workspace.OpenDocument(id); workspace.CloseDocument(id); openReady.Set(); closeReady.Set(); analyzer.BlockEvent.Set(); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [Fact] public void Document_TopLevelType_Whitespace() { var code = @"class C { $$ }"; var textToInsert = " "; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelType_Character() { var code = @"class C { $$ }"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelType_NewLine() { var code = @"class C { $$ }"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelType_NewLine2() { var code = @"class C { $$"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_EmptyFile() { var code = @"$$"; var textToInsert = "class"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevel1() { var code = @"class C { public void Test($$"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevel2() { var code = @"class C { public void Test(int $$"; var textToInsert = " "; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevel3() { var code = @"class C { public void Test(int i,$$"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_InteriorNode1() { var code = @"class C { public void Test() {$$"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode2() { var code = @"class C { public void Test() { $$ }"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode_Field() { var code = @"class C { int i = $$ }"; var textToInsert = "1"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode_Field1() { var code = @"class C { int i = 1 + $$ }"; var textToInsert = "1"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode_Accessor() { var code = @"class C { public int A { get { $$ } } }"; var textToInsert = "return"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_TopLevelWhitespace() { var code = @"class C { /// $$ public int A() { } }"; var textToInsert = "return"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelWhitespace2() { var code = @"/// $$ class C { public int A() { } }"; var textToInsert = "return"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_InteriorNode_Malformed() { var code = @"class C { public void Test() { $$"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void VBPropertyTest() { var markup = @"Class C Default Public Property G(x As Integer) As Integer Get $$ End Get Set(value As Integer) End Set End Property End Class"; int position; string code; MarkupTestFile.GetPosition(markup, out code, out position); var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code); var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>(); var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property); Assert.Equal(0, memberId); } [Fact, WorkItem(739943)] public void SemanticChange_Propagation() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); #if false Assert.True(1 == worker.SyntaxDocumentIds.Count, string.Format("Expected 1 SyntaxDocumentIds, Got {0}\n\n{1}", worker.SyntaxDocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); Assert.True(4 == worker.DocumentIds.Count, string.Format("Expected 4 DocumentIds, Got {0}\n\n{1}", worker.DocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); #endif } } [Fact] public void ProgressReporterTest() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { WaitWaiter(workspace.ExportProvider); var service = workspace.Services.GetService<ISolutionCrawlerService>(); var reporter = service.GetProgressReporter(workspace); Assert.False(reporter.InProgress); // set up events bool started = false; reporter.Started += (o, a) => { started = true; }; bool stopped = false; reporter.Stopped += (o, a) => { stopped = true; }; var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); // first mutation workspace.OnSolutionAdded(solution); Wait((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); // reset started = false; stopped = false; // second mutation workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6")); Wait((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); registrationService.Unregister(workspace); } } private void InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp) { using (var workspace = TestWorkspaceFactory.CreateWorkspaceFromLines( SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: new string[] { code })) { var analyzer = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); var testDocument = workspace.Documents.First(); var insertPosition = testDocument.CursorPosition; var textBuffer = testDocument.GetTextBuffer(); using (var edit = textBuffer.CreateEdit()) { edit.Insert(insertPosition.Value, text); edit.Apply(); } Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count); } } private Analyzer ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation) { var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. TouchEverything(workspace.CurrentSolution); operation(workspace); TouchEverything(workspace.CurrentSolution); Wait(service, workspace); service.Unregister(workspace); return worker; } private void TouchEverything(Solution solution) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { document.GetTextAsync().PumpingWait(); document.GetSyntaxRootAsync().PumpingWait(); document.GetSemanticModelAsync().PumpingWait(); } } } private void Wait(SolutionCrawlerRegistrationService service, TestWorkspace workspace) { WaitWaiter(workspace.ExportProvider); service.WaitUntilCompletion_ForTestingPurposesOnly(workspace); } private void WaitWaiter(ExportProvider provider) { var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; workspaceWaiter.CreateWaitTask().PumpingWait(); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; solutionCrawlerWaiter.CreateWaitTask().PumpingWait(); } private static SolutionInfo GetInitialSolutionInfoWithP2P() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); var projectId4 = ProjectId.CreateNewId(); var projectId5 = ProjectId.CreateNewId(); var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") }, projectReferences: new[] { new ProjectReference(projectId1) }), ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") }, projectReferences: new[] { new ProjectReference(projectId2) }), ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }), ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") }, projectReferences: new[] { new ProjectReference(projectId4) }), }); return solution; } private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace) { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5") }) }); } private IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider) { return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>(); } [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.SolutionCrawler)] private class SolutionCrawlerWaiter : AsynchronousOperationListener { } [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.Workspace)] private class WorkspaceWaiter : AsynchronousOperationListener { } private class AnalyzerProvider : IIncrementalAnalyzerProvider { private readonly Analyzer _analyzer; public AnalyzerProvider(Analyzer analyzer) { _analyzer = analyzer; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { return _analyzer; } } internal class Metadata : IncrementalAnalyzerProviderMetadata { public Metadata(params string[] workspaceKinds) : base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } }) { } public static readonly Metadata Crawler = new Metadata(SolutionCrawler); } private class Analyzer : IIncrementalAnalyzer { private readonly bool _waitForCancellation; private readonly bool _blockedRun; public readonly ManualResetEventSlim BlockEvent; public readonly ManualResetEventSlim RunningEvent; public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>(); public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>(); public Analyzer(bool waitForCancellation = false, bool blockedRun = false) { _waitForCancellation = waitForCancellation; _blockedRun = blockedRun; this.BlockEvent = new ManualResetEventSlim(initialState: false); this.RunningEvent = new ManualResetEventSlim(initialState: false); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { this.ProjectIds.Add(project.Id); return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { if (bodyOpt == null) { this.DocumentIds.Add(document.Id); } return SpecializedTasks.EmptyTask; } public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { this.SyntaxDocumentIds.Add(document.Id); Process(document.Id, cancellationToken); return SpecializedTasks.EmptyTask; } public void RemoveDocument(DocumentId documentId) { InvalidateDocumentIds.Add(documentId); } public void RemoveProject(ProjectId projectId) { InvalidateProjectIds.Add(projectId); } private void Process(DocumentId documentId, CancellationToken cancellationToken) { if (_blockedRun && !RunningEvent.IsSet) { this.RunningEvent.Set(); // Wait until unblocked this.BlockEvent.Wait(); } if (_waitForCancellation && !RunningEvent.IsSet) { this.RunningEvent.Set(); cancellationToken.WaitHandle.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); } } #region unused public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return false; } #endregion } #if false private string GetListenerTrace(ExportProvider provider) { var sb = new StringBuilder(); var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener; sb.AppendLine("workspace"); sb.AppendLine(workspaceWaiter.Trace()); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener; sb.AppendLine("solutionCrawler"); sb.AppendLine(solutionCrawlerWaiter.Trace()); return sb.ToString(); } internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter { private readonly object gate = new object(); private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>(); private readonly StringBuilder sb = new StringBuilder(); private int counter; public TestAsynchronousOperationListener() { } public IAsyncToken BeginAsyncOperation(string name, object tag = null) { lock (gate) { return new AsyncToken(this, name); } } private void Increment(string name) { lock (gate) { sb.AppendLine("i -> " + name + ":" + counter++); } } private void Decrement(string name) { lock (gate) { counter--; if (counter == 0) { foreach (var task in pendingTasks) { task.SetResult(true); } pendingTasks.Clear(); } sb.AppendLine("d -> " + name + ":" + counter); } } public virtual Task CreateWaitTask() { lock (gate) { var source = new TaskCompletionSource<bool>(); if (counter == 0) { // There is nothing to wait for, so we are immediately done source.SetResult(true); } else { pendingTasks.Add(source); } return source.Task; } } public bool TrackActiveTokens { get; set; } public bool HasPendingWork { get { return counter != 0; } } private class AsyncToken : IAsyncToken { private readonly TestAsynchronousOperationListener listener; private readonly string name; private bool disposed; public AsyncToken(TestAsynchronousOperationListener listener, string name) { this.listener = listener; this.name = name; listener.Increment(name); } public void Dispose() { lock (listener.gate) { if (disposed) { throw new InvalidOperationException("Double disposing of an async token"); } disposed = true; listener.Decrement(this.name); } } } public string Trace() { return sb.ToString(); } } #endif } }
using fyiReporting.RdlDesign.Resources; /* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <[email protected]> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.ComponentModel; // need this for the properties metadata using System.Drawing.Design; using System.Globalization; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Xml; namespace fyiReporting.RdlDesign { /// <summary> /// PropertyReportItem - The ReportItem Properties /// </summary> [DefaultProperty("Author")] internal class PropertyReport { private DesignXmlDraw _Draw; private DesignCtl _DesignCtl; internal PropertyReport(DesignXmlDraw d, DesignCtl dc) { _Draw = d; _DesignCtl = dc; } internal DesignXmlDraw Draw { get { return _Draw; } } internal DesignCtl DesignCtl { get { return _DesignCtl; } } XmlNode ReportNode { get { return _Draw.GetReportNode(); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_Author")] [LocalizedDescription("Report_Author")] public string Author { get {return GetReportValue("Author"); } set{SetReportValue("Author", value); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_Description")] [LocalizedDescription("Report_Description")] public string Description { get { return GetReportValue("Description"); } set { SetReportValue("Description", value); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_Width")] [LocalizedDescription("Report_Width")] public string Width { get { return GetReportValue("Width"); } set { DesignerUtility.ValidateSize(value, false, false); SetReportValue("Width", value); DesignCtl.SetScrollControls(); // this will force ruler and scroll bars to be updated } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_Parameters")] [LocalizedDescription("Report_Parameters")] public PropertyReportParameters Parameters { get { return new PropertyReportParameters(this); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_Code")] [LocalizedDescription("Report_Code")] public PropertyReportCode Code { get { return new PropertyReportCode(this); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_ModulesClasses")] [LocalizedDescription("Report_ModulesClasses")] public PropertyReportModulesClasses ModulesClasses { get { return new PropertyReportModulesClasses(this); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_PageWidth")] [LocalizedDescription("Report_PageWidth")] public string PageWidth { get { return GetReportValue("PageWidth"); } set { DesignerUtility.ValidateSize(value, false, false); SetReportValue("PageWidth", value); DesignCtl.SetScrollControls(); // this will force ruler and scroll bars to be updated } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_PageHeight")] [LocalizedDescription("Report_PageHeight")] public string PageHeight { get { return GetReportValue("PageHeight"); } set { DesignerUtility.ValidateSize(value, false, false); SetReportValue("PageHeight", value); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_Margins")] [LocalizedDescription("Report_Margins")] public PropertyMargin Margins { get { return new PropertyMargin(this); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_PageHeader")] [LocalizedDescription("Report_PageHeader")] public PropertyPrintFirstLast PageHeader { get { XmlNode phNode = _Draw.GetCreateNamedChildNode(ReportNode, "PageHeader"); return new PropertyPrintFirstLast(this, phNode); } } [LocalizedCategory("Report")] [LocalizedDisplayName("Report_PageFooter")] [LocalizedDescription("Report_PageFooter")] public PropertyPrintFirstLast PageFooter { get { XmlNode phNode = _Draw.GetCreateNamedChildNode(ReportNode, "PageFooter"); return new PropertyPrintFirstLast(this, phNode); } } [LocalizedCategory("Body")] [LocalizedDisplayName("Report_BodyHeight")] [LocalizedDescription("Report_BodyHeight")] public string BodyHeight { get { return GetBodyValue("Height", ""); } set { DesignerUtility.ValidateSize(value, true, false); SetBodyValue("Height", value); DesignCtl.SetScrollControls(); // this will force ruler and scroll bars to be updated } } [LocalizedCategory("Body")] [LocalizedDisplayName("Report_BodyColumns")] [LocalizedDescription("Report_BodyColumns")] public int BodyColumns { get { string c = GetBodyValue("Columns", "1"); try { return Convert.ToInt32(c); } catch { return 1; } } set { if (value < 1) throw new ArgumentException("The number of columns in the body must be greater than 0."); SetBodyValue("Columns", value.ToString()); } } [LocalizedCategory("Body")] [LocalizedDisplayName("Report_BodyColumnSpacing")] [LocalizedDescription("Report_BodyColumnSpacing")] public string BodyColumnSpacing { get { return GetBodyValue("ColumnSpacing", ""); } set { if (value.Length == 0) { RemoveBodyValue("ColumnSpacing"); } else { DesignerUtility.ValidateSize(value, true, false); SetBodyValue("ColumnSpacing", value); } } } [LocalizedCategory("XML")] [Editor(typeof(FileUIEditor), typeof(UITypeEditor))] [LocalizedDisplayName("Report_DataTransform")] [LocalizedDescription("Report_DataTransform")] public string DataTransform { get { return GetReportValue("DataTransform"); } set { SetReportValue("DataTransform", value); } } [LocalizedCategory("XML")] [LocalizedDisplayName("Report_DataSchema")] [LocalizedDescription("Report_DataSchema")] public string DataSchema { get { return GetReportValue("DataSchema"); } set { SetReportValue("DataSchema", value); } } [LocalizedCategory("XML")] [LocalizedDisplayName("Report_DataElementName")] [LocalizedDescription("Report_DataElementName")] public string DataElementName { get { return GetReportValue("DataElementName"); } set { SetReportValue("DataElementName", value); } } [LocalizedCategory("XML")] [TypeConverter(typeof(ElementStyleConverter))] [LocalizedDisplayName("Report_DataElementStyle")] [LocalizedDescription("Report_DataElementStyle")] public string DataElementStyle { get { return GetReportValue("DataElementStyle", "AttributeNormal"); } set { SetReportValue("DataElementStyle", value); } } string GetBodyValue(string l, string def) { XmlNode rNode = _Draw.GetReportNode(); XmlNode bNode = _Draw.GetNamedChildNode(rNode, "Body"); return _Draw.GetElementValue(bNode, l, def); } void SetBodyValue(string l, string v) { XmlNode rNode = _Draw.GetReportNode(); XmlNode bNode = _Draw.GetNamedChildNode(rNode, "Body"); _DesignCtl.StartUndoGroup(Strings.PropertyReport_Undo_Body + " " + l + " " + Strings.PropertyReport_Undo_change); _Draw.SetElement(bNode, l, v); _DesignCtl.EndUndoGroup(true); _DesignCtl.SignalReportChanged(); _Draw.Invalidate(); } void RemoveBodyValue(string l) { XmlNode rNode = _Draw.GetReportNode(); XmlNode bNode = _Draw.GetNamedChildNode(rNode, "Body"); _DesignCtl.StartUndoGroup(Strings.PropertyReport_Undo_Body + " " + l + " " + Strings.PropertyReport_Undo_change); _Draw.RemoveElement(bNode, l); _DesignCtl.EndUndoGroup(true); _DesignCtl.SignalReportChanged(); _Draw.Invalidate(); } internal string GetReportValue(string l) { return GetReportValue(l, ""); } internal string GetReportValue(string l, string def) { XmlNode rNode = _Draw.GetReportNode(); return _Draw.GetElementValue(rNode, l, def); } internal void SetReportValue(string l, string v) { XmlNode rNode = _Draw.GetReportNode(); _DesignCtl.StartUndoGroup(l + " " + Strings.PropertyReport_Undo_change); _Draw.SetElement(rNode, l, v); _DesignCtl.EndUndoGroup(true); _DesignCtl.SignalReportChanged(); _Draw.Invalidate(); } } #region Parameters [TypeConverter(typeof(PropertyReportParameterConverter)), Editor(typeof(PropertyReportParameterUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyReportParameters { PropertyReport pr; internal PropertyReportParameters(PropertyReport r) { pr = r; } public override string ToString() { XmlNode rNode = pr.Draw.GetReportNode(); XmlNode rpsNode = pr.Draw.GetNamedChildNode(rNode, "ReportParameters"); string s; if (rpsNode == null) s = "No parameters defined"; else { // show the list of parameters StringBuilder sb = new StringBuilder(); foreach (XmlNode repNode in rpsNode) { XmlAttribute nAttr = repNode.Attributes["Name"]; if (nAttr == null) // shouldn't really happen continue; if (sb.Length > 0) sb.Append(", "); sb.Append(nAttr.Value); } sb.Append(" defined"); s = sb.ToString(); } return s; } } internal class PropertyReportParameterConverter : StringConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyReportParameters)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyReportParameters) { PropertyReportParameters prp = value as PropertyReportParameters; return prp.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } internal class PropertyReportParameterUIEditor : UITypeEditor { internal PropertyReportParameterUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form PropertyReport pr = context.Instance as PropertyReport; if (pr == null) return base.EditValue(context, provider, value); using (SingleCtlDialog scd = new SingleCtlDialog(pr.DesignCtl, pr.Draw, null, SingleCtlTypeEnum.ReportParameterCtl, null)) { // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyReportParameters(pr); } return base.EditValue(context, provider, value); } } } #endregion #region Code [TypeConverter(typeof(PropertyReportCodeConverter)), Editor(typeof(PropertyReportCodeUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyReportCode { PropertyReport pr; internal PropertyReportCode(PropertyReport r) { pr = r; } public override string ToString() { XmlNode rNode = pr.Draw.GetReportNode(); XmlNode cNode = pr.Draw.GetNamedChildNode(rNode, "Code"); return cNode == null ? "None defined" : "Defined"; } } internal class PropertyReportCodeConverter : StringConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyReportCode)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyReportCode) { PropertyReportCode prc = value as PropertyReportCode; return prc.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } internal class PropertyReportCodeUIEditor : UITypeEditor { internal PropertyReportCodeUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form PropertyReport pr = context.Instance as PropertyReport; if (pr == null) return base.EditValue(context, provider, value); using (SingleCtlDialog scd = new SingleCtlDialog(pr.DesignCtl, pr.Draw, null, SingleCtlTypeEnum.ReportCodeCtl, null)) { // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyReportCode(pr); } return base.EditValue(context, provider, value); } } } #endregion #region ModulesClasses [TypeConverter(typeof(PropertyReportModulesClassesConverter)), Editor(typeof(PropertyReportModulesClassesUIEditor), typeof(System.Drawing.Design.UITypeEditor))] internal class PropertyReportModulesClasses { PropertyReport pr; internal PropertyReportModulesClasses(PropertyReport r) { pr = r; } public override string ToString() { XmlNode rNode = pr.Draw.GetReportNode(); StringBuilder sb = new StringBuilder(); XmlNode cmsNode = pr.Draw.GetNamedChildNode(rNode, "CodeModules"); sb.Append(cmsNode == null? "No Modules, ": "Modules, "); XmlNode clsNode = pr.Draw.GetNamedChildNode(rNode, "Classes"); sb.Append(clsNode == null? "No Classes": "Classes"); sb.Append(" defined"); return sb.ToString(); } } internal class PropertyReportModulesClassesConverter : StringConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyReportModulesClasses)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyReportModulesClasses) { PropertyReportModulesClasses prm = value as PropertyReportModulesClasses; return prm.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } internal class PropertyReportModulesClassesUIEditor : UITypeEditor { internal PropertyReportModulesClassesUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form PropertyReport pr = context.Instance as PropertyReport; if (pr == null) return base.EditValue(context, provider, value); using (SingleCtlDialog scd = new SingleCtlDialog(pr.DesignCtl, pr.Draw, null, SingleCtlTypeEnum.ReportModulesClassesCtl, null)) { // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyReportModulesClasses(pr); } return base.EditValue(context, provider, value); } } } #endregion #region XSLFile internal class FileUIEditor : UITypeEditor { internal FileUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form PropertyReport pr = context.Instance as PropertyReport; if (pr == null) return base.EditValue(context, provider, value); using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = Strings.FileUIEditor_EditValue_XSLFilesFilter; ofd.FilterIndex = 0; ofd.CheckFileExists = true; if (ofd.ShowDialog() == DialogResult.OK) { // Return the new property value from the UI editor form return ofd.FileName; } return base.EditValue(context, provider, value); } } } #endregion #region ElementStyle internal class ElementStyleConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "AttributeNormal", "ElementNormal"}); } } #endregion }
using AppXLibrary.DynamicCustomXmlConfigurableAndStartable; using AppXLibrary.Services; using Juhta.Net.Common; using Juhta.Net.Diagnostics; using Juhta.Net.Startup; using Juhta.Net.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Juhta.Net.Services.Tests { [TestClass] public class ServiceFactoryTests : TestClassBase { #region Test Setup Methods [ClassCleanup] public static void ClassCleanup() {} [ClassInitialize] public static void ClassInitialize(TestContext testContext) { if (!Directory.Exists(s_tempDirectory)) Directory.CreateDirectory(s_tempDirectory); } [TestCleanup] public void TestCleanup() { Application.CloseInstance(); DeleteConfigFiles("."); DeleteConfigFiles(s_configDirectory); DeleteConfigFiles(s_tempDirectory); } [TestInitialize] public void TestInitialize() { string defaultLogFile; DeleteLogFiles(GetTestLogDirectory()); defaultLogFile = GetDefaultLogFile(); if (File.Exists(defaultLogFile)) File.Delete(defaultLogFile); AppXLibrary.Startable.StartableLibrary.Reset(); } #endregion #region Test Methods [TestMethod] public void CreateService_AggregateSumService_ServiceGroups_ShouldReturn() { AggregateSumService aggregateSumService; SetConfigFiles("Services", "AggregateSumService_"); Application.StartInstance(null, s_configDirectory); aggregateSumService = ServiceFactory.Instance.CreateService<AggregateSumService>(); aggregateSumService.Add(15); Assert.AreEqual<int>(11 + 12 + 13 + 3 * 15, aggregateSumService.GetSum()); } [TestMethod] public void CreateService_AllParamTypeService_ShouldReturn() { IAllParamTypeService allParamTypeService; SetConfigFiles("Services", "AllParamTypeService_"); Application.StartInstance(null, s_configDirectory); allParamTypeService = ServiceFactory.Instance.CreateService<IAllParamTypeService>("AllParamTypeService"); Assert.AreEqual<bool>(true, allParamTypeService.BoolValue); Assert.AreEqual<byte>(223, allParamTypeService.ByteValue); Assert.AreEqual<char>('d', allParamTypeService.CharValue); Assert.AreEqual<DateTime>(new DateTime(2018, 1, 18), allParamTypeService.DateValue); Assert.AreEqual<DateTime>(new DateTime(2018, 1, 16, 19, 8, 20), allParamTypeService.DateTimeValue); Assert.AreEqual<decimal>(54.7636m, allParamTypeService.DecimalValue); Assert.AreEqual<double>(9956.8763, allParamTypeService.DoubleValue); Assert.AreEqual<float>(6373.88f, allParamTypeService.FloatValue); Assert.AreEqual<int>(64644646, allParamTypeService.IntValue); Assert.AreEqual<Int16>(32767, allParamTypeService.Int16Value); Assert.AreEqual<Int32>(64655646, allParamTypeService.Int32Value); Assert.AreEqual<Int64>(64644646566, allParamTypeService.Int64Value); Assert.AreEqual<long>(327000, allParamTypeService.LongValue); Assert.AreEqual<sbyte>(-100, allParamTypeService.SByteValue); Assert.AreEqual<short>(-4533, allParamTypeService.ShortValue); Assert.AreEqual<Single>(-66334.775f, allParamTypeService.SingleValue); Assert.AreEqual<string>("Hello from the service!", allParamTypeService.StringValue); Assert.AreEqual<DateTime>(new DateTime(1, 1, 1, 3, 9, 21), allParamTypeService.TimeValue); Assert.AreEqual<TimeSpan>(new TimeSpan(12345, 23, 56, 59), allParamTypeService.TimeSpanValue); Assert.AreEqual<uint>(65000, allParamTypeService.UintValue); Assert.AreEqual<UInt16>(56433, allParamTypeService.Uint16Value); Assert.AreEqual<UInt32>(444444444, allParamTypeService.Uint32Value); Assert.AreEqual<UInt64>(555555555555555, allParamTypeService.Uint64Value); Assert.AreEqual<ulong>(46456464646464, allParamTypeService.UlongValue); Assert.AreEqual<ushort>(56733, allParamTypeService.UshortValue); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void CreateService_InvalidServiceIdScheme_ShouldThrowArgumentException() { SetConfigFiles("Services", "AllParamTypeService_"); Application.StartInstance(null, s_configDirectory); try { ServiceFactory.Instance.CreateService<SumService>("scheme%", "SumService"); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("Invalid 'scheme' parameter value was passed to the method 'Juhta.Net.Services.ServiceId..ctor'.")); Assert.IsTrue(ex.Message.Contains("The value 'scheme%' does not conform to the regex pattern '^([a-zA-Z0-9])+$'.")); throw; } } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void CreateService_InvalidServiceIdSpecifier_ShouldThrowArgumentException() { SetConfigFiles("Services", "AllParamTypeService_"); Application.StartInstance(null, s_configDirectory); try { ServiceFactory.Instance.CreateService<SumService>("scheme", "SumService%"); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("Invalid 'specifier' parameter value was passed to the method 'Juhta.Net.Services.ServiceId..ctor'.")); Assert.IsTrue(ex.Message.Contains("The value 'SumService%' does not conform to the regex pattern '^([a-zA-Z0-9\\._/-])+$'.")); throw; } } [TestMethod] public void CreateService_NoConstructorParams_DefaultConstructor1_ShouldReturn() { SumService2 sumService2; SetConfigFiles("Services", "NoConstructorParams_DefaultConstructor_"); Application.StartInstance(null, s_configDirectory); sumService2 = ServiceFactory.Instance.CreateService<SumService2>("SumService20"); sumService2.Add(10); Assert.AreEqual<int>(100 + 10, sumService2.GetSum()); } [TestMethod] public void CreateService_NoConstructorParams_DefaultConstructor2_ShouldReturn() { SumService2 sumService2; SetConfigFiles("Services", "NoConstructorParams_DefaultConstructor_"); Application.StartInstance(null, s_configDirectory); sumService2 = ServiceFactory.Instance.CreateService<SumService2>("SumService21"); sumService2.Add(11); Assert.AreEqual<int>(100 + 11, sumService2.GetSum()); } [TestMethod] [ExpectedException(typeof(ServiceCreationException))] public void CreateService_NoConstructorParams_NoDefaultConstructor_ShouldThrowServiceCreationException() { SumService sumService; SetConfigFiles("Services", "NoConstructorParams_NoDefaultConstructor_"); Application.StartInstance(null, s_configDirectory); try { sumService = ServiceFactory.Instance.CreateService<SumService>("SumService"); } catch (Exception ex) { Logger.LogError(ex); AssertDefaultLogFileContent( "[Juhta.Net.Services.Error105004]", "Juhta.Net.Services.ServiceCreationException: [Juhta.Net.Services.Error105004] An instance of the dependency injection service 'name:SumService' could not be created.", "System.MissingMethodException: Constructor on type 'AppXLibrary.Services.SumService' not found." ); throw; } } [TestMethod] [ExpectedException(typeof(ServiceCreationException))] public void CreateService_NonExistingLibraryClass_ShouldThrowServiceCreationException() { object testService; SetConfigFiles("Services", "NonExistingLibraryClass_"); Application.StartInstance(null, s_configDirectory); try { testService = ServiceFactory.Instance.CreateService<object>("TestService"); } catch (Exception ex) { Logger.LogError(ex); AssertDefaultLogFileContent( "[Juhta.Net.Common.Error100017]", "Juhta.Net.Services.ServiceCreationException: [Juhta.Net.Services.Error105004] An instance of the dependency injection service 'name:TestService' could not be created.", "System.ArgumentException", "[Juhta.Net.Common.Error100017] An instance of the class 'AppXLibrary.Services.TestService' could not be created because the type was not found in the assembly" ); throw; } } [TestMethod] [ExpectedException(typeof(ServiceCreationException))] public void CreateService_NonExistingLibraryFile_ShouldThrowServiceCreationException() { object testService; SetConfigFiles("Services", "NonExistingLibraryFile_"); Application.StartInstance(null, s_configDirectory); try { testService = ServiceFactory.Instance.CreateService<object>("TestService"); } catch (Exception ex) { Logger.LogError(ex); AssertDefaultLogFileContent( "[Juhta.Net.Services.Error105004]", "Juhta.Net.Services.ServiceCreationException: [Juhta.Net.Services.Error105004] An instance of the dependency injection service 'name:TestService' could not be created.", "System.IO.FileNotFoundException", "AppXLibrary1234.dll'. The system cannot find the file specified." ); throw; } } [TestMethod] public void CreateService_NoServiceName_ServiceTypeImplemented_ShouldReturn() { IAllParamTypeService allParamTypeService; SetConfigFiles("Services", "NoServiceName_ServiceTypeImplemented_"); Application.StartInstance(null, s_configDirectory); allParamTypeService = ServiceFactory.Instance.CreateService<IAllParamTypeService>(); Assert.AreEqual<string>("This service has no name!", allParamTypeService.StringValue); } [TestMethod] [ExpectedException(typeof(KeyNotFoundException))] public void CreateService_NoServiceName_ServiceTypeNotImplemented_ShouldThrowKeyNotFoundException() { SumService sumService; SetConfigFiles("Services", "SumService10_"); Application.StartInstance(null, s_configDirectory); try { sumService = ServiceFactory.Instance.CreateService<SumService>(); } catch (Exception ex) { Logger.LogError(ex); AssertDefaultLogFileContent( "[Juhta.Net.Services.Error105001]", "System.Collections.Generic.KeyNotFoundException: [Juhta.Net.Services.Error105001] No dependency injection service was found with the identifier 'type:AppXLibrary.Services.SumService'." ); throw; } } [TestMethod] public void CreateService_SumService10_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "SumService10_"); Application.StartInstance(null, s_configDirectory); for (int i = 0; i < 9; i++) { sumService = ServiceFactory.Instance.CreateService<SumService>($"SumService{i}"); sumService.Add(10 + i); Assert.AreEqual<int>(10 + i + 10 + i, sumService.GetSum()); } } [TestMethod] public void CreateService_SumService10_ServiceGroups_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "SumService10_ServiceGroups_"); Application.StartInstance(null, s_configDirectory); for (int i = 0; i < 9; i++) { sumService = ServiceFactory.Instance.CreateService<SumService>($"SumService{i}"); sumService.Add(10 + i); Assert.AreEqual<int>(10 + i + 10 + i, sumService.GetSum()); } } [TestMethod] public void CreateService_SumService10_ServiceGroups2_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "SumService10_ServiceGroups2_"); Application.StartInstance(null, s_configDirectory); for (int i = 0; i < 9; i++) { sumService = ServiceFactory.Instance.CreateService<SumService>($"SumService{i}"); sumService.Add(10 + i); Assert.AreEqual<int>(10 + i + 10 + i, sumService.GetSum()); } } [TestMethod] public void CreateService_SumService10_ServiceGroups3_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "SumService10_ServiceGroups3_"); Application.StartInstance(null, s_configDirectory); for (int i = 0; i < 9; i++) { sumService = ServiceFactory.Instance.CreateService<SumService>($"SumService{i}"); sumService.Add(10 + i); Assert.AreEqual<int>(10 + i + 10 + i, sumService.GetSum()); } } [TestMethod] [ExpectedException(typeof(KeyNotFoundException))] public void CreateService_UndefinedServiceName_ShouldThrowKeyNotFoundException() { SumService sumService; SetConfigFiles("Services", "SumService10_"); Application.StartInstance(null, s_configDirectory); try { sumService = ServiceFactory.Instance.CreateService<SumService>("SumService10"); } catch (Exception ex) { Logger.LogError(ex); AssertDefaultLogFileContent( "[Juhta.Net.Services.Error105001]", "System.Collections.Generic.KeyNotFoundException: [Juhta.Net.Services.Error105001] No dependency injection service was found with the identifier 'name:SumService10'." ); throw; } } [TestMethod] public void CreateService_ValidServiceId_AllCharacters_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "ValidServiceId_AllCharacters_"); Application.StartInstance(null, s_configDirectory); sumService = ServiceFactory.Instance.CreateService<SumService>(new ServiceId("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._/-")); sumService.Add(19); Assert.AreEqual<int>(72 + 19, sumService.GetSum()); } [TestMethod] public void CreateService_ValidServiceIdSchemeAndSpecifier_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "SumService10_"); Application.StartInstance(null, s_configDirectory); sumService = ServiceFactory.Instance.CreateService<SumService>("name", "SumService0"); sumService.Add(9); Assert.AreEqual<int>(10 + 9, sumService.GetSum()); } [TestMethod] public void CreateService_ValidServiceIdSchemeAndSpecifier2_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "SumService10_"); Application.StartInstance(null, s_configDirectory); sumService = ServiceFactory.Instance.CreateService<SumService>(new ServiceId("name", "SumService0")); sumService.Add(9); Assert.AreEqual<int>(10 + 9, sumService.GetSum()); } [TestMethod] public void CreateService_ValidServiceIdSchemeAndSpecifier3_ShouldReturn() { SumService sumService; SetConfigFiles("Services", "SumService10_"); Application.StartInstance(null, s_configDirectory); sumService = ServiceFactory.Instance.CreateService<SumService>(new ServiceId("name:SumService0")); sumService.Add(9); Assert.AreEqual<int>(10 + 9, sumService.GetSum()); } [TestMethod] public void Services_ShouldReturn() { Service[] services; SetConfigFiles("Services", "SumService10_"); Application.StartInstance(null, s_configDirectory); services = ServiceFactory.Instance.Services; Assert.AreEqual<int>(10, services.Length); var sumServices = services.Where(service => service.Id.Specifier.StartsWith("SumService")); Assert.AreEqual<int>(10, sumServices.Count()); } [TestMethod] [ExpectedException(typeof(LibraryInitializationException))] public void Startup_FractionSecondInDateTimeConstructorParam_ShouldThrowLibraryInitializationException() { SetConfigFiles("Services", "FractionSecondInDateTimeConstructorParam_"); try { Application.StartInstance(null, s_configDirectory); } catch (Exception ex) { AssertDefaultLogFileContent( "[Juhta.Net.Services.Error105003]", "Juhta.Net.Services.ServiceInitializationException: [Juhta.Net.Services.Error105005] Dependency injection service 'name:AnyService' could not be initialized.", "Juhta.Net.Services.ConstructorParamException: [Juhta.Net.Services.Error105002] Constructor parameter 'dateTimeValue' could not be initialized.", "Juhta.Net.Common.InvalidConfigValueException: [Juhta.Net.Services.Error105003] Value '2018-02-04T16:55:00.7774' of the constructor parameter 'dateTimeValue' is not a valid 'DateTime' parameter value." ); Assert.IsTrue(ex.InnerException is ServiceInitializationException); throw; } } [TestMethod] [ExpectedException(typeof(LibraryInitializationException))] public void Startup_IdNotGiven_ShouldThrowLibraryInitializationException() { SetConfigFiles("Services", "IdNotGiven_"); try { Application.StartInstance(null, s_configDirectory); } catch (Exception ex) { AssertDefaultLogFileContent( "[Juhta.Net.Startup.Error106002]", "Juhta.Net.Common.InvalidConfigFileException: [Juhta.Net.Startup.Error106002] XML configuration file", "[Juhta.Net.Startup.Error106002] XML configuration file", "Juhta.Net.Services.config' does not conform to the configuration schema(s) of the custom XML configurable library 'Juhta.Net.Services.dll'.", "Juhta.Net.Validation.ValidationException: [Juhta.Net.Validation.Error102004] XML document is not valid according to the given schema(s).", "System.Xml.Schema.XmlSchemaValidationException: The required attribute 'id' is missing." ); Assert.IsTrue(ex.InnerException is InvalidConfigFileException); throw; } } #endregion #region Private Methods private void StressTestMain(object paramObj) { Stopwatch stopwatch = new Stopwatch(); string s; ReplaceService replaceService = new ReplaceService(); StressTestParam param = (StressTestParam)paramObj; stopwatch.Start(); do s = replaceService.Replace("Ho-Ho-Ho"); while (s == $"Yo-Yo-Yo" && stopwatch.ElapsedMilliseconds <= 30000); param.Value = s + "-" + param.Index.ToString(); } #endregion #region Private Types private class StressTestParam { #region Public Properties public int Index {get; set;} public string Value {get; set;} #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace eDrive.Osc.Serialisation { /// <summary> /// Osc Serializer Factory; /// </summary> public static class SerializerFactory { /// <summary> /// The beginning character in an Osc message type tag. /// </summary> public const char DefaultTag = ','; /// <summary> /// The type tag for Nil. No bytes are allocated in the argument data. /// </summary> public const char NilTag = 'N'; /// <summary> /// The type tag for inifinitum. No bytes are allocated in the argument data. /// </summary> public const char InfinitumTag = 'I'; /// <summary> /// The type tag for event. No bytes are allocated in the argument data. /// </summary> public const char EventTag = 'I'; /// <summary> /// The type tag for event. No bytes are allocated in the argument data. /// </summary> public const string EventTagString = "I"; /// <summary> /// The array open /// </summary> public const char ArrayOpen = '['; /// <summary> /// The array close /// </summary> public const char ArrayClose = ']'; private static readonly IOscTypeSerializer[] s_tag2Serializer; private static readonly Dictionary<Type, IOscTypeSerializer> s_type2Serializer; private static string s_supported; /// <summary> /// Initializes the <see cref="SerializerFactory" /> class. /// </summary> static SerializerFactory() { s_type2Serializer = new Dictionary<Type, IOscTypeSerializer>(); s_tag2Serializer = new IOscTypeSerializer[256]; NilSerializer = new NilSerializer(); StringSerializer = new StringSerializer(); TimeTagSerializer = new OscTimeTagSerializer(); IntSerializer = new IntSerializer(); ByteArraySerializer = new ByteArraySerializer(); var src = typeof(SerializerFactory).GetTypeInfo ().Assembly; LoadSerializersFromAssembly (src); } public static void LoadSerializer(TypeInfo source){ if (source == null) { throw new ArgumentNullException ("source"); } s_supported = null; Scan(source); } public static void LoadSerializer(Type source){ if (source == null) { throw new ArgumentNullException ("source"); } LoadSerializer (source.GetTypeInfo ()); } public static void LoadSerializers(IEnumerable<TypeInfo> sources){ if (sources == null) { throw new ArgumentNullException ("sources"); } s_supported = null; foreach (var source in sources) { Scan(source); } } public static void LoadSerializers(IEnumerable<Type> sources){ if (sources == null) { throw new ArgumentNullException ("sources"); } s_supported = null; foreach (var source in sources.Select(s => s.GetTypeInfo())) { Scan(source); } } public static void LoadSerializers(params TypeInfo[] sources){ if (sources == null) { throw new ArgumentNullException ("sources"); } LoadSerializers ((IEnumerable<TypeInfo>)sources); } public static void LoadSerializersFromAssembly(Assembly source){ if (source == null) { throw new ArgumentNullException ("source"); } s_supported = null; Scan(source); } public static void LoadSerializersFromAssemblies(IEnumerable<Assembly> sources) { if (sources == null) { throw new ArgumentNullException ("sources"); } s_supported = null; foreach (var source in sources) { Scan(source); } } public static void LoadSerializersFromAssemblies(params Assembly[] sources) { if (sources == null) { throw new ArgumentNullException ("sources"); } LoadSerializersFromAssemblies((IEnumerable<Assembly>)sources); } /// <summary> /// Gets the byte array serializer. /// </summary> /// <value> /// The byte array serializer. /// </value> public static ByteArraySerializer ByteArraySerializer { get; private set; } /// <summary> /// Gets the int serializer. /// </summary> /// <value> /// The int serializer. /// </value> public static IntSerializer IntSerializer { get; private set; } /// <summary> /// Gets the time tag serializer. /// </summary> /// <value> /// The time tag serializer. /// </value> public static OscTimeTagSerializer TimeTagSerializer { get; private set; } /// <summary> /// Gets the string serializer. /// </summary> /// <value> /// The string serializer. /// </value> public static StringSerializer StringSerializer { get; private set; } /// <summary> /// Gets the nil serializer. /// </summary> /// <value> /// The nil serializer. /// </value> public static NilSerializer NilSerializer { get; private set; } /// <summary> /// Gets the tag. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <returns></returns> public static string GetTag<T>(T value) { var t = typeof (T); var tInfo = t.GetTypeInfo (); var typeTag = string.Empty; if (value is Array && !(value is byte[])) // NB: blobs are handled with a specific serializer. { typeTag += ArrayOpen; foreach (var component in (value as Array)) { if (component is Array) { throw new OscSerializerException("Nested arrays are not supported."); } typeTag += GetTag(component); } typeTag += ArrayClose; } else { if (!tInfo.IsValueType && Equals(value, default(T))) { typeTag += NilSerializer.Tag; } else if (t == value.GetType()) { if (tInfo.IsValueType || !Equals(value, default(T))) { var sed = GetSerializer<T>(); typeTag += sed.GetTag(value); } else { typeTag += NilSerializer.Tag; } } else { var sed = GetSerializer((object) value); typeTag += sed.GetTag(value); } } return typeTag; } /// <summary> /// Determines whether this instance can serialise the specified t. /// </summary> /// <param name="t">The t.</param> /// <returns> /// <c>true</c> if this instance can serialise the specified t; otherwise, <c>false</c>. /// </returns> public static bool CanSerialize(Type t) { return s_type2Serializer.ContainsKey(t); } /// <summary> /// Supported types. /// </summary> /// <returns></returns> public static string SupportedTypes() { if (s_supported == null) { var chars = s_tag2Serializer.Where(s => s != null) .Select((s, i) => (char) i) .Concat(new[] {NilTag, EventTag, ArrayOpen, ArrayClose}) .Distinct() .ToArray(); s_supported = new string(chars); } return s_supported; } /// <summary> /// Gets the serializer. /// </summary> /// <param name="typeTag">The type tag.</param> /// <returns></returns> public static IOscTypeSerializer GetSerializer(char typeTag) { return s_tag2Serializer[typeTag]; } /// <summary> /// Gets the ses serializer. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static IOscTypeSerializer GetSerializer(Type type) { return s_type2Serializer[type]; } /// <summary> /// Gets the serializer. /// </summary> /// <param name="source">The source.</param> /// <returns></returns> public static IOscTypeSerializer GetSerializer(object source) { return (source == null ? NilSerializer : GetSerializer(source.GetType())); } /// <summary> /// Gets the serializer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> public static IOscTypeSerializer<T> GetSerializer<T>(T source) { return GetSerializer<T>(); } /// <summary> /// Gets the serializer. /// </summary> /// <param name="typeTag">The type tag.</param> /// <returns></returns> public static IOscTypeSerializer<T> GetSerializer<T>(char typeTag) { return GetSerializer(typeTag) as IOscTypeSerializer<T>; } /// <summary> /// Gets the ses serializer. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IOscTypeSerializer<T> GetSerializer<T>() { var type = typeof (T); return GetSerializer(type) as IOscTypeSerializer<T>; } private static void Scan(TypeInfo tInfo) { var attr = tInfo.GetCustomAttribute<CustomOscSerializerAttribute> (); if (attr != null) { try { var instance = Activator.CreateInstance(tInfo.AsType()) as IOscTypeSerializer; if (instance != null) { if (attr.TypeTag != ' ') { s_tag2Serializer[attr.TypeTag] = instance; } if (attr.Type != null) { s_type2Serializer[attr.Type] = instance; } } } catch { } } } private static void Scan(Assembly loadedAssembly) { { var types = loadedAssembly.ExportedTypes.Select(et => et.GetTypeInfo()); foreach (var source in types) { Scan (source); } } } } }
// 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 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// MultipleResponses operations. /// </summary> public partial interface IMultipleResponses { /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError204ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError201InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with no payload: /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError202NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid error payload: {'status': 400, /// 'message': 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model204NoModelDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201', /// 'textStatusCode': 'Created'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError201ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200Model201ModelDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'httpCode': '201'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError201ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'httpStatusCode': '404'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError404ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<object>> Get200ModelA201ModelC404ModelDDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultError202NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultError204NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': /// 'client error'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultError400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with an unexpected payload {'property': /// 'value'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone202InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone204NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with an unexpected payload {'property': /// 'value'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> Get202None204NoneDefaultNone400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> GetDefaultModelA400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload: {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone200InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> GetDefaultNone400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with no payload, when a payload is expected - /// client should return a null object of thde type for model A /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA200NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with payload {'statusCode': '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA200ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': /// '200'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA200InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 400 response with no payload client should treat as an http /// error with no error model /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA400NoneWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with payload {'statusCode': '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA400ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': /// '400'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA400InvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Send a 202 response with payload {'statusCode': '202'} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<A>> Get200ModelA202ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/******************************************************************************* INTEL CORPORATION PROPRIETARY INFORMATION This software is supplied under the terms of a license agreement or nondisclosure agreement with Intel Corporation and may not be copied or disclosed except in accordance with the terms of that agreement Copyright(c) 2012-2015 Intel Corporation. All Rights Reserved. ******************************************************************************/ using System; using UnityEngine; using RSUnityToolkit; [System.Serializable] public class SmoothingUtility : System.Object { private SmoothingTypes _type3D; private SmoothingTypes _type2D; private SmoothingTypes _type1D; private float _factor3D; private float _factor2D; private float _factor1D; private PXCMSmoother _smoother; private PXCMSmoother.Smoother3D _smoother3D; private PXCMSmoother.Smoother2D _smoother2D; private PXCMSmoother.Smoother1D _smoother1D; private bool _initialized = false; public enum SmoothingTypes { Spring, Stabilizer, Weighted, Quadratic } public SmoothingUtility() { } public void Dispose() { if (_smoother1D != null) { _smoother1D.Dispose(); } if (_smoother2D != null) { _smoother2D.Dispose(); } if (_smoother3D != null) { _smoother3D.Dispose(); } if (_smoother != null) { _smoother.Dispose(); } } ~SmoothingUtility() { } public bool Init() { if (!_initialized && SenseToolkitManager.Instance != null) { SenseToolkitManager.Instance.AddDisposeFunction(Dispose); _initialized = true; } return _initialized; } public Quaternion ProcessSmoothing(SmoothingTypes type, float factor, Quaternion vec) { Init(); Vector3 vec3 = new Vector3(vec.x, vec.y, vec.z); vec3 = ProcessSmoothing(type, factor, vec3); float w = vec.w; w = ProcessSmoothing(type, factor, w); return new Quaternion(vec3.x, vec3.y, vec3.z, w); } public Vector3 ProcessSmoothing(SmoothingTypes type, float factor, Vector3 vec) { Init(); if (_smoother == null) { SenseToolkitManager.Instance.SenseManager.session.CreateImpl<PXCMSmoother>(out _smoother); } if (_smoother3D == null || _type3D != type || factor != _factor3D) { if (_smoother3D != null) { _smoother3D.Dispose(); } CreateSmootherType(type, factor, out _smoother3D); _type3D = type; _factor3D = factor; } PXCMPoint3DF32 point = new PXCMPoint3DF32(){x = vec.x, y = vec.y, z = vec.z}; point = _smoother3D.SmoothValue(point); return new Vector3(point.x, point.y, point.z); } public Vector2 ProcessSmoothing(SmoothingTypes type, float factor, Vector2 vec) { Init(); if (_smoother == null) { SenseToolkitManager.Instance.SenseManager.session.CreateImpl<PXCMSmoother>(out _smoother); } if (_smoother2D == null || _type2D != type || factor != _factor2D) { if (_smoother2D != null) { _smoother2D.Dispose(); } CreateSmootherType(type, factor, out _smoother2D); _type2D = type; _factor2D = factor; } PXCMPointF32 point = new PXCMPointF32(){x = vec.x, y = vec.y}; point = _smoother2D.SmoothValue (point); return new Vector2(point.x, point.y); } public float ProcessSmoothing(SmoothingTypes type, float factor, float sample) { Init(); if (_smoother == null) { SenseToolkitManager.Instance.SenseManager.session.CreateImpl<PXCMSmoother>(out _smoother); } if (_smoother1D == null || _type1D != type || factor != _factor1D) { if (_smoother1D != null) { _smoother1D.Dispose(); } CreateSmootherType(type, factor, out _smoother1D); _type1D = type; _factor1D = factor; } sample = _smoother1D.SmoothValue (sample); return sample; } private void CreateSmootherType(SmoothingTypes type, float factor, out PXCMSmoother.Smoother3D smoother) { switch (type) { case SmoothingTypes.Quadratic: smoother = _smoother.Create3DQuadratic(factor); break; case SmoothingTypes.Stabilizer: smoother = _smoother.Create3DStabilizer(7, factor); break; case SmoothingTypes.Weighted: smoother = _smoother.Create3DWeighted((int)factor); break; case SmoothingTypes.Spring: default: smoother = _smoother.Create3DSpring(factor); break; } } private void CreateSmootherType(SmoothingTypes type, float factor, out PXCMSmoother.Smoother2D smoother) { switch (type) { case SmoothingTypes.Quadratic: smoother = _smoother.Create2DQuadratic(factor); break; case SmoothingTypes.Stabilizer: smoother = _smoother.Create2DStabilizer(7, factor); break; case SmoothingTypes.Weighted: smoother = _smoother.Create2DWeighted((int)factor); break; case SmoothingTypes.Spring: default: smoother = _smoother.Create2DSpring(factor); break; } } private void CreateSmootherType(SmoothingTypes type, float factor, out PXCMSmoother.Smoother1D smoother) { switch (type) { case SmoothingTypes.Quadratic: smoother = _smoother.Create1DQuadratic(factor); break; case SmoothingTypes.Stabilizer: smoother = _smoother.Create1DStabilizer(7, factor); break; case SmoothingTypes.Weighted: smoother = _smoother.Create1DWeighted((int)factor); break; case SmoothingTypes.Spring: default: smoother = _smoother.Create1DSpring(factor); break; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.SqlClient; using System.Diagnostics; using System.Drawing.Printing; using System.Linq; using System.Reflection; using System.Windows.Forms; using bv.common.Configuration; using bv.common.Core; using bv.common.Enums; using bv.model.BLToolkit; using bv.model.Model.Core; using bv.winclient.BasePanel; using bv.winclient.Core; using bv.winclient.Core.TranslationTool; using bv.winclient.Layout; using DevExpress.Utils; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Controls; using DevExpress.XtraPrinting; using eidss.model.Core.CultureInfo; using eidss.model.Reports; using eidss.model.Reports.Common; using eidss.model.Reports.OperationContext; using eidss.model.Resources; using EIDSS.Reports.BaseControls.Form; using EIDSS.Reports.BaseControls.Report; using EIDSS.Reports.BaseControls.Transaction; using eidss.winclient.Reports; using Localizer = bv.common.Core.Localizer; using Trace = bv.common.Trace; namespace EIDSS.Reports.BaseControls.Keeper { public partial class BaseReportKeeper : BvXtraUserControl { private readonly IContextKeeper m_ContextKeeper; private readonly LanguageProcessor m_LanguageProcessor; private readonly ScreenSaver m_ScreenSaver; private bool m_FirstLoad = true; protected bool m_HasLoad; private static Dictionary<string, string> m_ReportNameDictionary; protected Dictionary<string, string> m_Parameters; private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (BaseReportKeeper)); private WaitDialog m_FirstReportRenderWait; private DbManagerProxy m_DbManager; private readonly string m_ReportAlias; public BaseReportKeeper() : this(new Dictionary<string, string>()) { } public BaseReportKeeper(Dictionary<string, string> parameters) { Utils.CheckNotNull(parameters, "parameters"); m_Parameters = parameters; LayoutCorrector.Reset(); m_ContextKeeper = new ContextKeeper(); string title = EidssMessages.Get("msgPleaseWait"); string caption = EidssMessages.Get("msgReportInitializing"); using (new WaitDialog(caption, title)) { InitializeComponent(); LayoutCorrector.SetStyleController(cbLanguage, LayoutCorrector.MandatoryStyleController); m_ScreenSaver = new ScreenSaver(this, reportView1); m_LanguageProcessor = new LanguageProcessor(this); InitLanguages(); m_ReportAlias = GetCurrentReportAlias(); } } [Browsable(true)] public int HeaderHeight { get { return grcTop.Height; } set { grcTop.Height = value; } } [Browsable(false)] public IContextKeeper ContextKeeper { get { return m_ContextKeeper; } } [Browsable(false)] public CultureInfoEx CurrentCulture { get { return m_LanguageProcessor.CurrentCulture; } set { m_LanguageProcessor.CurrentCulture = value; } } [Browsable(false)] public bool UseArchive { get { return ceUseArchiveData.CheckState == CheckState.Checked; } } [Browsable(false)] public Type ReportType { get; protected set; } [Browsable(false)] protected bool IsResourceLoading { get; set; } [Browsable(false)] [DefaultValue(false)] protected internal bool ReloadReportOnLanguageChanged { get; set; } private static Dictionary<string, string> ReportNameDictionary { get { if (m_ReportNameDictionary == null) { m_ReportNameDictionary = new Dictionary<string, string>(); foreach (MethodInfo info in typeof (IReportFactory).GetMethods()) { var attribute = (MenuReportDescriptionAttribute) info.GetCustomAttributes(typeof (MenuReportDescriptionAttribute), true).FirstOrDefault(); if (attribute != null) { m_ReportNameDictionary.Add(info.Name, attribute.Caption); } } } return m_ReportNameDictionary; } } protected internal void ReloadReportIfFormLoaded(Control sender = null) { if (!m_HasLoad || WinUtils.IsComponentInDesignMode(this) || ContextKeeper.ContainsContext(ContextValue.ReportFormLoading) || ContextKeeper.ContainsContext(ContextValue.ReportLoading) || ContextKeeper.ContainsContext(ContextValue.ReportFilterLoading)) { return; } DisableControlAndReloadReport(sender); } private void DisableControlAndReloadReport(Control sender) { if (sender == null) { ReloadReport(); } else { using (new DisableControlTransaction(sender, ContextKeeper)) { ReloadReport(); } } } private void ReloadReport() { using (ContextKeeper.CreateNewContext(ContextValue.ReportLoading)) { bool cultureNotChanged = ModelUserContext.CurrentLanguage == Localizer.GetLanguageID(CurrentCulture.CultureInfo); using (new CultureInfoTransaction(CurrentCulture.CultureInfo)) { try { InitMessageRendering(); // set "screensaver" to prevent flicking of report view control during report generation if (!m_FirstLoad) { m_ScreenSaver.Screen = (reportView1.Report == null) ? m_ScreenSaver.DefaultScreen : reportView1; } m_FirstLoad = false; reportView1.ApplyResources(); Application.DoEvents(); Application.DoEvents(); if (ValidateMandatoryFields()) { if (m_DbManager != null) { m_DbManager.Dispose(); } m_DbManager = DbManagerFactory.Factory.Create(ModelUserContext.Instance); BaseReport report = GenerateReport(m_DbManager); reportView1.SetReport(report, cultureNotChanged); reportView1.Report.AfterPrint += Report_AfterPrint; // start timer which shows report if AfterPrint will not fire automatically ShowReportTimer.Start(); ApplyPageSettings(); } else { Report_AfterPrint(this, EventArgs.Empty); } var translationView = Parent as ITranslationView; if (translationView != null) { if (translationView.DCManager != null) { translationView.DCManager.ApplyResources(); } else if (BaseSettings.TranslationMode) { DesignControlManager.Create(translationView); } } } catch (SqlException ex) { CreateErrorReport(ex, false); if (!SqlExceptionHandler.Handle(ex)) { ErrorForm.ShowError(StandardError.DatabaseError, ex); } } catch (Exception ex) { CreateErrorReport(ex, false); string description = SqlExceptionHandler.GetExceptionDescription(ex); if (string.IsNullOrEmpty(description)) { ErrorForm.ShowError(ex); } else { ErrorForm.ShowError(description, description, ex); } } } } } protected virtual BaseReport GenerateReport(DbManagerProxy manager) { return new BaseReport(); } protected object CreateReportObject() { object reportObject = Activator.CreateInstance(ReportType, 0, null, null, CurrentCulture.CultureInfo); return reportObject; } private void CreateErrorReport(Exception ex, bool printException) { Trace.WriteLine(ex); ErrorReport errorReport = printException ? new ErrorReport(ex) : new ErrorReport(); reportView1.SetReport(errorReport, false); Report_AfterPrint(this, EventArgs.Empty); } private void cbLanguage_EditValueChanging(object sender, ChangingEventArgs e) { if (ContextKeeper.ContainsContext(ContextValue.ReportLoading)) { e.Cancel = true; } } private void cbLanguage_SelectedIndexChanged(object sender, EventArgs e) { if (!m_HasLoad) { return; } CurrentCulture = (CultureInfoEx) cbLanguage.EditValue; using (new CultureInfoTransaction(CurrentCulture.CultureInfo)) { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { ApplyResources(manager); } Application.DoEvents(); } if (ReloadReportOnLanguageChanged && ValidateMandatoryFields(true)) { ReloadReportIfFormLoaded(sender as Control); } } private void GenerateReportButton_Click(object sender, EventArgs e) { if (ValidateMandatoryFields(true)) { ReloadReportIfFormLoaded(sender as Control); } } protected void ApplyLookupResources(LookUpEdit lookup, List<ItemWrapper> dataSource, int? parameter, string caption) { int index = -1; if (parameter.HasValue) { index = parameter.Value - 1; } BindLookup(lookup, dataSource, caption); if (index != -1) { lookup.ItemIndex = index; lookup.EditValue = dataSource[index]; } else { lookup.EditValue = null; } } protected void BindLookup(LookUpEdit lookup, List<ItemWrapper> collection, string caption) { lookup.Properties.Columns.Clear(); lookup.Properties.Columns.Add(new LookUpColumnInfo("NativeName", caption, 200, FormatType.None, "", true, HorzAlignment.Near)); lookup.Properties.DataSource = collection; } private void SetUseArchiveDataVisibility(bool canWorkWithArchive) { ceUseArchiveData.Visible = canWorkWithArchive && ArchiveDataHelper.ShowUseArchiveDataCheckbox; } private void ApplyPageSettings() { XtraPageSettingsBase pageSettings = reportView1.Report.PrintingSystem.PageSettings; Margins margins = reportView1.Report.Margins; pageSettings.RightMargin = margins.Right; pageSettings.LeftMargin = margins.Left; pageSettings.TopMargin = margins.Top; pageSettings.BottomMargin = margins.Bottom; } private void Report_AfterPrint(object sender, EventArgs e) { reportView1.Visible = true; m_ScreenSaver.Screen = null; DisposeMessageRendering(); if (m_DbManager != null) { m_DbManager.Dispose(); } ShowReportTimer.Stop(); } private void ShowReportTimer_Tick(object sender, EventArgs e) { Report_AfterPrint(sender, e); } private void InitMessageRendering() { if (m_FirstReportRenderWait == null) { string title = EidssMessages.Get("msgPleaseWait"); string caption = EidssMessages.Get("msgReportRendering"); if (m_FirstReportRenderWait != null) { m_FirstReportRenderWait.Caption = caption; } else { m_FirstReportRenderWait = new WaitDialog(caption, title); } } } private void DisposeMessageRendering() { if (m_FirstReportRenderWait != null) { m_FirstReportRenderWait.Dispose(); m_FirstReportRenderWait = null; } } protected internal virtual void ApplyResources(DbManagerProxy manager) { var reportForm = ParentForm as IReportForm; if (reportForm != null) { reportForm.ApplyResources(); reportForm.Text = string.Format("{0} - {1}", reportForm.Text, EidssMenu.Get(m_ReportAlias, m_ReportAlias)); } grcTop.Text = m_Resources.GetString("grcTop.Text"); ceUseArchiveData.Properties.Caption = m_Resources.GetString("ceUseArchiveData.Properties.Caption"); m_Resources.ApplyResources(lblLanguage, "lblLanguage"); GenerateReportButton.Text = m_Resources.GetString("GenerateReportButton.Text"); LayoutCorrector.ApplySystemFont(this); SetUseArchiveDataVisibility(BaseReport.CanReportWorkWithArchive(ReportType)); } private static string GetCurrentReportAlias() { var stack = new StackTrace(); int frameCount = stack.FrameCount - 1; for (int frame = 3; frame <= frameCount; frame++) { string methodName = stack.GetFrame(frame).GetMethod().Name; if (ReportNameDictionary.ContainsKey(methodName)) { return ReportNameDictionary[methodName]; } } return string.Empty; } private void InitLanguages() { m_LanguageProcessor.InitLanguages(); cbLanguage.Properties.Columns.Clear(); string caption = lblLanguage.Text; cbLanguage.Properties.Columns.Add(new LookUpColumnInfo("NativeName", caption, 200, FormatType.None, "", true, HorzAlignment.Near)); cbLanguage.Properties.DataSource = m_LanguageProcessor.LanguageItems; cbLanguage.EditValue = CurrentCulture; } protected bool ValidateMandatoryFields(bool showMessage = false) { bool isValidated = ValidateMandatoryFields(this); if (showMessage && !isValidated) { ErrorForm.ShowWarningFormat("ErrAllMandatoryFieldsRequired", "You must enter data in all mandatory fields."); } return isValidated; } private static bool ValidateMandatoryFields(Control parentControl) { if (parentControl == null) { return true; } var parentEdit = parentControl as BaseEdit; if (parentEdit != null && parentEdit.Visible && parentEdit.StyleController is MandatoryStyleController && Utils.IsEmpty(parentEdit.Text)) { return false; } IEnumerable<Control> childControls = parentControl.Controls.Cast<Control>(); return childControls.All(ValidateMandatoryFields); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; using Xunit; namespace System.Collections.Tests { public class Perf_BitArray { const int IterationCount = 100_000; private static Random s_random = new Random(42); [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1, true)] [InlineData(10, true)] [InlineData(32, true)] [InlineData(64, true)] [InlineData(100, true)] [InlineData(128, true)] [InlineData(1000, true)] [InlineData(1, false)] [InlineData(10, false)] [InlineData(32, false)] [InlineData(64, false)] [InlineData(100, false)] [InlineData(128, false)] [InlineData(1000, false)] public void BitArrayLengthCtor(int size, bool value) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { var local = new BitArray(size, value); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1, true)] [InlineData(2, true)] [InlineData(3, true)] [InlineData(4, true)] [InlineData(10, true)] [InlineData(32, true)] [InlineData(64, true)] [InlineData(100, true)] [InlineData(128, true)] [InlineData(1000, true)] [InlineData(1, false)] [InlineData(2, false)] [InlineData(3, false)] [InlineData(4, false)] [InlineData(10, false)] [InlineData(32, false)] [InlineData(64, false)] [InlineData(100, false)] [InlineData(128, false)] [InlineData(1000, false)] public void BitArrayBitArrayCtor(int size, bool value) { var original = new BitArray(size, value); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { var local = new BitArray(original); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayBoolArrayCtor(int size) { var bools = new bool[size]; for (int i = 0; i < bools.Length; i++) { bools[i] = s_random.NextDouble() >= 0.5; } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { var local = new BitArray(bools); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayByteArrayCtor(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { var local = new BitArray(bytes); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayIntArrayCtor(int size) { var ints = new int[size]; for (int i = 0; i < ints.Length; i++) { ints[i] = s_random.Next(); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { var local = new BitArray(ints); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1, true)] [InlineData(2, true)] [InlineData(3, true)] [InlineData(4, true)] [InlineData(10, true)] [InlineData(32, true)] [InlineData(64, true)] [InlineData(100, true)] [InlineData(128, true)] [InlineData(1000, true)] [InlineData(1, false)] [InlineData(2, false)] [InlineData(3, false)] [InlineData(4, false)] [InlineData(10, false)] [InlineData(32, false)] [InlineData(64, false)] [InlineData(100, false)] [InlineData(128, false)] [InlineData(1000, false)] public void BitArraySetAll(int size, bool value) { var bytes = new byte[size]; s_random.NextBytes(bytes); var original = new BitArray(bytes); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { original.SetAll(value); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayNot(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); var original = new BitArray(bytes); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { original.Not(); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayGet(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); var original = new BitArray(bytes); bool local = false; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { for (int j = 0; j < original.Length; j++) { local ^= original.Get(j); } } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArraySet(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); var original = new BitArray(bytes); var values = new bool[original.Length]; for (int i = 0; i < values.Length; i++) { values[i] = s_random.NextDouble() >= 0.5; } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { for (int j = 0; j < original.Length; j++) { original.Set(j, values[j]); } } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArraySetLengthGrow(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { var original = new BitArray(bytes); original.Length = original.Length * 2; } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArraySetLengthShrink(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { var original = new BitArray(bytes); original.Length = original.Length / 2; } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayCopyToIntArray(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); var original = new BitArray(bytes); var array = new int[size * 32]; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { original.CopyTo(array, 0); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayCopyToByteArray(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); var original = new BitArray(bytes); var array = new byte[size * 32]; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { original.CopyTo(array, 0); } } } } [Benchmark(InnerIterationCount = IterationCount)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(10)] [InlineData(32)] [InlineData(64)] [InlineData(100)] [InlineData(128)] [InlineData(1000)] public void BitArrayCopyToBoolArray(int size) { var bytes = new byte[size]; s_random.NextBytes(bytes); var original = new BitArray(bytes); var array = new bool[size * 32]; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { original.CopyTo(array, 0); } } } } } }
// 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 System.Linq.Expressions.Tests { public static class BinaryExclusiveOrTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckByteExclusiveOrTest(bool useInterpreter) { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteExclusiveOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckSByteExclusiveOrTest(bool useInterpreter) { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteExclusiveOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortExclusiveOrTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortExclusiveOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortExclusiveOrTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortExclusiveOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntExclusiveOrTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntExclusiveOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntExclusiveOrTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntExclusiveOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongExclusiveOrTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongExclusiveOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongExclusiveOrTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongExclusiveOr(array[i], array[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyByteExclusiveOr(byte a, byte b, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(byte))), Enumerable.Empty<ParameterExpression>()); Func<byte> f = e.Compile(useInterpreter); Assert.Equal((byte)(a ^ b), f()); } private static void VerifySByteExclusiveOr(sbyte a, sbyte b, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(sbyte))), Enumerable.Empty<ParameterExpression>()); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal((sbyte)(a ^ b), f()); } private static void VerifyUShortExclusiveOr(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal((ushort)(a ^ b), f()); } private static void VerifyShortExclusiveOr(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal((short)(a ^ b), f()); } private static void VerifyUIntExclusiveOr(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(a ^ b, f()); } private static void VerifyIntExclusiveOr(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(a ^ b, f()); } private static void VerifyULongExclusiveOr(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(a ^ b, f()); } private static void VerifyLongExclusiveOr(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.ExclusiveOr( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal(a ^ b, f()); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.ExclusiveOr(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.ExclusiveOr(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.ExclusiveOr(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.ExclusiveOr(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.ExclusiveOr(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e = Expression.ExclusiveOr(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a ^ b)", e.ToString()); // NB: Unlike And and Or, there's no special case for bool and bool? here. } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using KellermanSoftware.CompareNetObjects; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; namespace InWorldz.Data.Assets.Stratus.Tests { [TestFixture] class DiskWriteBackCacheTests { private CloudFilesAssetClient _client; private bool _runTests; [TestFixtureSetUp] public void Setup() { if (Environment.GetEnvironmentVariable("CFUsername") == null) { _runTests = false; return; } _runTests = true; Config.Settings.Instance.CFUseInternalURL = false; Config.Settings.Instance.CFUsername = Environment.GetEnvironmentVariable("CFUsername"); Config.Settings.Instance.CFApiKey = Environment.GetEnvironmentVariable("CFAPIKey"); Config.Settings.Instance.CFUseCache = false; Config.Settings.Instance.CFContainerPrefix = Environment.GetEnvironmentVariable("CFContainerPrefix"); Config.Settings.Instance.CFWorkerThreads = 8; Config.Settings.Instance.CFDefaultRegion = Environment.GetEnvironmentVariable("CFDefaultRegion"); _client = new CloudFilesAssetClient(); _client.Start(); } [TestFixtureTearDown] public void Stop() { if (!_runTests) return; _client.Stop(); } [Test] public void TestBasicCacheRetrieval() { Cache.DiskWriteBackCache wbc = new Cache.DiskWriteBackCache(); AssetBase baseAsset = new AssetBase(); baseAsset.Data = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5, 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 }; baseAsset.Name = "Name"; baseAsset.Description = "Description"; baseAsset.FullID = UUID.Random(); baseAsset.Local = true; baseAsset.Temporary = true; baseAsset.Type = 5; baseAsset.Metadata.CreationDate = DateTime.Now; var stAsset = StratusAsset.FromAssetBase(baseAsset); wbc.StoreAsset(stAsset); CompareObjects comp = new CompareObjects(); comp.CompareStaticFields = false; comp.CompareStaticProperties = false; var cacheAsset = wbc.GetAsset(baseAsset.FullID.Guid); Assert.IsTrue(comp.Compare(cacheAsset, stAsset), comp.DifferencesString); CollectionAssert.AreEqual(cacheAsset.Data, stAsset.Data); } [Test] public void TestCachePersists() { Cache.DiskWriteBackCache wbc = new Cache.DiskWriteBackCache(); AssetBase baseAsset = new AssetBase(); baseAsset.Data = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5, 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 }; baseAsset.Name = "Name"; baseAsset.Description = "Description"; baseAsset.FullID = UUID.Random(); baseAsset.Local = true; baseAsset.Temporary = true; baseAsset.Type = 5; baseAsset.Metadata.CreationDate = DateTime.Now; var stAsset = StratusAsset.FromAssetBase(baseAsset); wbc.StoreAsset(stAsset); wbc = null; wbc = new Cache.DiskWriteBackCache(); CompareObjects comp = new CompareObjects(); comp.CompareStaticFields = false; comp.CompareStaticProperties = false; var cacheAsset = wbc.GetAsset(baseAsset.FullID.Guid); Assert.IsTrue(comp.Compare(cacheAsset, stAsset), comp.DifferencesString); CollectionAssert.AreEqual(cacheAsset.Data, stAsset.Data); } [Test] public void TestWriteToCF() { if (!_runTests) return; //delete any leftover files in the writeback cache foreach (var file in Directory.EnumerateFiles("cache/cf_writeback")) { File.Delete(file); } Cache.DiskWriteBackCache wbc = new Cache.DiskWriteBackCache(); AssetBase baseAsset = new AssetBase(); baseAsset.Data = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5, 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 }; baseAsset.Name = "Name"; baseAsset.Description = "Description"; baseAsset.FullID = UUID.Random(); baseAsset.Local = true; baseAsset.Temporary = true; baseAsset.Type = 5; baseAsset.Metadata.CreationDate = DateTime.Now; var stAsset = StratusAsset.FromAssetBase(baseAsset); wbc.StoreAsset(stAsset); wbc.DoWriteCycle(); //the asset should still be in the WB cache Assert.IsNotNull(wbc.GetAsset(baseAsset.FullID.Guid)); //... but we should now be able to get the asset from CF AssetBase cfAsset = _client.RequestAssetSync(baseAsset.FullID); CompareObjects comp = new CompareObjects(); comp.CompareStaticFields = false; comp.CompareStaticProperties = false; Assert.IsTrue(comp.Compare(baseAsset, cfAsset), comp.DifferencesString); CollectionAssert.AreEqual(baseAsset.Data, cfAsset.Data); } [Test] [Repeat(1)] public void TestCFTimeoutAndWritePath() { if (!_runTests) return; //delete any leftover files in the writeback cache foreach (var file in Directory.EnumerateFiles("cache/cf_writeback")) { File.Delete(file); } Cache.DiskWriteBackCache wbc = new Cache.DiskWriteBackCache(); AssetBase baseAsset = new AssetBase(); baseAsset.Data = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5, 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 }; baseAsset.Name = "Name"; baseAsset.Description = "Description"; baseAsset.FullID = UUID.Random(); baseAsset.Local = true; baseAsset.Temporary = true; baseAsset.Type = 5; baseAsset.Metadata.CreationDate = DateTime.Now; try { Config.Settings.Instance.UnitTest_ThrowTimeout = true; _client.StoreAsset(baseAsset); } finally { Config.Settings.Instance.UnitTest_ThrowTimeout = false; } System.Threading.Thread.Sleep(5000); //we should now be able to get the asset from CF since it should've been written back //by the write back recovery code AssetBase cfAsset = _client.RequestAssetSync(baseAsset.FullID); CompareObjects comp = new CompareObjects(); comp.CompareStaticFields = false; comp.CompareStaticProperties = false; Assert.IsTrue(comp.Compare(baseAsset, cfAsset), comp.DifferencesString); CollectionAssert.AreEqual(baseAsset.Data, cfAsset.Data); } [Test] public void TestCFTimeoutAndWritePathWithImmediateStaleDeletes() { if (!_runTests) return; //delete any leftover files in the writeback cache foreach (var file in Directory.EnumerateFiles("cache/cf_writeback")) { File.Delete(file); } AssetBase baseAsset = new AssetBase(); baseAsset.Data = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5, 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 }; baseAsset.Name = "Name"; baseAsset.Description = "Description"; baseAsset.FullID = UUID.Random(); baseAsset.Local = true; baseAsset.Temporary = true; baseAsset.Type = 5; baseAsset.Metadata.CreationDate = DateTime.Now; try { Config.Settings.Instance.UnitTest_ThrowTimeout = true; Config.Settings.Instance.UnitTest_DeleteOldCacheFilesImmediately = true; _client.StoreAsset(baseAsset); System.Threading.Thread.Sleep(5000); //confirm the asset is now missing from the writeback cache Assert.IsNull(_client.DiskWriteBackCache.GetAsset(baseAsset.FullID.Guid)); } finally { Config.Settings.Instance.UnitTest_ThrowTimeout = false; Config.Settings.Instance.UnitTest_DeleteOldCacheFilesImmediately = false; } //we should now be able to get the asset from CF since it should've been written back //by the write back recovery code AssetBase cfAsset = _client.RequestAssetSync(baseAsset.FullID); CompareObjects comp = new CompareObjects(); comp.CompareStaticFields = false; comp.CompareStaticProperties = false; Assert.IsTrue(comp.Compare(baseAsset, cfAsset), comp.DifferencesString); CollectionAssert.AreEqual(baseAsset.Data, cfAsset.Data); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { public abstract class AbstractExternalCodeElement : AbstractCodeModelObject, ICodeElementContainer<AbstractExternalCodeElement>, EnvDTE.CodeElement, EnvDTE80.CodeElement2 { protected readonly ProjectId ProjectId; internal readonly SymbolKey SymbolKey; internal AbstractExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol) : base(state) { Debug.Assert(projectId != null); Debug.Assert(symbol != null); this.ProjectId = projectId; this.SymbolKey = symbol.GetSymbolKey(); } internal Compilation GetCompilation() { var project = this.State.Workspace.CurrentSolution.GetProject(this.ProjectId); if (project == null) { throw Exceptions.ThrowEFail(); } return project.GetCompilationAsync(CancellationToken.None).Result; } internal ISymbol LookupSymbol() { var symbol = CodeModelService.ResolveSymbol(this.State.Workspace, this.ProjectId, this.SymbolKey); if (symbol == null) { throw Exceptions.ThrowEFail(); } return symbol; } protected virtual EnvDTE.vsCMAccess GetAccess() { return CodeModelService.GetAccess(LookupSymbol()); } protected virtual string GetDocComment() { throw new NotImplementedException(); } protected virtual string GetFullName() { return CodeModelService.GetFullName(LookupSymbol()); } protected virtual bool GetIsShared() { var symbol = LookupSymbol(); return symbol.IsStatic; } protected virtual string GetName() { var symbol = LookupSymbol(); return symbol.Name; } protected virtual object GetParent() { var symbol = LookupSymbol(); if (symbol.Kind == SymbolKind.Namespace && ((INamespaceSymbol)symbol).IsGlobalNamespace) { // TODO: We should be returning the RootCodeModel object here. throw new NotImplementedException(); } if (symbol.ContainingType != null) { return CodeModelService.CreateCodeType(this.State, this.ProjectId, symbol.ContainingType); } else if (symbol.ContainingNamespace != null) { return CodeModelService.CreateExternalCodeElement(this.State, this.ProjectId, symbol.ContainingNamespace); } throw Exceptions.ThrowEFail(); } public EnvDTE.vsCMAccess Access { get { return GetAccess(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeElements Attributes { get { return EmptyCollection.Create(this.State, this); } } public virtual EnvDTE.CodeElements Children { get { throw new NotImplementedException(); } } EnvDTE.CodeElements ICodeElementContainer<AbstractExternalCodeElement>.GetCollection() { return Children; } protected virtual EnvDTE.CodeElements GetCollection() { return GetCollection<AbstractExternalCodeElement>(this.Parent); } public EnvDTE.CodeElements Collection { get { return GetCollection(); } } public string Comment { get { throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public string DocComment { get { return GetDocComment(); } set { throw Exceptions.ThrowEFail(); } } public object Parent { get { return GetParent(); } } public EnvDTE.TextPoint EndPoint { get { throw Exceptions.ThrowEFail(); } } public string FullName { get { return GetFullName(); } } public bool IsShared { get { return GetIsShared(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.TextPoint GetEndPoint(EnvDTE.vsCMPart part) { throw Exceptions.ThrowEFail(); } public EnvDTE.TextPoint GetStartPoint(EnvDTE.vsCMPart part) { throw Exceptions.ThrowEFail(); } public EnvDTE.vsCMInfoLocation InfoLocation { get { return EnvDTE.vsCMInfoLocation.vsCMInfoLocationExternal; } } public virtual bool IsCodeType { get { return false; } } public abstract EnvDTE.vsCMElement Kind { get; } public string Name { get { return GetName(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.ProjectItem ProjectItem { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.TextPoint StartPoint { get { throw Exceptions.ThrowEFail(); } } public string ExtenderCATID { get { throw new NotImplementedException(); } } protected virtual object GetExtenderNames() { throw Exceptions.ThrowENotImpl(); } public object ExtenderNames { get { return GetExtenderNames(); } } protected virtual object GetExtender(string name) { throw Exceptions.ThrowENotImpl(); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Required by interface")] public object get_Extender(string extenderName) { return GetExtender(extenderName); } public string ElementID { get { throw new NotImplementedException(); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { throw Exceptions.ThrowEFail(); } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { throw Exceptions.ThrowEFail(); } public void RenameSymbol(string newName) { throw Exceptions.ThrowEFail(); } public void RemoveParameter(object element) { throw Exceptions.ThrowEFail(); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Required by interface")] public string get_Prototype(int flags = 0) { return CodeModelService.GetPrototype(null, LookupSymbol(), (PrototypeFlags)flags); } } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Class used to represent the browser process aspects of a browser window. The /// methods of this class can only be called in the browser process. They may be /// called on any thread in that process unless otherwise indicated in the /// comments. /// </summary> public sealed unsafe partial class CefBrowserHost { /// <summary> /// Create a new browser window using the window parameters specified by /// |windowInfo|. All values will be copied internally and the actual window /// will be created on the UI thread. If |request_context| is empty the /// global request context will be used. This method can be called on any /// browser process thread and will not block. /// </summary> public static int CreateBrowser(cef_window_info_t* windowInfo, cef_client_t* client, cef_string_t* url, cef_browser_settings_t* settings, cef_request_context_t* request_context) { throw new NotImplementedException(); // TODO: CefBrowserHost.CreateBrowser } /// <summary> /// Create a new browser window using the window parameters specified by /// |windowInfo|. If |request_context| is empty the global request context /// will be used. This method can only be called on the browser process UI /// thread. /// </summary> public static cef_browser_t* CreateBrowserSync(cef_window_info_t* windowInfo, cef_client_t* client, cef_string_t* url, cef_browser_settings_t* settings, cef_request_context_t* request_context) { throw new NotImplementedException(); // TODO: CefBrowserHost.CreateBrowserSync } /// <summary> /// Returns the hosted browser object. /// </summary> public cef_browser_t* GetBrowser() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetBrowser } /// <summary> /// Request that the browser close. The JavaScript 'onbeforeunload' event will /// be fired. If |force_close| is false the event handler, if any, will be /// allowed to prompt the user and the user can optionally cancel the close. /// If |force_close| is true the prompt will not be displayed and the close /// will proceed. Results in a call to CefLifeSpanHandler::DoClose() if the /// event handler allows the close or if |force_close| is true. See /// CefLifeSpanHandler::DoClose() documentation for additional usage /// information. /// </summary> public void CloseBrowser(int force_close) { throw new NotImplementedException(); // TODO: CefBrowserHost.CloseBrowser } /// <summary> /// Helper for closing a browser. Call this method from the top-level window /// close handler. Internally this calls CloseBrowser(false) if the close has /// not yet been initiated. This method returns false while the close is /// pending and true after the close has completed. See CloseBrowser() and /// CefLifeSpanHandler::DoClose() documentation for additional usage /// information. This method must be called on the browser process UI thread. /// </summary> public int TryCloseBrowser() { throw new NotImplementedException(); // TODO: CefBrowserHost.TryCloseBrowser } /// <summary> /// Set whether the browser is focused. /// </summary> public void SetFocus(int focus) { throw new NotImplementedException(); // TODO: CefBrowserHost.SetFocus } /// <summary> /// Retrieve the window handle for this browser. If this browser is wrapped in /// a CefBrowserView this method should be called on the browser process UI /// thread and it will return the handle for the top-level native window. /// </summary> public IntPtr GetWindowHandle() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetWindowHandle } /// <summary> /// Retrieve the window handle of the browser that opened this browser. Will /// return NULL for non-popup windows or if this browser is wrapped in a /// CefBrowserView. This method can be used in combination with custom handling /// of modal windows. /// </summary> public IntPtr GetOpenerWindowHandle() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetOpenerWindowHandle } /// <summary> /// Returns true if this browser is wrapped in a CefBrowserView. /// </summary> public int HasView() { throw new NotImplementedException(); // TODO: CefBrowserHost.HasView } /// <summary> /// Returns the client for this browser. /// </summary> public cef_client_t* GetClient() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetClient } /// <summary> /// Returns the request context for this browser. /// </summary> public cef_request_context_t* GetRequestContext() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetRequestContext } /// <summary> /// Get the current zoom level. The default zoom level is 0.0. This method can /// only be called on the UI thread. /// </summary> public double GetZoomLevel() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetZoomLevel } /// <summary> /// Change the zoom level to the specified value. Specify 0.0 to reset the /// zoom level. If called on the UI thread the change will be applied /// immediately. Otherwise, the change will be applied asynchronously on the /// UI thread. /// </summary> public void SetZoomLevel(double zoomLevel) { throw new NotImplementedException(); // TODO: CefBrowserHost.SetZoomLevel } /// <summary> /// Call to run a file chooser dialog. Only a single file chooser dialog may be /// pending at any given time. |mode| represents the type of dialog to display. /// |title| to the title to be used for the dialog and may be empty to show the /// default title ("Open" or "Save" depending on the mode). |default_file_path| /// is the path with optional directory and/or file name component that will be /// initially selected in the dialog. |accept_filters| are used to restrict the /// selectable file types and may any combination of (a) valid lower-cased MIME /// types (e.g. "text/*" or "image/*"), (b) individual file extensions (e.g. /// ".txt" or ".png"), or (c) combined description and file extension delimited /// using "|" and ";" (e.g. "Image Types|.png;.gif;.jpg"). /// |selected_accept_filter| is the 0-based index of the filter that will be /// selected by default. |callback| will be executed after the dialog is /// dismissed or immediately if another dialog is already pending. The dialog /// will be initiated asynchronously on the UI thread. /// </summary> public void RunFileDialog(CefFileDialogMode mode, cef_string_t* title, cef_string_t* default_file_path, cef_string_list* accept_filters, int selected_accept_filter, cef_run_file_dialog_callback_t* callback) { throw new NotImplementedException(); // TODO: CefBrowserHost.RunFileDialog } /// <summary> /// Download the file at |url| using CefDownloadHandler. /// </summary> public void StartDownload(cef_string_t* url) { throw new NotImplementedException(); // TODO: CefBrowserHost.StartDownload } /// <summary> /// Download |image_url| and execute |callback| on completion with the images /// received from the renderer. If |is_favicon| is true then cookies are not /// sent and not accepted during download. Images with density independent /// pixel (DIP) sizes larger than |max_image_size| are filtered out from the /// image results. Versions of the image at different scale factors may be /// downloaded up to the maximum scale factor supported by the system. If there /// are no image results <= |max_image_size| then the smallest image is resized /// to |max_image_size| and is the only result. A |max_image_size| of 0 means /// unlimited. If |bypass_cache| is true then |image_url| is requested from the /// server even if it is present in the browser cache. /// </summary> public void DownloadImage(cef_string_t* image_url, int is_favicon, uint max_image_size, int bypass_cache, cef_download_image_callback_t* callback) { throw new NotImplementedException(); // TODO: CefBrowserHost.DownloadImage } /// <summary> /// Print the current browser contents. /// </summary> public void Print() { throw new NotImplementedException(); // TODO: CefBrowserHost.Print } /// <summary> /// Print the current browser contents to the PDF file specified by |path| and /// execute |callback| on completion. The caller is responsible for deleting /// |path| when done. For PDF printing to work on Linux you must implement the /// CefPrintHandler::GetPdfPaperSize method. /// </summary> public void PrintToPDF(cef_string_t* path, cef_pdf_print_settings_t* settings, cef_pdf_print_callback_t* callback) { throw new NotImplementedException(); // TODO: CefBrowserHost.PrintToPDF } /// <summary> /// Search for |searchText|. |identifier| can be used to have multiple searches /// running simultaniously. |forward| indicates whether to search forward or /// backward within the page. |matchCase| indicates whether the search should /// be case-sensitive. |findNext| indicates whether this is the first request /// or a follow-up. The CefFindHandler instance, if any, returned via /// CefClient::GetFindHandler will be called to report find results. /// </summary> public void Find(int identifier, cef_string_t* searchText, int forward, int matchCase, int findNext) { throw new NotImplementedException(); // TODO: CefBrowserHost.Find } /// <summary> /// Cancel all searches that are currently going on. /// </summary> public void StopFinding(int clearSelection) { throw new NotImplementedException(); // TODO: CefBrowserHost.StopFinding } /// <summary> /// Open developer tools (DevTools) in its own browser. The DevTools browser /// will remain associated with this browser. If the DevTools browser is /// already open then it will be focused, in which case the |windowInfo|, /// |client| and |settings| parameters will be ignored. If |inspect_element_at| /// is non-empty then the element at the specified (x,y) location will be /// inspected. The |windowInfo| parameter will be ignored if this browser is /// wrapped in a CefBrowserView. /// </summary> public void ShowDevTools(cef_window_info_t* windowInfo, cef_client_t* client, cef_browser_settings_t* settings, cef_point_t* inspect_element_at) { throw new NotImplementedException(); // TODO: CefBrowserHost.ShowDevTools } /// <summary> /// Explicitly close the associated DevTools browser, if any. /// </summary> public void CloseDevTools() { throw new NotImplementedException(); // TODO: CefBrowserHost.CloseDevTools } /// <summary> /// Returns true if this browser currently has an associated DevTools browser. /// Must be called on the browser process UI thread. /// </summary> public int HasDevTools() { throw new NotImplementedException(); // TODO: CefBrowserHost.HasDevTools } /// <summary> /// Retrieve a snapshot of current navigation entries as values sent to the /// specified visitor. If |current_only| is true only the current navigation /// entry will be sent, otherwise all navigation entries will be sent. /// </summary> public void GetNavigationEntries(cef_navigation_entry_visitor_t* visitor, int current_only) { throw new NotImplementedException(); // TODO: CefBrowserHost.GetNavigationEntries } /// <summary> /// Set whether mouse cursor change is disabled. /// </summary> public void SetMouseCursorChangeDisabled(int disabled) { throw new NotImplementedException(); // TODO: CefBrowserHost.SetMouseCursorChangeDisabled } /// <summary> /// Returns true if mouse cursor change is disabled. /// </summary> public int IsMouseCursorChangeDisabled() { throw new NotImplementedException(); // TODO: CefBrowserHost.IsMouseCursorChangeDisabled } /// <summary> /// If a misspelled word is currently selected in an editable node calling /// this method will replace it with the specified |word|. /// </summary> public void ReplaceMisspelling(cef_string_t* word) { throw new NotImplementedException(); // TODO: CefBrowserHost.ReplaceMisspelling } /// <summary> /// Add the specified |word| to the spelling dictionary. /// </summary> public void AddWordToDictionary(cef_string_t* word) { throw new NotImplementedException(); // TODO: CefBrowserHost.AddWordToDictionary } /// <summary> /// Returns true if window rendering is disabled. /// </summary> public int IsWindowRenderingDisabled() { throw new NotImplementedException(); // TODO: CefBrowserHost.IsWindowRenderingDisabled } /// <summary> /// Notify the browser that the widget has been resized. The browser will first /// call CefRenderHandler::GetViewRect to get the new size and then call /// CefRenderHandler::OnPaint asynchronously with the updated regions. This /// method is only used when window rendering is disabled. /// </summary> public void WasResized() { throw new NotImplementedException(); // TODO: CefBrowserHost.WasResized } /// <summary> /// Notify the browser that it has been hidden or shown. Layouting and /// CefRenderHandler::OnPaint notification will stop when the browser is /// hidden. This method is only used when window rendering is disabled. /// </summary> public void WasHidden(int hidden) { throw new NotImplementedException(); // TODO: CefBrowserHost.WasHidden } /// <summary> /// Send a notification to the browser that the screen info has changed. The /// browser will then call CefRenderHandler::GetScreenInfo to update the /// screen information with the new values. This simulates moving the webview /// window from one display to another, or changing the properties of the /// current display. This method is only used when window rendering is /// disabled. /// </summary> public void NotifyScreenInfoChanged() { throw new NotImplementedException(); // TODO: CefBrowserHost.NotifyScreenInfoChanged } /// <summary> /// Invalidate the view. The browser will call CefRenderHandler::OnPaint /// asynchronously. This method is only used when window rendering is /// disabled. /// </summary> public void Invalidate(CefPaintElementType type) { throw new NotImplementedException(); // TODO: CefBrowserHost.Invalidate } /// <summary> /// Send a key event to the browser. /// </summary> public void SendKeyEvent(cef_key_event_t* @event) { throw new NotImplementedException(); // TODO: CefBrowserHost.SendKeyEvent } /// <summary> /// Send a mouse click event to the browser. The |x| and |y| coordinates are /// relative to the upper-left corner of the view. /// </summary> public void SendMouseClickEvent(cef_mouse_event_t* @event, CefMouseButtonType type, int mouseUp, int clickCount) { throw new NotImplementedException(); // TODO: CefBrowserHost.SendMouseClickEvent } /// <summary> /// Send a mouse move event to the browser. The |x| and |y| coordinates are /// relative to the upper-left corner of the view. /// </summary> public void SendMouseMoveEvent(cef_mouse_event_t* @event, int mouseLeave) { throw new NotImplementedException(); // TODO: CefBrowserHost.SendMouseMoveEvent } /// <summary> /// Send a mouse wheel event to the browser. The |x| and |y| coordinates are /// relative to the upper-left corner of the view. The |deltaX| and |deltaY| /// values represent the movement delta in the X and Y directions respectively. /// In order to scroll inside select popups with window rendering disabled /// CefRenderHandler::GetScreenPoint should be implemented properly. /// </summary> public void SendMouseWheelEvent(cef_mouse_event_t* @event, int deltaX, int deltaY) { throw new NotImplementedException(); // TODO: CefBrowserHost.SendMouseWheelEvent } /// <summary> /// Send a focus event to the browser. /// </summary> public void SendFocusEvent(int setFocus) { throw new NotImplementedException(); // TODO: CefBrowserHost.SendFocusEvent } /// <summary> /// Send a capture lost event to the browser. /// </summary> public void SendCaptureLostEvent() { throw new NotImplementedException(); // TODO: CefBrowserHost.SendCaptureLostEvent } /// <summary> /// Notify the browser that the window hosting it is about to be moved or /// resized. This method is only used on Windows and Linux. /// </summary> public void NotifyMoveOrResizeStarted() { throw new NotImplementedException(); // TODO: CefBrowserHost.NotifyMoveOrResizeStarted } /// <summary> /// Returns the maximum rate in frames per second (fps) that CefRenderHandler:: /// OnPaint will be called for a windowless browser. The actual fps may be /// lower if the browser cannot generate frames at the requested rate. The /// minimum value is 1 and the maximum value is 60 (default 30). This method /// can only be called on the UI thread. /// </summary> public int GetWindowlessFrameRate() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetWindowlessFrameRate } /// <summary> /// Set the maximum rate in frames per second (fps) that CefRenderHandler:: /// OnPaint will be called for a windowless browser. The actual fps may be /// lower if the browser cannot generate frames at the requested rate. The /// minimum value is 1 and the maximum value is 60 (default 30). Can also be /// set at browser creation via CefBrowserSettings.windowless_frame_rate. /// </summary> public void SetWindowlessFrameRate(int frame_rate) { throw new NotImplementedException(); // TODO: CefBrowserHost.SetWindowlessFrameRate } /// <summary> /// Begins a new composition or updates the existing composition. Blink has a /// special node (a composition node) that allows the input method to change /// text without affecting other DOM nodes. |text| is the optional text that /// will be inserted into the composition node. |underlines| is an optional set /// of ranges that will be underlined in the resulting text. /// |replacement_range| is an optional range of the existing text that will be /// replaced. |selection_range| is an optional range of the resulting text that /// will be selected after insertion or replacement. The |replacement_range| /// value is only used on OS X. /// This method may be called multiple times as the composition changes. When /// the client is done making changes the composition should either be canceled /// or completed. To cancel the composition call ImeCancelComposition. To /// complete the composition call either ImeCommitText or /// ImeFinishComposingText. Completion is usually signaled when: /// A. The client receives a WM_IME_COMPOSITION message with a GCS_RESULTSTR /// flag (on Windows), or; /// B. The client receives a "commit" signal of GtkIMContext (on Linux), or; /// C. insertText of NSTextInput is called (on Mac). /// This method is only used when window rendering is disabled. /// </summary> public void ImeSetComposition(cef_string_t* text, UIntPtr underlinesCount, cef_composition_underline_t* underlines, cef_range_t* replacement_range, cef_range_t* selection_range) { throw new NotImplementedException(); // TODO: CefBrowserHost.ImeSetComposition } /// <summary> /// Completes the existing composition by optionally inserting the specified /// |text| into the composition node. |replacement_range| is an optional range /// of the existing text that will be replaced. |relative_cursor_pos| is where /// the cursor will be positioned relative to the current cursor position. See /// comments on ImeSetComposition for usage. The |replacement_range| and /// |relative_cursor_pos| values are only used on OS X. /// This method is only used when window rendering is disabled. /// </summary> public void ImeCommitText(cef_string_t* text, cef_range_t* replacement_range, int relative_cursor_pos) { throw new NotImplementedException(); // TODO: CefBrowserHost.ImeCommitText } /// <summary> /// Completes the existing composition by applying the current composition node /// contents. If |keep_selection| is false the current selection, if any, will /// be discarded. See comments on ImeSetComposition for usage. /// This method is only used when window rendering is disabled. /// </summary> public void ImeFinishComposingText(int keep_selection) { throw new NotImplementedException(); // TODO: CefBrowserHost.ImeFinishComposingText } /// <summary> /// Cancels the existing composition and discards the composition node /// contents without applying them. See comments on ImeSetComposition for /// usage. /// This method is only used when window rendering is disabled. /// </summary> public void ImeCancelComposition() { throw new NotImplementedException(); // TODO: CefBrowserHost.ImeCancelComposition } /// <summary> /// Call this method when the user drags the mouse into the web view (before /// calling DragTargetDragOver/DragTargetLeave/DragTargetDrop). /// |drag_data| should not contain file contents as this type of data is not /// allowed to be dragged into the web view. File contents can be removed using /// CefDragData::ResetFileContents (for example, if |drag_data| comes from /// CefRenderHandler::StartDragging). /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDragEnter(cef_drag_data_t* drag_data, cef_mouse_event_t* @event, CefDragOperationsMask allowed_ops) { throw new NotImplementedException(); // TODO: CefBrowserHost.DragTargetDragEnter } /// <summary> /// Call this method each time the mouse is moved across the web view during /// a drag operation (after calling DragTargetDragEnter and before calling /// DragTargetDragLeave/DragTargetDrop). /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDragOver(cef_mouse_event_t* @event, CefDragOperationsMask allowed_ops) { throw new NotImplementedException(); // TODO: CefBrowserHost.DragTargetDragOver } /// <summary> /// Call this method when the user drags the mouse out of the web view (after /// calling DragTargetDragEnter). /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDragLeave() { throw new NotImplementedException(); // TODO: CefBrowserHost.DragTargetDragLeave } /// <summary> /// Call this method when the user completes the drag operation by dropping /// the object onto the web view (after calling DragTargetDragEnter). /// The object being dropped is |drag_data|, given as an argument to /// the previous DragTargetDragEnter call. /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDrop(cef_mouse_event_t* @event) { throw new NotImplementedException(); // TODO: CefBrowserHost.DragTargetDrop } /// <summary> /// Call this method when the drag operation started by a /// CefRenderHandler::StartDragging call has ended either in a drop or /// by being cancelled. |x| and |y| are mouse coordinates relative to the /// upper-left corner of the view. If the web view is both the drag source /// and the drag target then all DragTarget* methods should be called before /// DragSource* mthods. /// This method is only used when window rendering is disabled. /// </summary> public void DragSourceEndedAt(int x, int y, CefDragOperationsMask op) { throw new NotImplementedException(); // TODO: CefBrowserHost.DragSourceEndedAt } /// <summary> /// Call this method when the drag operation started by a /// CefRenderHandler::StartDragging call has completed. This method may be /// called immediately without first calling DragSourceEndedAt to cancel a /// drag operation. If the web view is both the drag source and the drag /// target then all DragTarget* methods should be called before DragSource* /// mthods. /// This method is only used when window rendering is disabled. /// </summary> public void DragSourceSystemDragEnded() { throw new NotImplementedException(); // TODO: CefBrowserHost.DragSourceSystemDragEnded } /// <summary> /// Returns the current visible navigation entry for this browser. This method /// can only be called on the UI thread. /// </summary> public cef_navigation_entry_t* GetVisibleNavigationEntry() { throw new NotImplementedException(); // TODO: CefBrowserHost.GetVisibleNavigationEntry } } }
// 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 CompareLessThanOrEqualSingle() { var test = new SimpleBinaryOpTest__CompareLessThanOrEqualSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareLessThanOrEqualSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareLessThanOrEqualSingle testClass) { var result = Sse.CompareLessThanOrEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareLessThanOrEqualSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareLessThanOrEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareLessThanOrEqualSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__CompareLessThanOrEqualSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareLessThanOrEqual( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareLessThanOrEqual( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareLessThanOrEqual( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareLessThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareLessThanOrEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareLessThanOrEqual( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareLessThanOrEqualSingle(); var result = Sse.CompareLessThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareLessThanOrEqualSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareLessThanOrEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareLessThanOrEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareLessThanOrEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareLessThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareLessThanOrEqual( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] <= right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != ((left[i] <= right[i]) ? -1 : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareLessThanOrEqual)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using Orleans.Runtime; using System; using System.Runtime.Serialization; namespace Orleans.Transactions { /// <summary> /// Base class for all transaction exceptions /// </summary> [Serializable] public class OrleansTransactionException : OrleansException { public OrleansTransactionException() : base("Orleans transaction error.") { } public OrleansTransactionException(string message) : base(message) { } public OrleansTransactionException(string message, Exception innerException) : base(message, innerException) { } protected OrleansTransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Orleans transactions are disabled. /// </summary> [Serializable] public class OrleansTransactionsDisabledException : OrleansTransactionException { public OrleansTransactionsDisabledException() : base("Orleans transactions have not been enabled. Transactions are disabled by default and must be configured to be used.") { } public OrleansTransactionsDisabledException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the runtime was unable to start a transaction. /// </summary> [Serializable] public class OrleansStartTransactionFailedException : OrleansTransactionException { public OrleansStartTransactionFailedException(Exception innerException) : base("Failed to start transaction. Check InnerException for details", innerException) { } public OrleansStartTransactionFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that transaction runtime is overloaded /// </summary> [Serializable] public class OrleansTransactionOverloadException : OrleansTransactionException { public OrleansTransactionOverloadException() : base("Transaction is overloaded on current silo, please try again later.") { } } /// <summary> /// Signifies that the runtime is unable to determine whether a transaction /// has committed. /// </summary> [Serializable] public class OrleansTransactionInDoubtException : OrleansTransactionException { public string TransactionId { get; private set; } public OrleansTransactionInDoubtException(string transactionId) : base(string.Format("Transaction {0} is InDoubt", transactionId)) { this.TransactionId = transactionId; } public OrleansTransactionInDoubtException(string transactionId, Exception exc) : base(string.Format("Transaction {0} is InDoubt", transactionId), exc) { this.TransactionId = transactionId; } public OrleansTransactionInDoubtException(string transactionId, string msg, Exception innerException) : base(string.Format("Transaction {0} is InDoubt: {1}", transactionId, msg), innerException) { this.TransactionId = transactionId; } public OrleansTransactionInDoubtException(SerializationInfo info, StreamingContext context) : base(info, context) { this.TransactionId = info.GetString(nameof(this.TransactionId)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(this.TransactionId), this.TransactionId); } } /// <summary> /// Signifies that the executing transaction has aborted. /// </summary> [Serializable] public class OrleansTransactionAbortedException : OrleansTransactionException { /// <summary> /// The unique identifier of the aborted transaction. /// </summary> public string TransactionId { get; private set; } public OrleansTransactionAbortedException(string transactionId, string msg, Exception innerException) : base(msg, innerException) { this.TransactionId = transactionId; } public OrleansTransactionAbortedException(string transactionId, string msg) : base(msg) { this.TransactionId = transactionId; } public OrleansTransactionAbortedException(string transactionId, Exception innerException) : base($"Transaction {transactionId} Aborted because of an unhandled exception in a grain method call. See InnerException for details.", innerException) { TransactionId = transactionId; } public OrleansTransactionAbortedException(SerializationInfo info, StreamingContext context) : base(info, context) { this.TransactionId = info.GetString(nameof(this.TransactionId)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(this.TransactionId), this.TransactionId); } } /// <summary> /// Signifies that the executing transaction has aborted because a dependent transaction aborted. /// </summary> [Serializable] public class OrleansCascadingAbortException : OrleansTransactionTransientFailureException { public string DependentTransactionId { get; private set; } public OrleansCascadingAbortException(string transactionId, string dependentId) : base(transactionId, string.Format("Transaction {0} aborted because its dependent transaction {1} aborted", transactionId, dependentId)) { this.DependentTransactionId = dependentId; } public OrleansCascadingAbortException(string transactionId) : base(transactionId, string.Format("Transaction {0} aborted because a dependent transaction aborted", transactionId)) { } public OrleansCascadingAbortException(string transactionId, Exception innerException) : base(transactionId, string.Format("Transaction {0} aborted because a dependent transaction aborted", transactionId), innerException) { } public OrleansCascadingAbortException(SerializationInfo info, StreamingContext context) : base(info, context) { this.DependentTransactionId = info.GetString(nameof(this.DependentTransactionId)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(this.DependentTransactionId), this.DependentTransactionId); } } /// <summary> /// Signifies that the executing transaction has aborted because a method did not await all its pending calls. /// </summary> [Serializable] public class OrleansOrphanCallException : OrleansTransactionAbortedException { public OrleansOrphanCallException(string transactionId, int pendingCalls) : base( transactionId, $"Transaction {transactionId} aborted because method did not await all its outstanding calls ({pendingCalls})") { } public OrleansOrphanCallException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing read-only transaction has aborted because it attempted to write to a grain. /// </summary> [Serializable] public class OrleansReadOnlyViolatedException : OrleansTransactionAbortedException { public OrleansReadOnlyViolatedException(string transactionId) : base(transactionId, string.Format("Transaction {0} aborted because it attempted to write a grain", transactionId)) { } public OrleansReadOnlyViolatedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class OrleansTransactionServiceNotAvailableException : OrleansTransactionException { public OrleansTransactionServiceNotAvailableException() : base("Transaction service not available") { } public OrleansTransactionServiceNotAvailableException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because its execution lock was broken /// </summary> [Serializable] public class OrleansBrokenTransactionLockException : OrleansTransactionTransientFailureException { public OrleansBrokenTransactionLockException(string transactionId, string situation) : base(transactionId, $"Transaction {transactionId} aborted because a broken lock was detected, {situation}") { } public OrleansBrokenTransactionLockException(string transactionId, string situation, Exception innerException) : base(transactionId, $"Transaction {transactionId} aborted because a broken lock was detected, {situation}", innerException) { } public OrleansBrokenTransactionLockException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because it could not upgrade some lock /// </summary> [Serializable] public class OrleansTransactionLockUpgradeException : OrleansTransactionTransientFailureException { public OrleansTransactionLockUpgradeException(string transactionId) : base(transactionId, $"Transaction {transactionId} Aborted because it could not upgrade a lock, because of a higher-priority conflicting transaction") { } public OrleansTransactionLockUpgradeException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because the TM did not receive all prepared messages in time /// </summary> [Serializable] public class OrleansTransactionPrepareTimeoutException : OrleansTransactionTransientFailureException { public OrleansTransactionPrepareTimeoutException(string transactionId, Exception innerException) : base(transactionId, $"Transaction {transactionId} Aborted because the prepare phase did not complete within the timeout limit", innerException) { } public OrleansTransactionPrepareTimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Signifies that the executing transaction has aborted because some possibly transient problem, such as internal /// timeouts for locks or protocol responses, or speculation failures. /// </summary> [Serializable] public class OrleansTransactionTransientFailureException : OrleansTransactionAbortedException { public OrleansTransactionTransientFailureException(string transactionId, string msg, Exception innerException) : base(transactionId, msg, innerException) { } public OrleansTransactionTransientFailureException(string transactionId, string msg) : base(transactionId, msg) { } public OrleansTransactionTransientFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PatternMatching { /// <summary> /// The pattern matcher is thread-safe. However, it maintains an internal cache of /// information as it is used. Therefore, you should not keep it around forever and should get /// and release the matcher appropriately once you no longer need it. /// Also, while the pattern matcher is culture aware, it uses the culture specified in the /// constructor. /// </summary> internal sealed partial class PatternMatcher : IDisposable { public const int NoBonus = 0; public const int CamelCaseContiguousBonus = 1; public const int CamelCaseMatchesFromStartBonus = 2; public const int CamelCaseMaxWeight = CamelCaseContiguousBonus + CamelCaseMatchesFromStartBonus; private static readonly char[] s_dotCharacterArray = { '.' }; private readonly object _gate = new object(); private readonly bool _allowFuzzyMatching; private readonly bool _invalidPattern; private readonly PatternSegment _fullPatternSegment; private readonly PatternSegment[] _dotSeparatedPatternSegments; private readonly Dictionary<string, StringBreaks> _stringToWordSpans = new Dictionary<string, StringBreaks>(); private static readonly Func<string, StringBreaks> _breakIntoWordSpans = StringBreaker.BreakIntoWordParts; // PERF: Cache the culture's compareInfo to avoid the overhead of asking for them repeatedly in inner loops private readonly CompareInfo _compareInfo; /// <summary> /// Construct a new PatternMatcher using the calling thread's culture for string searching and comparison. /// </summary> public PatternMatcher( string pattern, bool verbatimIdentifierPrefixIsWordCharacter = false, bool allowFuzzyMatching = false) : this(pattern, CultureInfo.CurrentCulture, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching) { } /// <summary> /// Construct a new PatternMatcher using the specified culture. /// </summary> /// <param name="pattern">The pattern to make the pattern matcher for.</param> /// <param name="culture">The culture to use for string searching and comparison.</param> /// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param> /// <param name="allowFuzzyMatching">Whether or not close matches should count as matches.</param> public PatternMatcher( string pattern, CultureInfo culture, bool verbatimIdentifierPrefixIsWordCharacter, bool allowFuzzyMatching) { pattern = pattern.Trim(); _compareInfo = culture.CompareInfo; _allowFuzzyMatching = allowFuzzyMatching; _fullPatternSegment = new PatternSegment(pattern, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching); if (pattern.IndexOf('.') < 0) { // PERF: Avoid string.Split allocations when the pattern doesn't contain a dot. _dotSeparatedPatternSegments = pattern.Length > 0 ? new PatternSegment[1] { _fullPatternSegment } : Array.Empty<PatternSegment>(); } else { _dotSeparatedPatternSegments = pattern.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries) .Select(text => new PatternSegment(text.Trim(), verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching)) .ToArray(); } _invalidPattern = _dotSeparatedPatternSegments.Length == 0 || _dotSeparatedPatternSegments.Any(s => s.IsInvalid); } public void Dispose() { _fullPatternSegment.Dispose(); foreach (var segment in _dotSeparatedPatternSegments) { segment.Dispose(); } } public bool IsDottedPattern => _dotSeparatedPatternSegments.Length > 1; private bool SkipMatch(string candidate) { return _invalidPattern || string.IsNullOrWhiteSpace(candidate); } public ImmutableArray<PatternMatch> GetMatches(string candidate) => GetMatches(candidate, includeMatchSpans: false); /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <param name="candidate">The word being tested.</param> /// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param> /// <returns>If this was a match, a set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public ImmutableArray<PatternMatch> GetMatches(string candidate, bool includeMatchSpans) { if (SkipMatch(candidate)) { return ImmutableArray<PatternMatch>.Empty; } var result = MatchPatternSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: true); if (!result.IsEmpty) { return result; } return MatchPatternSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: false); } public ImmutableArray<PatternMatch> GetMatchesForLastSegmentOfPattern(string candidate) { if (SkipMatch(candidate)) { return ImmutableArray<PatternMatch>.Empty; } var result = MatchPatternSegment(candidate, includeMatchSpans: false, patternSegment: _dotSeparatedPatternSegments.Last(), fuzzyMatch: false); if (!result.IsEmpty) { return result; } return MatchPatternSegment(candidate, includeMatchSpans: false, patternSegment: _dotSeparatedPatternSegments.Last(), fuzzyMatch: true); } public PatternMatches GetMatches(string candidate, string dottedContainer) => GetMatches(candidate, dottedContainer, includeMatchSpans: false); /// <summary> /// Matches a pattern against a candidate, and an optional dotted container for the /// candidate. If the container is provided, and the pattern itself contains dots, then /// the pattern will be tested against the candidate and container. Specifically, /// the part of the pattern after the last dot will be tested against the candidate. If /// a match occurs there, then the remaining dot-separated portions of the pattern will /// be tested against every successive portion of the container from right to left. /// /// i.e. if you have a pattern of "Con.WL" and the candidate is "WriteLine" with a /// dotted container of "System.Console", then "WL" will be tested against "WriteLine". /// With a match found there, "Con" will then be tested against "Console". /// </summary> public PatternMatches GetMatches( string candidate, string dottedContainer, bool includeMatchSpans) { var result = GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: false); if (!result.IsEmpty) { return result; } return GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: true); } private PatternMatches GetMatches( string candidate, string dottedContainer, bool includeMatchSpans, bool fuzzyMatch) { if (fuzzyMatch && !_allowFuzzyMatching) { return PatternMatches.Empty; } if (SkipMatch(candidate)) { return PatternMatches.Empty; } // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. var candidateMatch = MatchPatternSegment(candidate, includeMatchSpans, _dotSeparatedPatternSegments.Last(), fuzzyMatch); if (candidateMatch.IsDefaultOrEmpty) { return PatternMatches.Empty; } dottedContainer = dottedContainer ?? string.Empty; var containerParts = dottedContainer.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries); // -1 because the last part was checked against the name, and only the rest // of the parts are checked against the container. var relevantDotSeparatedSegmentLength = _dotSeparatedPatternSegments.Length - 1; if (relevantDotSeparatedSegmentLength > containerParts.Length) { // There weren't enough container parts to match against the pattern parts. // So this definitely doesn't match. return PatternMatches.Empty; } // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. var containerMatches = ArrayBuilder<PatternMatch>.GetInstance(); try { // Don't need to check the last segment. We did that as the very first bail out step. for (int i = 0, j = containerParts.Length - relevantDotSeparatedSegmentLength; i < relevantDotSeparatedSegmentLength; i++, j++) { var segment = _dotSeparatedPatternSegments[i]; var containerName = containerParts[j]; var containerMatch = MatchPatternSegment(containerName, includeMatchSpans, segment, fuzzyMatch); if (containerMatch.IsDefaultOrEmpty) { // This container didn't match the pattern piece. So there's no match at all. return PatternMatches.Empty; } containerMatches.AddRange(containerMatch); } // Success, this symbol's full name matched against the dotted name the user was asking // about. return new PatternMatches(candidateMatch, containerMatches.ToImmutable()); } finally { containerMatches.Free(); } } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <remarks> /// PERF: This is slightly faster and uses less memory than <see cref="GetMatches(string, bool)"/> /// so, unless you need to know the full set of matches, use this version. /// </remarks> /// <param name="candidate">The word being tested.</param> /// <param name="inludeMatchSpans">Whether or not the matched spans should be included with results</param> /// <returns>If this was a match, the first element of the set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public PatternMatch? GetFirstMatch(string candidate, bool inludeMatchSpans = false) { if (SkipMatch(candidate)) { return null; } return MatchPatternSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out _, fuzzyMatch: false) ?? MatchPatternSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out _, fuzzyMatch: true); } private StringBreaks GetWordSpans(string word) { lock (_gate) { return _stringToWordSpans.GetOrAdd(word, _breakIntoWordSpans); } } internal PatternMatch? MatchSingleWordPattern_ForTestingOnly(string candidate) { return MatchPatternChunk(candidate, includeMatchSpans: true, patternChunk: _fullPatternSegment.TotalTextChunk, punctuationStripped: false, fuzzyMatch: false); } private static bool ContainsUpperCaseLetter(string pattern) { // Expansion of "foreach(char ch in pattern)" to avoid a CharEnumerator allocation for (int i = 0; i < pattern.Length; i++) { if (char.IsUpper(pattern[i])) { return true; } } return false; } private PatternMatch? MatchPatternChunk( string candidate, bool includeMatchSpans, TextChunk patternChunk, bool punctuationStripped, bool fuzzyMatch) { int caseInsensitiveIndex = _compareInfo.IndexOf(candidate, patternChunk.Text, CompareOptions.IgnoreCase); if (caseInsensitiveIndex == 0) { if (patternChunk.Text.Length == candidate.Length) { // a) Check if the part matches the candidate entirely, in an case insensitive or // sensitive manner. If it does, return that there was an exact match. return new PatternMatch( PatternMatchKind.Exact, punctuationStripped, isCaseSensitive: candidate == patternChunk.Text, matchedSpan: GetMatchedSpan(includeMatchSpans, 0, candidate.Length)); } else { // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive // manner. If it does, return that there was a prefix match. return new PatternMatch( PatternMatchKind.Prefix, punctuationStripped, isCaseSensitive: _compareInfo.IsPrefix(candidate, patternChunk.Text), matchedSpan: GetMatchedSpan(includeMatchSpans, 0, patternChunk.Text.Length)); } } var isLowercase = !ContainsUpperCaseLetter(patternChunk.Text); if (isLowercase) { if (caseInsensitiveIndex > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring // match. // // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). // // Also, if we matched at location right after punctuation, then this is a good // substring match. i.e. if the user is testing mybutton against _myButton // then this should hit. As we really are finding the match at the beginning of // a word. if (char.IsPunctuation(candidate[caseInsensitiveIndex - 1]) || char.IsPunctuation(patternChunk.Text[0])) { return new PatternMatch( PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: PartStartsWith( candidate, new TextSpan(caseInsensitiveIndex, patternChunk.Text.Length), patternChunk.Text, CompareOptions.None), matchedSpan: GetMatchedSpan(includeMatchSpans, caseInsensitiveIndex, patternChunk.Text.Length)); } var wordSpans = GetWordSpans(candidate); for (int i = 0; i < wordSpans.Count; i++) { var span = wordSpans[i]; if (PartStartsWith(candidate, span, patternChunk.Text, CompareOptions.IgnoreCase)) { return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: PartStartsWith(candidate, span, patternChunk.Text, CompareOptions.None), matchedSpan: GetMatchedSpan(includeMatchSpans, span.Start, patternChunk.Text.Length)); } } } } else { // d) If the part was not entirely lowercase, then check if it is contained in the // candidate in a case *sensitive* manner. If so, return that there was a substring // match. var caseSensitiveIndex = _compareInfo.IndexOf(candidate, patternChunk.Text); if (caseSensitiveIndex > 0) { return new PatternMatch( PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: true, matchedSpan: GetMatchedSpan(includeMatchSpans, caseSensitiveIndex, patternChunk.Text.Length)); } } var match = TryCamelCaseMatch( candidate, includeMatchSpans, patternChunk, punctuationStripped, isLowercase); if (match.HasValue) { return match.Value; } if (isLowercase) { // g) The word is all lower case. Is it a case insensitive substring of the candidate // starting on a part boundary of the candidate? // We could check every character boundary start of the candidate for the pattern. // However, that's an m * n operation in the worst case. Instead, find the first // instance of the pattern substring, and see if it starts on a capital letter. // It seems unlikely that the user will try to filter the list based on a substring // that starts on a capital letter and also with a lowercase one. (Pattern: fogbar, // Candidate: quuxfogbarFogBar). if (patternChunk.Text.Length < candidate.Length) { if (caseInsensitiveIndex != -1 && char.IsUpper(candidate[caseInsensitiveIndex])) { return new PatternMatch( PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: false, matchedSpan: GetMatchedSpan(includeMatchSpans, caseInsensitiveIndex, patternChunk.Text.Length)); } } } if (fuzzyMatch) { if (patternChunk.SimilarityChecker.AreSimilar(candidate)) { return new PatternMatch( PatternMatchKind.Fuzzy, punctuationStripped, isCaseSensitive: false, matchedSpan: null); } } return null; } private ImmutableArray<TextSpan> GetMatchedSpans(bool includeMatchSpans, List<TextSpan> matchedSpans) { return includeMatchSpans ? new NormalizedTextSpanCollection(matchedSpans).ToImmutableArray() : ImmutableArray<TextSpan>.Empty; } private static TextSpan? GetMatchedSpan(bool includeMatchSpans, int start, int length) { return includeMatchSpans ? new TextSpan(start, length) : (TextSpan?)null; } private static bool ContainsSpaceOrAsterisk(string text) { for (int i = 0; i < text.Length; i++) { char ch = text[i]; if (ch == ' ' || ch == '*') { return true; } } return false; } private ImmutableArray<PatternMatch> MatchPatternSegment( string candidate, bool includeMatchSpans, PatternSegment patternSegment, bool fuzzyMatch) { if (fuzzyMatch && !_allowFuzzyMatching) { return ImmutableArray<PatternMatch>.Empty; } var singleMatch = MatchPatternSegment(candidate, includeMatchSpans, patternSegment, wantAllMatches: true, fuzzyMatch: fuzzyMatch, allMatches: out var matches); if (singleMatch.HasValue) { return ImmutableArray.Create(singleMatch.Value); } return matches; } /// <summary> /// Internal helper for MatchPatternInternal /// </summary> /// <remarks> /// PERF: Designed to minimize allocations in common cases. /// If there's no match, then null is returned. /// If there's a single match, or the caller only wants the first match, then it is returned (as a Nullable) /// If there are multiple matches, and the caller wants them all, then a List is allocated. /// </remarks> /// <param name="candidate">The word being tested.</param> /// <param name="segment">The segment of the pattern to check against the candidate.</param> /// <param name="wantAllMatches">Does the caller want all matches or just the first?</param> /// <param name="fuzzyMatch">If a fuzzy match should be performed</param> /// <param name="allMatches">If <paramref name="wantAllMatches"/> is true, and there's more than one match, then the list of all matches.</param> /// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param> /// <returns>If there's only one match, then the return value is that match. Otherwise it is null.</returns> private PatternMatch? MatchPatternSegment( string candidate, bool includeMatchSpans, PatternSegment segment, bool wantAllMatches, bool fuzzyMatch, out ImmutableArray<PatternMatch> allMatches) { allMatches = ImmutableArray<PatternMatch>.Empty; if (fuzzyMatch && !_allowFuzzyMatching) { return null; } // First check if the segment matches as is. This is also useful if the segment contains // characters we would normally strip when splitting into parts that we also may want to // match in the candidate. For example if the segment is "@int" and the candidate is // "@int", then that will show up as an exact match here. // // Note: if the segment contains a space or an asterisk then we must assume that it's a // multi-word segment. if (!ContainsSpaceOrAsterisk(segment.TotalTextChunk.Text)) { var match = MatchPatternChunk(candidate, includeMatchSpans, segment.TotalTextChunk, punctuationStripped: false, fuzzyMatch: fuzzyMatch); if (match != null) { return match; } } // The logic for pattern matching is now as follows: // // 1) Break the segment passed in into words. Breaking is rather simple and a // good way to think about it that if gives you all the individual alphanumeric words // of the pattern. // // 2) For each word try to match the word against the candidate value. // // 3) Matching is as follows: // // a) Check if the word matches the candidate entirely, in an case insensitive or // sensitive manner. If it does, return that there was an exact match. // // b) Check if the word is a prefix of the candidate, in a case insensitive or // sensitive manner. If it does, return that there was a prefix match. // // c) If the word is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring // match. // // Note: We only have a substring match if the lowercase part is prefix match of // some word part. That way we don't match something like 'Class' when the user // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with // 'a'). // // d) If the word was not entirely lowercase, then check if it is contained in the // candidate in a case *sensitive* manner. If so, return that there was a substring // match. // // e) If the word was entirely lowercase, then attempt a special lower cased camel cased // match. i.e. cofipro would match CodeFixProvider. // // f) If the word was not entirely lowercase, then attempt a normal camel cased match. // i.e. CoFiPro would match CodeFixProvider, but CofiPro would not. // // g) The word is all lower case. Is it a case insensitive substring of the candidate starting // on a part boundary of the candidate? // // Only if all words have some sort of match is the pattern considered matched. var matches = ArrayBuilder<PatternMatch>.GetInstance(); try { var subWordTextChunks = segment.SubWordTextChunks; foreach (var subWordTextChunk in subWordTextChunks) { // Try to match the candidate with this word var result = MatchPatternChunk(candidate, includeMatchSpans, subWordTextChunk, punctuationStripped: true, fuzzyMatch: fuzzyMatch); if (result == null) { return null; } if (!wantAllMatches || subWordTextChunks.Length == 1) { // Stop at the first word return result; } matches.Add(result.Value); } allMatches = matches.ToImmutable(); return null; } finally { matches.Free(); } } private static bool IsWordChar(char ch, bool verbatimIdentifierPrefixIsWordCharacter) { return char.IsLetterOrDigit(ch) || ch == '_' || (verbatimIdentifierPrefixIsWordCharacter && ch == '@'); } /// <summary> /// Do the two 'parts' match? i.e. Does the candidate part start with the pattern part? /// </summary> /// <param name="candidate">The candidate text</param> /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param> /// <param name="pattern">The pattern text</param> /// <param name="patternPart">The span within the <paramref name="pattern"/> text</param> /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param> /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with /// the span identified by <paramref name="patternPart"/> within <paramref name="pattern"/>.</returns> private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, TextSpan patternPart, CompareOptions compareOptions) { if (patternPart.Length > candidatePart.Length) { // Pattern part is longer than the candidate part. There can never be a match. return false; } return _compareInfo.Compare(candidate, candidatePart.Start, patternPart.Length, pattern, patternPart.Start, patternPart.Length, compareOptions) == 0; } /// <summary> /// Does the given part start with the given pattern? /// </summary> /// <param name="candidate">The candidate text</param> /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param> /// <param name="pattern">The pattern text</param> /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param> /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with <paramref name="pattern"/></returns> private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, CompareOptions compareOptions) => PartStartsWith(candidate, candidatePart, pattern, new TextSpan(0, pattern.Length), compareOptions); private PatternMatch? TryCamelCaseMatch( string candidate, bool includeMatchSpans, TextChunk patternChunk, bool punctuationStripped, bool isLowercase) { if (isLowercase) { // e) If the word was entirely lowercase, then attempt a special lower cased camel cased // match. i.e. cofipro would match CodeFixProvider. var candidateParts = GetWordSpans(candidate); var camelCaseWeight = TryAllLowerCamelCaseMatch( candidate, includeMatchSpans, candidateParts, patternChunk, out var matchedSpans); if (camelCaseWeight.HasValue) { return new PatternMatch( PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: false, camelCaseWeight: camelCaseWeight, matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans)); } } else { // f) If the word was not entirely lowercase, then attempt a normal camel cased match. // i.e. CoFiPro would match CodeFixProvider, but CofiPro would not. if (patternChunk.CharacterSpans.Count > 0) { var candidateParts = GetWordSpans(candidate); var camelCaseWeight = TryUpperCaseCamelCaseMatch(candidate, includeMatchSpans, candidateParts, patternChunk, CompareOptions.None, out var matchedSpans); if (camelCaseWeight.HasValue) { return new PatternMatch( PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: true, camelCaseWeight: camelCaseWeight, matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans)); } camelCaseWeight = TryUpperCaseCamelCaseMatch(candidate, includeMatchSpans, candidateParts, patternChunk, CompareOptions.IgnoreCase, out matchedSpans); if (camelCaseWeight.HasValue) { return new PatternMatch( PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: false, camelCaseWeight: camelCaseWeight, matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans)); } } } return null; } private int? TryAllLowerCamelCaseMatch( string candidate, bool includeMatchedSpans, StringBreaks candidateParts, TextChunk patternChunk, out List<TextSpan> matchedSpans) { var matcher = new AllLowerCamelCaseMatcher(candidate, includeMatchedSpans, candidateParts, patternChunk); return matcher.TryMatch(out matchedSpans); } private int? TryUpperCaseCamelCaseMatch( string candidate, bool includeMatchedSpans, StringBreaks candidateParts, TextChunk patternChunk, CompareOptions compareOption, out List<TextSpan> matchedSpans) { matchedSpans = null; var patternChunkCharacterSpans = patternChunk.CharacterSpans; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U // and I will both match in UI. int currentCandidate = 0; int currentChunkSpan = 0; int? firstMatch = null; bool? contiguous = null; while (true) { // Let's consider our termination cases if (currentChunkSpan == patternChunkCharacterSpans.Count) { Contract.Requires(firstMatch.HasValue); Contract.Requires(contiguous.HasValue); // We did match! We shall assign a weight to this var weight = 0; // Was this contiguous? if (contiguous.Value) { weight += CamelCaseContiguousBonus; } // Did we start at the beginning of the candidate? if (firstMatch.Value == 0) { weight += CamelCaseMatchesFromStartBonus; } return weight; } else if (currentCandidate == candidateParts.Count) { // No match, since we still have more of the pattern to hit matchedSpans = null; return null; } var candidatePart = candidateParts[currentCandidate]; bool gotOneMatchThisCandidate = false; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < patternChunkCharacterSpans.Count; currentChunkSpan++) { var patternChunkCharacterSpan = patternChunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will // only continue trying to consume pattern parts if the last part and this // part are both upper case. if (!char.IsUpper(patternChunk.Text[patternChunkCharacterSpans[currentChunkSpan - 1].Start]) || !char.IsUpper(patternChunk.Text[patternChunkCharacterSpans[currentChunkSpan].Start])) { break; } } if (!PartStartsWith(candidate, candidatePart, patternChunk.Text, patternChunkCharacterSpan, compareOption)) { break; } if (includeMatchedSpans) { matchedSpans = matchedSpans ?? new List<TextSpan>(); matchedSpans.Add(new TextSpan(candidatePart.Start, patternChunkCharacterSpan.Length)); } gotOneMatchThisCandidate = true; firstMatch = firstMatch ?? currentCandidate; // If we were contiguous, then keep that value. If we weren't, then keep that // value. If we don't know, then set the value to 'true' as an initial match is // obviously contiguous. contiguous = contiguous ?? true; candidatePart = new TextSpan(candidatePart.Start + patternChunkCharacterSpan.Length, candidatePart.Length - patternChunkCharacterSpan.Length); } // Check if we matched anything at all. If we didn't, then we need to unset the // contiguous bit if we currently had it set. // If we haven't set the bit yet, then that means we haven't matched anything so // far, and we don't want to change that. if (!gotOneMatchThisCandidate && contiguous.HasValue) { contiguous = false; } // Move onto the next candidate. currentCandidate++; } } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Abp; using Abp.Configuration.Startup; using Abp.Domain.Uow; using Abp.Runtime.Session; using Abp.TestBase; using AbpCompanyName.AbpProjectName.Authorization.Users; using AbpCompanyName.AbpProjectName.EntityFramework; using AbpCompanyName.AbpProjectName.Migrations.SeedData; using AbpCompanyName.AbpProjectName.MultiTenancy; using AbpCompanyName.AbpProjectName.Users; using Castle.MicroKernel.Registration; using Effort; using EntityFramework.DynamicFilters; namespace AbpCompanyName.AbpProjectName.Tests { public abstract class AbpProjectNameTestBase : AbpIntegratedTestBase<AbpProjectNameTestModule> { private DbConnection _hostDb; private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture protected AbpProjectNameTestBase() { //Seed initial data for host AbpSession.TenantId = null; UsingDbContext(context => { new InitialHostDbBuilder(context).Create(); new DefaultTenantCreator(context).Create(); }); //Seed initial data for default tenant AbpSession.TenantId = 1; UsingDbContext(context => { new TenantRoleAndUserBuilder(context, 1).Create(); }); LoginAsDefaultTenantAdmin(); } protected override void PreInitialize() { base.PreInitialize(); /* You can switch database architecture here: */ UseSingleDatabase(); //UseDatabasePerTenant(); } /* Uses single database for host and all tenants. */ private void UseSingleDatabase() { _hostDb = DbConnectionFactory.CreateTransient(); LocalIocManager.IocContainer.Register( Component.For<DbConnection>() .UsingFactoryMethod(() => _hostDb) .LifestyleSingleton() ); } /* Uses single database for host and Default tenant, * but dedicated databases for all other tenants. */ private void UseDatabasePerTenant() { _hostDb = DbConnectionFactory.CreateTransient(); _tenantDbs = new Dictionary<int, DbConnection>(); LocalIocManager.IocContainer.Register( Component.For<DbConnection>() .UsingFactoryMethod((kernel) => { lock (_tenantDbs) { var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current; var abpSession = kernel.Resolve<IAbpSession>(); var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId; if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db { return _hostDb; } if (!_tenantDbs.ContainsKey(tenantId.Value)) { _tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient(); } return _tenantDbs[tenantId.Value]; } }, true) .LifestyleTransient() ); } #region UsingDbContext protected IDisposable UsingTenantId(int? tenantId) { var previousTenantId = AbpSession.TenantId; AbpSession.TenantId = tenantId; return new DisposeAction(() => AbpSession.TenantId = previousTenantId); } protected void UsingDbContext(Action<AbpProjectNameDbContext> action) { UsingDbContext(AbpSession.TenantId, action); } protected Task UsingDbContextAsync(Func<AbpProjectNameDbContext, Task> action) { return UsingDbContextAsync(AbpSession.TenantId, action); } protected T UsingDbContext<T>(Func<AbpProjectNameDbContext, T> func) { return UsingDbContext(AbpSession.TenantId, func); } protected Task<T> UsingDbContextAsync<T>(Func<AbpProjectNameDbContext, Task<T>> func) { return UsingDbContextAsync(AbpSession.TenantId, func); } protected void UsingDbContext(int? tenantId, Action<AbpProjectNameDbContext> action) { using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>()) { context.DisableAllFilters(); action(context); context.SaveChanges(); } } } protected async Task UsingDbContextAsync(int? tenantId, Func<AbpProjectNameDbContext, Task> action) { using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>()) { context.DisableAllFilters(); await action(context); await context.SaveChangesAsync(); } } } protected T UsingDbContext<T>(int? tenantId, Func<AbpProjectNameDbContext, T> func) { T result; using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>()) { context.DisableAllFilters(); result = func(context); context.SaveChanges(); } } return result; } protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<AbpProjectNameDbContext, Task<T>> func) { T result; using (UsingTenantId(tenantId)) { using (var context = LocalIocManager.Resolve<AbpProjectNameDbContext>()) { context.DisableAllFilters(); result = await func(context); await context.SaveChangesAsync(); } } return result; } #endregion #region Login protected void LoginAsHostAdmin() { LoginAsHost(User.AdminUserName); } protected void LoginAsDefaultTenantAdmin() { LoginAsTenant(Tenant.DefaultTenantName, User.AdminUserName); } protected void LogoutAsDefaultTenant() { LogoutAsTenant(Tenant.DefaultTenantName); } protected void LoginAsHost(string userName) { AbpSession.TenantId = null; var user = UsingDbContext( context => context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName)); if (user == null) { throw new Exception("There is no user: " + userName + " for host."); } AbpSession.UserId = user.Id; } protected void LogoutAsHost() { Resolve<IMultiTenancyConfig>().IsEnabled = true; AbpSession.TenantId = null; AbpSession.UserId = null; } protected void LoginAsTenant(string tenancyName, string userName) { var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName)); if (tenant == null) { throw new Exception("There is no tenant: " + tenancyName); } AbpSession.TenantId = tenant.Id; var user = UsingDbContext( context => context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName)); if (user == null) { throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName); } AbpSession.UserId = user.Id; } protected void LogoutAsTenant(string tenancyName) { var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName)); if (tenant == null) { throw new Exception("There is no tenant: " + tenancyName); } AbpSession.TenantId = tenant.Id; AbpSession.UserId = null; } #endregion /// <summary> /// Gets current user if <see cref="IAbpSession.UserId"/> is not null. /// Throws exception if it's null. /// </summary> protected async Task<User> GetCurrentUserAsync() { var userId = AbpSession.GetUserId(); return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId)); } /// <summary> /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null. /// Throws exception if there is no current tenant. /// </summary> protected async Task<Tenant> GetCurrentTenantAsync() { var tenantId = AbpSession.GetTenantId(); return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] [RequireComponent(typeof(OVROverlay))] public class OVROverlayMeshGenerator : MonoBehaviour { private Mesh _Mesh; private List<Vector3> _Verts = new List<Vector3>(); private List<Vector2> _UV = new List<Vector2>(); private List<int> _Tris = new List<int>(); private OVROverlay _Overlay; private MeshFilter _MeshFilter; private MeshCollider _MeshCollider; private Transform _CameraRoot; private Transform _Transform; private OVROverlay.OverlayShape _LastShape; private Vector3 _LastPosition; private Quaternion _LastRotation; private Vector3 _LastScale; private Rect _LastRectLeft; private Rect _LastRectRight; private bool _Awake = false; protected void Awake() { _Overlay = GetComponent<OVROverlay>(); _MeshFilter = GetComponent<MeshFilter>(); _MeshCollider = GetComponent<MeshCollider>(); _Transform = transform; if (Camera.main && Camera.main.transform.parent) { _CameraRoot = Camera.main.transform.parent; } #if UNITY_EDITOR if (!Application.isPlaying) { UnityEditor.EditorApplication.update += Update; } #endif _Awake = true; } private Rect GetBoundingRect(Rect a, Rect b) { float xMin = Mathf.Min(a.x, b.x); float xMax = Mathf.Max(a.x + a.width, b.x + b.width); float yMin = Mathf.Min(a.y, b.y); float yMax = Mathf.Max(a.y + a.height, b.y + b.height); return new Rect(xMin, yMin, xMax - xMin, yMax - yMin); } private void Update() { if (!_Awake) { Awake(); } if (_Overlay) { OVROverlay.OverlayShape shape = _Overlay.currentOverlayShape; Vector3 position = _CameraRoot ? (_Transform.position - _CameraRoot.position) : _Transform.position; Quaternion rotation = _Transform.rotation; Vector3 scale = _Transform.lossyScale; Rect rectLeft = _Overlay.overrideTextureRectMatrix ? _Overlay.destRectLeft : new Rect(0,0,1,1); Rect rectRight = _Overlay.overrideTextureRectMatrix ? _Overlay.destRectRight : new Rect(0,0,1,1); if (_Mesh == null || _LastShape != shape || _LastPosition != position || _LastRotation != rotation || _LastScale != scale || _LastRectLeft != rectLeft || _LastRectRight != rectRight) { UpdateMesh(shape, position, rotation, scale, GetBoundingRect(rectLeft, rectRight)); _LastShape = shape; _LastPosition = position; _LastRotation = rotation; _LastScale = scale; _LastRectLeft = rectLeft; _LastRectRight = rectRight; } } } private void UpdateMesh(OVROverlay.OverlayShape shape, Vector3 position, Quaternion rotation, Vector3 scale, Rect rect) { if (_MeshFilter) { if (_Mesh == null) { _Mesh = new Mesh() { name = "Overlay" }; _Mesh.hideFlags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor; } _Mesh.Clear(); _Verts.Clear(); _UV.Clear(); _Tris.Clear(); GenerateMesh(_Verts, _UV, _Tris, shape, position, rotation, scale, rect); _Mesh.SetVertices(_Verts); _Mesh.SetUVs(0, _UV); _Mesh.SetTriangles(_Tris, 0); _Mesh.UploadMeshData(false); _MeshFilter.sharedMesh = _Mesh; if (_MeshCollider) { _MeshCollider.sharedMesh = _Mesh; } } } public static void GenerateMesh(List<Vector3> verts, List<Vector2> uvs, List<int> tris, OVROverlay.OverlayShape shape, Vector3 position, Quaternion rotation, Vector3 scale, Rect rect) { switch (shape) { case OVROverlay.OverlayShape.Equirect: BuildSphere(verts, uvs, tris, position, rotation, scale, rect); break; case OVROverlay.OverlayShape.Cubemap: case OVROverlay.OverlayShape.OffcenterCubemap: BuildCube(verts, uvs, tris, position, rotation, scale); break; case OVROverlay.OverlayShape.Quad: BuildQuad(verts, uvs, tris, rect); break; case OVROverlay.OverlayShape.Cylinder: BuildHemicylinder(verts, uvs, tris, scale, rect); break; } } private static Vector2 GetSphereUV(float theta, float phi, float expand_coef) { float thetaU = ((theta / (2 * Mathf.PI) - 0.5f) / expand_coef) + 0.5f; float phiV = ((phi / Mathf.PI) / expand_coef) + 0.5f; return new Vector2(thetaU, phiV); } private static Vector3 GetSphereVert(float theta, float phi) { return new Vector3(-Mathf.Sin(theta) * Mathf.Cos(phi), Mathf.Sin(phi), -Mathf.Cos(theta) * Mathf.Cos(phi)); } public static void BuildSphere(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 position, Quaternion rotation, Vector3 scale, Rect rect, float worldScale = 800, int latitudes = 128, int longitudes = 128, float expand_coef = 1.0f) { position = Quaternion.Inverse(rotation) * position; latitudes = Mathf.CeilToInt(latitudes * rect.height); longitudes = Mathf.CeilToInt(longitudes * rect.width); float minTheta = Mathf.PI * 2 * ( rect.x); float minPhi = Mathf.PI * (0.5f - rect.y - rect.height); float thetaScale = Mathf.PI * 2 * rect.width / longitudes; float phiScale = Mathf.PI * rect.height / latitudes; for (int j = 0; j < latitudes + 1; j += 1) { for (int k = 0; k < longitudes + 1; k++) { float theta = minTheta + k * thetaScale; float phi = minPhi + j * phiScale; Vector2 suv = GetSphereUV(theta, phi, expand_coef); uv.Add(new Vector2((suv.x - rect.x) / rect.width, (suv.y - rect.y) / rect.height)); Vector3 vert = GetSphereVert(theta, phi); vert.x = (worldScale * vert.x - position.x) / scale.x; vert.y = (worldScale * vert.y - position.y) / scale.y; vert.z = (worldScale * vert.z - position.z) / scale.z; verts.Add(vert); } } for (int j = 0; j < latitudes; j++) { for (int k = 0; k < longitudes; k++) { triangles.Add((j * (longitudes + 1)) + k); triangles.Add(((j + 1) * (longitudes + 1)) + k); triangles.Add(((j + 1) * (longitudes + 1)) + k + 1); triangles.Add(((j + 1) * (longitudes + 1)) + k + 1); triangles.Add((j * (longitudes + 1)) + k + 1); triangles.Add((j * (longitudes + 1)) + k); } } } private enum CubeFace { Right, Left, Top, Bottom, Front, Back, COUNT } private static readonly Vector3[] BottomLeft = new Vector3[] { new Vector3(-0.5f, -0.5f, -0.5f), new Vector3(0.5f, -0.5f, 0.5f), new Vector3(0.5f, 0.5f, -0.5f), new Vector3(0.5f, -0.5f, 0.5f), new Vector3(0.5f, -0.5f, -0.5f), new Vector3(-0.5f, -0.5f, 0.5f) }; private static readonly Vector3[] RightVector = new Vector3[] { Vector3.forward, Vector3.back, Vector3.left, Vector3.left, Vector3.left, Vector3.right }; private static readonly Vector3[] UpVector = new Vector3[] { Vector3.up, Vector3.up, Vector3.forward, Vector3.back, Vector3.up, Vector3.up }; private static Vector2 GetCubeUV(CubeFace face, Vector2 sideUV, float expand_coef) { sideUV = (sideUV - 0.5f * Vector2.one) / expand_coef + 0.5f * Vector2.one; switch (face) { case CubeFace.Bottom: return new Vector2(sideUV.x / 3, sideUV.y / 2); case CubeFace.Front: return new Vector2((1 + sideUV.x) / 3, sideUV.y / 2); case CubeFace.Back: return new Vector2((2 + sideUV.x) / 3, sideUV.y / 2); case CubeFace.Right: return new Vector2(sideUV.x / 3, (1 + sideUV.y) / 2); case CubeFace.Left: return new Vector2((1 + sideUV.x) / 3, (1 + sideUV.y) / 2); case CubeFace.Top: return new Vector2((2 + sideUV.x) / 3, (1 + sideUV.y) / 2); default: return Vector2.zero; } } private static Vector3 GetCubeVert(CubeFace face, Vector2 sideUV, float expand_coef) { return BottomLeft[(int)face] + sideUV.x * RightVector[(int)face] + sideUV.y * UpVector[(int)face]; } public static void BuildCube(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 position, Quaternion rotation, Vector3 scale, float worldScale = 800, int subQuads = 1, float expand_coef = 1.01f) { position = Quaternion.Inverse(rotation) * position; int vertsPerSide = (subQuads + 1) * (subQuads + 1); for (int i = 0; i < (int)CubeFace.COUNT; i++) { for(int j = 0; j < subQuads + 1; j++) { for(int k = 0; k < subQuads + 1; k++) { float u = j / (float)subQuads; float v = k / (float)subQuads; uv.Add(GetCubeUV((CubeFace)i, new Vector2(u, v), expand_coef)); Vector3 vert = GetCubeVert((CubeFace)i, new Vector2(u, v), expand_coef); vert.x = (worldScale * vert.x - position.x) / scale.x; vert.y = (worldScale * vert.y - position.y) / scale.y; vert.z = (worldScale * vert.z - position.z) / scale.z; verts.Add(vert); } } for(int j = 0; j < subQuads; j++) { for(int k = 0; k < subQuads; k++) { triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k); triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k); triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k + 1); triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k + 1); triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k); triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k + 1); } } } } public static void BuildQuad(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Rect rect) { verts.Add(new Vector3(rect.x - 0.5f, (1 - rect.y - rect.height) - 0.5f, 0)); verts.Add(new Vector3(rect.x - 0.5f, (1 - rect.y) - 0.5f, 0)); verts.Add(new Vector3(rect.x + rect.width - 0.5f, (1 - rect.y) - 0.5f, 0)); verts.Add(new Vector3(rect.x + rect.width - 0.5f, (1 - rect.y - rect.height) - 0.5f, 0)); uv.Add(new Vector2(0, 0)); uv.Add(new Vector2(0, 1)); uv.Add(new Vector2(1, 1)); uv.Add(new Vector2(1, 0)); triangles.Add(0); triangles.Add(1); triangles.Add(2); triangles.Add(2); triangles.Add(3); triangles.Add(0); } public static void BuildHemicylinder(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 scale, Rect rect, int longitudes = 128) { float height = Mathf.Abs(scale.y) * rect.height; float radius = scale.z; float arcLength = scale.x * rect.width; float arcAngle = arcLength / radius; float minAngle = scale.x * (-0.5f + rect.x) / radius; int columns = Mathf.CeilToInt(longitudes * arcAngle / (2 * Mathf.PI)); // we don't want super tall skinny triangles because that can lead to artifacting. // make triangles no more than 2x taller than wide float triangleWidth = arcLength / columns; float ratio = height / triangleWidth; int rows = Mathf.CeilToInt(ratio / 2); for (int j = 0; j < rows + 1; j += 1) { for (int k = 0; k < columns + 1; k++) { uv.Add(new Vector2((k / (float)columns), 1 - (j / (float)rows))); Vector3 vert = Vector3.zero; // because the scale is used to control the parameters, we need // to reverse multiply by scale to appear correctly vert.x = (Mathf.Sin(minAngle + (k * arcAngle / columns)) * radius) / scale.x; vert.y = (0.5f - rect.y - rect.height + rect.height * (1 - j / (float)rows)); vert.z = (Mathf.Cos(minAngle + (k * arcAngle / columns)) * radius) / scale.z; verts.Add(vert); } } for (int j = 0; j < rows; j++) { for (int k = 0; k < columns; k++) { triangles.Add((j * (columns + 1)) + k); triangles.Add(((j + 1) * (columns + 1)) + k + 1); triangles.Add(((j + 1) * (columns + 1)) + k); triangles.Add(((j + 1) * (columns + 1)) + k + 1); triangles.Add((j * (columns + 1)) + k); triangles.Add((j * (columns + 1)) + k + 1); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Providers; namespace Orleans.Runtime.Configuration { /// <summary> /// Orleans client configuration parameters. /// </summary> [Serializable] public class ClientConfiguration : MessagingConfiguration, IStatisticsConfiguration { /// <summary> /// Specifies the type of the gateway provider. /// </summary> public enum GatewayProviderType { /// <summary>No provider specified</summary> None, /// <summary>use Azure, requires SystemStore element</summary> AzureTable, /// <summary>use ADO.NET, requires SystemStore element</summary> AdoNet, /// <summary>use ZooKeeper, requires SystemStore element</summary> ZooKeeper, /// <summary>use Config based static list, requires Config element(s)</summary> Config, /// <summary>use provider from third-party assembly</summary> Custom } /// <summary> /// The name of this client. /// </summary> public string ClientName { get; set; } = "Client"; /// <summary>Gets the configuration source file path</summary> public string SourceFile { get; private set; } /// <summary> /// The list fo the gateways to use. /// Each GatewayNode element specifies an outside grain client gateway node. /// If outside (non-Orleans) clients are to connect to the Orleans system, then at least one gateway node must be specified. /// Additional gateway nodes may be specified if desired, and will add some failure resilience and scalability. /// If multiple gateways are specified, then each client will select one from the list at random. /// </summary> public IList<IPEndPoint> Gateways { get; set; } /// <summary> /// </summary> public int PreferedGatewayIndex { get; set; } /// <summary> /// </summary> public GatewayProviderType GatewayProvider { get; set; } /// <summary> /// Specifies a unique identifier for this cluster. /// If the silos are deployed on Azure (run as workers roles), deployment id is set automatically by Azure runtime, /// accessible to the role via RoleEnvironment.DeploymentId static variable and is passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set by a deployment script in the OrleansConfiguration.xml file. /// </summary> public string ClusterId { get; set; } /// <summary> /// Deployment Id. This is the same as ClusterId and has been deprecated in favor of it. /// </summary> [Obsolete("DeploymentId is the same as ClusterId.")] public string DeploymentId { get => this.ClusterId; set => this.ClusterId = value; } /// <summary> /// Specifies the connection string for the gateway provider. /// If the silos are deployed on Azure (run as workers roles), DataConnectionString may be specified via RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"); /// In such a case it is taken from there and passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles and this config is specified via RoleEnvironment, /// this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set in the OrleansConfiguration.xml file. /// If not set at all, DevelopmentStorageAccount will be used. /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for the gateway provider. This three-part naming syntax is also used when creating a new factory /// and for identifying the provider in an application configuration file so that the provider name, along with its associated /// connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// </summary> public string AdoInvariant { get; set; } public string CustomGatewayProviderAssemblyName { get; set; } /// <summary> /// Whether Trace.CorrelationManager.ActivityId settings should be propagated into grain calls. /// </summary> public bool PropagateActivityId { get; set; } /// <summary> /// </summary> public AddressFamily PreferredFamily { get; set; } /// <summary> /// The Interface attribute specifies the name of the network interface to use to work out an IP address for this machine. /// </summary> public string NetInterface { get; private set; } /// <summary> /// The Port attribute specifies the specific listen port for this client machine. /// If value is zero, then a random machine-assigned port number will be used. /// </summary> public int Port { get; private set; } /// <summary>Gets the true host name, no IP address. It equals Dns.GetHostName()</summary> public string DNSHostName { get; private set; } /// <summary> /// </summary> public TimeSpan GatewayListRefreshPeriod { get; set; } public string StatisticsProviderName { get; set; } public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } public TimeSpan StatisticsLogWriteInterval { get; set; } [Obsolete("Statistics table is no longer supported.")] public bool StatisticsWriteLogStatisticsToTable { get; set; } public StatisticsLevel StatisticsCollectionLevel { get; set; } public TelemetryConfiguration TelemetryConfiguration { get; } = new TelemetryConfiguration(); public LimitManager LimitManager { get; private set; } private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = Constants.INFINITE_TIMESPAN; /// <summary> /// </summary> public bool UseAzureSystemStore { get { return GatewayProvider == GatewayProviderType.AzureTable && !String.IsNullOrWhiteSpace(this.ClusterId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } /// <summary> /// </summary> public bool UseAdoNetSystemStore { get { return GatewayProvider == GatewayProviderType.AdoNet && !String.IsNullOrWhiteSpace(this.ClusterId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } private bool HasStaticGateways { get { return Gateways != null && Gateways.Count > 0; } } /// <summary> /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } /// <summary>Initializes a new instance of <see cref="ClientConfiguration"/>.</summary> public ClientConfiguration() : base(false) { SourceFile = null; PreferedGatewayIndex = -1; Gateways = new List<IPEndPoint>(); GatewayProvider = GatewayProviderType.None; PreferredFamily = AddressFamily.InterNetwork; NetInterface = null; Port = 0; DNSHostName = Dns.GetHostName(); this.ClusterId = ""; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; GatewayListRefreshPeriod = GatewayOptions.DEFAULT_GATEWAY_LIST_REFRESH_PERIOD; StatisticsProviderName = null; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = StatisticsOptions.DEFAULT_LOG_WRITE_PERIOD; StatisticsCollectionLevel = StatisticsOptions.DEFAULT_COLLECTION_LEVEL; LimitManager = new LimitManager(); ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); } public void Load(TextReader input) { var xml = new XmlDocument(); var xmlReader = XmlReader.Create(input); xml.Load(xmlReader); XmlElement root = xml.DocumentElement; LoadFromXml(root); } internal void LoadFromXml(XmlElement root) { foreach (XmlNode node in root.ChildNodes) { var child = node as XmlElement; if (child != null) { switch (child.LocalName) { case "Gateway": Gateways.Add(ConfigUtilities.ParseIPEndPoint(child).GetResult()); if (GatewayProvider == GatewayProviderType.None) { GatewayProvider = GatewayProviderType.Config; } break; case "Azure": // Throw exception with explicit deprecation error message throw new OrleansException( "The Azure element has been deprecated -- use SystemStore element instead."); case "SystemStore": if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); GatewayProvider = (GatewayProviderType)Enum.Parse(typeof(GatewayProviderType), sst); } if (child.HasAttribute("CustomGatewayProviderAssemblyName")) { CustomGatewayProviderAssemblyName = child.GetAttribute("CustomGatewayProviderAssemblyName"); if (CustomGatewayProviderAssemblyName.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"CustomGatewayProviderAssemblyName\""); if (GatewayProvider != GatewayProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when CustomGatewayProviderAssemblyName is specified"); } if (child.HasAttribute("DeploymentId")) { this.ClusterId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } if (GatewayProvider == GatewayProviderType.None) { // Assume the connection string is for Azure storage if not explicitly specified GatewayProvider = GatewayProviderType.AzureTable; } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { AdoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(AdoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } } break; case "Tracing": if (ConfigUtilities.TryParsePropagateActivityId(child, ClientName, out var propagateActivityId)) this.PropagateActivityId = propagateActivityId; break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, ClientName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, ClientName); break; case "Debug": break; case "Messaging": base.Load(child); break; case "LocalAddress": if (child.HasAttribute("PreferredFamily")) { PreferredFamily = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid address family for the PreferredFamily attribute on the LocalAddress element"); } else { throw new FormatException("Missing PreferredFamily attribute on the LocalAddress element"); } if (child.HasAttribute("Interface")) { NetInterface = child.GetAttribute("Interface"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Invalid integer value for the Port attribute on the LocalAddress element"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child, this.TelemetryConfiguration); break; default: if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } } /// <summary> /// </summary> public static ClientConfiguration LoadFromFile(string fileName) { if (fileName == null) { return null; } using (TextReader input = File.OpenText(fileName)) { var config = new ClientConfiguration(); config.Load(input); config.SourceFile = fileName; return config; } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="Orleans.Streams.IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { TypeInfo providerTypeInfo = typeof(T).GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(typeof(T))) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } /// <summary> /// Loads the configuration from the standard paths, looking up the directory hierarchy /// </summary> /// <returns>Client configuration data if a configuration file was found.</returns> /// <exception cref="FileNotFoundException">Thrown if no configuration file could be found in any of the standard locations</exception> public static ClientConfiguration StandardLoad() { var fileName = ConfigUtilities.FindConfigFile(false); // Throws FileNotFoundException return LoadFromFile(fileName); } /// <summary>Returns a detailed human readable string that represents the current configuration. It does not contain every single configuration knob.</summary> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo()); sb.Append(" Host: ").AppendLine(Dns.GetHostName()); sb.Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.AppendLine("Client Configuration:"); sb.Append(" Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile)); sb.Append(" Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow)); sb.Append(" Gateway Provider: ").Append(GatewayProvider); if (GatewayProvider == GatewayProviderType.None) { sb.Append(". Gateway Provider that will be used instead: ").Append(GatewayProviderToUse); } sb.AppendLine(); if (Gateways != null && Gateways.Count > 0 ) { sb.AppendFormat(" Gateways[{0}]:", Gateways.Count).AppendLine(); foreach (var endpoint in Gateways) { sb.Append(" ").AppendLine(endpoint.ToString()); } } else { sb.Append(" Gateways: ").AppendLine("Unspecified"); } sb.Append(" Preferred Gateway Index: ").AppendLine(PreferedGatewayIndex.ToString()); if (Gateways != null && PreferedGatewayIndex >= 0 && PreferedGatewayIndex < Gateways.Count) { sb.Append(" Preferred Gateway Address: ").AppendLine(Gateways[PreferedGatewayIndex].ToString()); } sb.Append(" GatewayListRefreshPeriod: ").Append(GatewayListRefreshPeriod).AppendLine(); if (!String.IsNullOrEmpty(this.ClusterId) || !String.IsNullOrEmpty(DataConnectionString)) { sb.Append(" Azure:").AppendLine(); sb.Append(" ClusterId: ").Append(this.ClusterId).AppendLine(); string dataConnectionInfo = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); // Don't print Azure account keys in log files sb.Append(" DataConnectionString: ").Append(dataConnectionInfo).AppendLine(); } if (!string.IsNullOrWhiteSpace(NetInterface)) { sb.Append(" Network Interface: ").AppendLine(NetInterface); } if (Port != 0) { sb.Append(" Network Port: ").Append(Port).AppendLine(); } sb.Append(" Preferred Address Family: ").AppendLine(PreferredFamily.ToString()); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Client Name: ").AppendLine(ClientName); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); sb.AppendFormat(base.ToString()); sb.Append(" .NET: ").AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal GatewayProviderType GatewayProviderToUse { get { // order is important here for establishing defaults. if (GatewayProvider != GatewayProviderType.None) return GatewayProvider; if (UseAzureSystemStore) return GatewayProviderType.AzureTable; return HasStaticGateways ? GatewayProviderType.Config : GatewayProviderType.None; } } internal void CheckGatewayProviderSettings() { switch (GatewayProvider) { case GatewayProviderType.AzureTable: if (!UseAzureSystemStore) throw new ArgumentException("Config specifies Azure based GatewayProviderType, but Azure element is not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.Config: if (!HasStaticGateways) throw new ArgumentException("Config specifies Config based GatewayProviderType, but Gateway element(s) is/are not specified.", "GatewayProvider"); break; case GatewayProviderType.Custom: if (String.IsNullOrEmpty(CustomGatewayProviderAssemblyName)) throw new ArgumentException("Config specifies Custom GatewayProviderType, but CustomGatewayProviderAssemblyName attribute is not specified", "GatewayProvider"); break; case GatewayProviderType.None: if (!UseAzureSystemStore && !HasStaticGateways) throw new ArgumentException("Config does not specify GatewayProviderType, and also does not have the adequate defaults: no Azure and or Gateway element(s) are specified.","GatewayProvider"); break; case GatewayProviderType.AdoNet: if (!UseAdoNetSystemStore) throw new ArgumentException("Config specifies SqlServer based GatewayProviderType, but ClusterId or DataConnectionString are not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.ZooKeeper: break; } } /// <summary> /// Returns a ClientConfiguration object for connecting to a local silo (for testing). /// </summary> /// <param name="gatewayPort">Client gateway TCP port</param> /// <returns>ClientConfiguration object that can be passed to GrainClient class for initialization</returns> public static ClientConfiguration LocalhostSilo(int gatewayPort = 40000) { var config = new ClientConfiguration {GatewayProvider = GatewayProviderType.Config}; config.Gateways.Add(new IPEndPoint(IPAddress.Loopback, gatewayPort)); return config; } } }
/* * Vericred API * * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,staes.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` <cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit> <tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:" <opt-num-prefix> ::= "first" <num> <unit> | "" <unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)" <value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable" <compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible> <copay> ::= "$" <num> <coinsurace> ::= <num> "%" <ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited" <opt-per-unit> ::= "per day" | "per visit" | "per stay" | "" <deductible> ::= "before deductible" | "after deductible" | "" <tier-limit> ::= ", " <limit> | "" <benefit-limit> ::= <limit> | "" ``` * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Vericred.Client; using IO.Vericred.Model; namespace IO.Vericred.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface INetworksApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Networks /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>NetworkSearchResponse</returns> NetworkSearchResponse ListNetworks (string carrierId, int? page = null, int? perPage = null); /// <summary> /// Networks /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>ApiResponse of NetworkSearchResponse</returns> ApiResponse<NetworkSearchResponse> ListNetworksWithHttpInfo (string carrierId, int? page = null, int? perPage = null); /// <summary> /// Network Details /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>NetworkDetailsResponse</returns> NetworkDetailsResponse ShowNetwork (int? id); /// <summary> /// Network Details /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>ApiResponse of NetworkDetailsResponse</returns> ApiResponse<NetworkDetailsResponse> ShowNetworkWithHttpInfo (int? id); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Networks /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of NetworkSearchResponse</returns> System.Threading.Tasks.Task<NetworkSearchResponse> ListNetworksAsync (string carrierId, int? page = null, int? perPage = null); /// <summary> /// Networks /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of ApiResponse (NetworkSearchResponse)</returns> System.Threading.Tasks.Task<ApiResponse<NetworkSearchResponse>> ListNetworksAsyncWithHttpInfo (string carrierId, int? page = null, int? perPage = null); /// <summary> /// Network Details /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>Task of NetworkDetailsResponse</returns> System.Threading.Tasks.Task<NetworkDetailsResponse> ShowNetworkAsync (int? id); /// <summary> /// Network Details /// </summary> /// <remarks> /// A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>Task of ApiResponse (NetworkDetailsResponse)</returns> System.Threading.Tasks.Task<ApiResponse<NetworkDetailsResponse>> ShowNetworkAsyncWithHttpInfo (int? id); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class NetworksApi : INetworksApi { private IO.Vericred.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="NetworksApi"/> class. /// </summary> /// <returns></returns> public NetworksApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Vericred.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="NetworksApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public NetworksApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Vericred.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Vericred.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Networks A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>NetworkSearchResponse</returns> public NetworkSearchResponse ListNetworks (string carrierId, int? page = null, int? perPage = null) { ApiResponse<NetworkSearchResponse> localVarResponse = ListNetworksWithHttpInfo(carrierId, page, perPage); return localVarResponse.Data; } /// <summary> /// Networks A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>ApiResponse of NetworkSearchResponse</returns> public ApiResponse< NetworkSearchResponse > ListNetworksWithHttpInfo (string carrierId, int? page = null, int? perPage = null) { // verify the required parameter 'carrierId' is set if (carrierId == null) throw new ApiException(400, "Missing required parameter 'carrierId' when calling NetworksApi->ListNetworks"); var localVarPath = "/networks"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (carrierId != null) localVarQueryParams.Add("carrier_id", Configuration.ApiClient.ParameterToString(carrierId)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (perPage != null) localVarQueryParams.Add("per_page", Configuration.ApiClient.ParameterToString(perPage)); // query parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ListNetworks", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<NetworkSearchResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NetworkSearchResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NetworkSearchResponse))); } /// <summary> /// Networks A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of NetworkSearchResponse</returns> public async System.Threading.Tasks.Task<NetworkSearchResponse> ListNetworksAsync (string carrierId, int? page = null, int? perPage = null) { ApiResponse<NetworkSearchResponse> localVarResponse = await ListNetworksAsyncWithHttpInfo(carrierId, page, perPage); return localVarResponse.Data; } /// <summary> /// Networks A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. This endpoint is paginated. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierId">Carrier HIOS Issuer ID</param> /// <param name="page">Page of paginated response (optional)</param> /// <param name="perPage">Responses per page (optional)</param> /// <returns>Task of ApiResponse (NetworkSearchResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<NetworkSearchResponse>> ListNetworksAsyncWithHttpInfo (string carrierId, int? page = null, int? perPage = null) { // verify the required parameter 'carrierId' is set if (carrierId == null) throw new ApiException(400, "Missing required parameter 'carrierId' when calling NetworksApi->ListNetworks"); var localVarPath = "/networks"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (carrierId != null) localVarQueryParams.Add("carrier_id", Configuration.ApiClient.ParameterToString(carrierId)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (perPage != null) localVarQueryParams.Add("per_page", Configuration.ApiClient.ParameterToString(perPage)); // query parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ListNetworks", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<NetworkSearchResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NetworkSearchResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NetworkSearchResponse))); } /// <summary> /// Network Details A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>NetworkDetailsResponse</returns> public NetworkDetailsResponse ShowNetwork (int? id) { ApiResponse<NetworkDetailsResponse> localVarResponse = ShowNetworkWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Network Details A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>ApiResponse of NetworkDetailsResponse</returns> public ApiResponse< NetworkDetailsResponse > ShowNetworkWithHttpInfo (int? id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling NetworksApi->ShowNetwork"); var localVarPath = "/networks/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ShowNetwork", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<NetworkDetailsResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NetworkDetailsResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NetworkDetailsResponse))); } /// <summary> /// Network Details A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>Task of NetworkDetailsResponse</returns> public async System.Threading.Tasks.Task<NetworkDetailsResponse> ShowNetworkAsync (int? id) { ApiResponse<NetworkDetailsResponse> localVarResponse = await ShowNetworkAsyncWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Network Details A network is a list of the doctors, other health care providers, and hospitals that a plan has contracted with to provide medical care to its members. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Primary key of the network</param> /// <returns>Task of ApiResponse (NetworkDetailsResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<NetworkDetailsResponse>> ShowNetworkAsyncWithHttpInfo (int? id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling NetworksApi->ShowNetwork"); var localVarPath = "/networks/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ShowNetwork", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<NetworkDetailsResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NetworkDetailsResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NetworkDetailsResponse))); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Mvc5AppServer.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Linq; using Monodoc; using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.WebKit; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Drawing; namespace macdoc { class LinkPageVisit : PageVisit { MyDocument document; string url; public LinkPageVisit (MyDocument document, string url) { this.document = document; this.url = url; } public override void Go () { document.LoadUrl (url, true, null, false); } } // // The OutlineView works by passing NSObject tokens around for its data. // We conveniently have a Node structure from MonoDoc that we can use // so we just wrap that in this WrapNode class // public class WrapNode : NSObject { public WrapNode (Node n) { Node = n; } public Node Node { get; set; } public static Node FromObject (NSObject obj) { return (obj as WrapNode).Node; } } // // Data source for rendering the tree // public class DocTreeDataSource : NSOutlineViewDataSource { RootTree Root = AppDelegate.Root; // We need to keep all objects that we have ever handed out to the Outline View around Dictionary<Node,WrapNode> nodeToWrapper; static Node GetNode (NSObject obj) { return WrapNode.FromObject (obj); } public DocTreeDataSource (MyDocument parent) { nodeToWrapper = parent.nodeToWrapper; } public override NSObject GetChild (NSOutlineView outlineView, int index, NSObject item) { WrapNode wrap; Node n = (Node) (item == null ? Root.RootNode : (Node) GetNode (item)).ChildNodes [index]; if (nodeToWrapper.ContainsKey (n)) return nodeToWrapper [n]; wrap = new WrapNode (n); nodeToWrapper [n] = wrap; return wrap; } public override bool ItemExpandable (NSOutlineView outlineView, NSObject item) { if (item == null) return true; return GetNode (item).ChildNodes.Count > 0; } public override int GetChildrenCount (NSOutlineView outlineView, NSObject item) { if (item == null) return Root.RootNode.ChildNodes.Count; return GetNode (item).ChildNodes.Count; } public override NSObject GetObjectValue (NSOutlineView outlineView, NSTableColumn tableColumn, NSObject item) { if (item == null) return new NSString ("Root"); return new NSString (GetNode (item).Caption); } } // // Data source for rendering the index // public class IndexDataSource : NSTableViewSource { IndexSearcher searcher; public IndexDataSource (IndexSearcher searcher) { this.searcher = searcher; } public override int GetRowCount (NSTableView tableView) { if (searcher.Index == null) return 0; return searcher.Index.Rows; } public override NSObject GetObjectValue (NSTableView tableView, NSTableColumn tableColumn, int row) { return new NSString (searcher.Index.GetValue (row)); } } public class ResultDataSource : NSTableViewSource { struct ResultDataEntry { // value is element is a section, null if it's a section child public string SectionName { get; set; } public Result ResultSet { get; set; } public int Index { get; set; } } // Dict key is section name, value is a sorted list of section element (result it comes from and the index in it) with key being the url (to avoid duplicates) Dictionary<string, SortedList<string, Tuple<Result, int>>> sections = new Dictionary<string, SortedList<string, Tuple<Result, int>>> (); List<ResultDataEntry> data = new List<ResultDataEntry> (); NSTextFieldCell normalCell; NSTableHeaderCell headerCell; public ResultDataSource () { normalCell = new NSTextFieldCell (); headerCell = new NSTableHeaderCell (); headerCell.LineBreakMode = NSLineBreakMode.TruncatingMiddle; headerCell.FocusRingType = NSFocusRingType.None; headerCell.Editable = false; headerCell.Selectable = false; } public void AddResultSet (Result result) { for (int i = 0; i < result.Count; i++) { string fullTitle = result.GetFullTitle (i); string section = string.IsNullOrWhiteSpace (fullTitle) ? "Other" : fullTitle.Split (':')[0]; SortedList<string, Tuple<Result, int>> sectionContent; var newItem = Tuple.Create (result, i); var url = result.GetUrl (i); if (!sections.TryGetValue (section, out sectionContent)) sections[section] = new SortedList<string, Tuple<Result, int>> () { { url, newItem } }; else sectionContent[url] = newItem; } // Flatten everything back to a list data.Clear (); foreach (var kvp in sections) { data.Add (new ResultDataEntry { SectionName = kvp.Key }); foreach (var item in kvp.Value) data.Add (new ResultDataEntry { ResultSet = item.Value.Item1, Index = item.Value.Item2 }); } } public void ClearResultSet () { sections.Clear (); } public override int GetRowCount (NSTableView tableView) { return data.Count; } public override NSCell GetCell (NSTableView tableView, NSTableColumn tableColumn, int row) { if (tableView == null) return null; var resultEntry = data[row]; return !string.IsNullOrEmpty (resultEntry.SectionName) ? headerCell : normalCell; } public string GetResultUrl (int row) { if (data == null || row >= data.Count || row < 0) return null; var resultEntry = data[row]; return resultEntry.ResultSet == null ? null : resultEntry.ResultSet.GetUrl (resultEntry.Index); } public override NSObject GetObjectValue (NSTableView tableView, NSTableColumn tableColumn, int row) { var resultEntry = data[row]; return new NSString (!string.IsNullOrEmpty (resultEntry.SectionName) ? resultEntry.SectionName : resultEntry.ResultSet.GetTitle (resultEntry.Index)); } public override bool ShouldSelectRow (NSTableView tableView, int row) { // If it's a section, do not select return string.IsNullOrEmpty (data[row].SectionName); } // Keep the search term in memory so that heavy search can check if its result are still fresh enough public string LatestSearchTerm { get; set; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect.Configuration; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Util; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using QuantConnect.Lean.Engine.DataFeeds; using DateTime = System.DateTime; using Log = QuantConnect.Logging.Log; namespace QuantConnect.ToolBox.CoarseUniverseGenerator { /// <summary> /// Coarse /// </summary> public class CoarseUniverseGeneratorProgram { private readonly DirectoryInfo _dailyDataFolder; private readonly DirectoryInfo _destinationFolder; private readonly DirectoryInfo _fineFundamentalFolder; private readonly IMapFileProvider _mapFileProvider; private readonly IFactorFileProvider _factorFileProvider; private readonly string _market; private readonly FileInfo _blackListedTickersFile; /// <summary> /// Runs the Coarse universe generator with default values. /// </summary> /// <returns></returns> public static bool CoarseUniverseGenerator() { var dailyDataFolder = new DirectoryInfo(Path.Combine(Globals.DataFolder, SecurityType.Equity.SecurityTypeToLower(), Market.USA, Resolution.Daily.ResolutionToLower())); var destinationFolder = new DirectoryInfo(Path.Combine(Globals.DataFolder, SecurityType.Equity.SecurityTypeToLower(), Market.USA, "fundamental", "coarse")); var fineFundamentalFolder = new DirectoryInfo(Path.Combine(dailyDataFolder.Parent.FullName, "fundamental", "fine")); var blackListedTickersFile = new FileInfo("blacklisted-tickers.txt"); var reservedWordPrefix = Config.Get("reserved-words-prefix", "quantconnect-"); var dataProvider = new DefaultDataProvider(); var mapFileProvider = new LocalDiskMapFileProvider(); mapFileProvider.Initialize(dataProvider); var factorFileProvider = new LocalDiskFactorFileProvider(); factorFileProvider.Initialize(mapFileProvider, dataProvider); var generator = new CoarseUniverseGeneratorProgram(dailyDataFolder, destinationFolder, fineFundamentalFolder, Market.USA, blackListedTickersFile, reservedWordPrefix, mapFileProvider, factorFileProvider); return generator.Run(); } /// <summary> /// Initializes a new instance of the <see cref="CoarseUniverseGeneratorProgram"/> class. /// </summary> /// <param name="dailyDataFolder">The daily data folder.</param> /// <param name="destinationFolder">The destination folder.</param> /// <param name="market">The market.</param> /// <param name="blackListedTickersFile">The black listed tickers file.</param> /// <param name="reservedWordsPrefix">The reserved words prefix.</param> /// <param name="mapFileProvider">The map file provider.</param> /// <param name="factorFileProvider">The factor file provider.</param> /// <param name="debugEnabled">if set to <c>true</c> [debug enabled].</param> public CoarseUniverseGeneratorProgram( DirectoryInfo dailyDataFolder, DirectoryInfo destinationFolder, DirectoryInfo fineFundamentalFolder, string market, FileInfo blackListedTickersFile, string reservedWordsPrefix, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider, bool debugEnabled = false) { _blackListedTickersFile = blackListedTickersFile; _market = market; _factorFileProvider = factorFileProvider; _mapFileProvider = mapFileProvider; _destinationFolder = destinationFolder; _dailyDataFolder = dailyDataFolder; _fineFundamentalFolder = fineFundamentalFolder; Log.DebuggingEnabled = debugEnabled; } /// <summary> /// Runs this instance. /// </summary> /// <returns></returns> public bool Run() { var startTime = DateTime.UtcNow; var success = true; Log.Trace($"CoarseUniverseGeneratorProgram.ProcessDailyFolder(): Processing: {_dailyDataFolder.FullName}"); var symbolsProcessed = 0; var filesRead = 0; var dailyFilesNotFound = 0; var coarseFilesGenerated = 0; var mapFileResolver = _mapFileProvider.Get(new AuxiliaryDataKey(_market, SecurityType.Equity)); var blackListedTickers = new HashSet<string>(); if (_blackListedTickersFile.Exists) { blackListedTickers = File.ReadAllLines(_blackListedTickersFile.FullName).ToHashSet(); } if (!_fineFundamentalFolder.Exists) { Log.Error($"CoarseUniverseGenerator.Run(): FAIL, Fine Fundamental folder not found at {_fineFundamentalFolder}! "); return false; } var securityIdentifierContexts = PopulateSidContex(mapFileResolver, blackListedTickers); var dailyPricesByTicker = new ConcurrentDictionary<string, List<TradeBar>>(); var outputCoarseContent = new ConcurrentDictionary<DateTime, List<string>>(); var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount / 2) }; try { Parallel.ForEach(securityIdentifierContexts, parallelOptions, sidContext => { var symbol = new Symbol(sidContext.SID, sidContext.LastTicker); var symbolCount = Interlocked.Increment(ref symbolsProcessed); Log.Debug($"CoarseUniverseGeneratorProgram.Run(): Processing {symbol} with tickers: '{string.Join(",", sidContext.Tickers)}'"); var factorFile = _factorFileProvider.Get(symbol); // Populate dailyPricesByTicker with all daily data by ticker for all tickers of this security. foreach (var ticker in sidContext.Tickers) { var dailyFile = new FileInfo(Path.Combine(_dailyDataFolder.FullName, $"{ticker}.zip")); if (!dailyFile.Exists) { Log.Debug($"CoarseUniverseGeneratorProgram.Run(): {dailyFile.FullName} not found, looking for daily data in data folder"); dailyFile = new FileInfo(Path.Combine(Globals.DataFolder, "equity", "usa", "daily", $"{ticker}.zip")); if (!dailyFile.Exists) { Log.Error($"CoarseUniverseGeneratorProgram.Run(): {dailyFile} not found!"); Interlocked.Increment(ref dailyFilesNotFound); continue; } } if (!dailyPricesByTicker.ContainsKey(ticker)) { dailyPricesByTicker.AddOrUpdate(ticker, ParseDailyFile(dailyFile)); Interlocked.Increment(ref filesRead); } } // Look for daily data for each ticker of the actual security for (int mapFileRowIndex = sidContext.MapFileRows.Length - 1; mapFileRowIndex >= 1; mapFileRowIndex--) { var ticker = sidContext.MapFileRows[mapFileRowIndex].Item2.ToLowerInvariant(); var endDate = sidContext.MapFileRows[mapFileRowIndex].Item1; var startDate = sidContext.MapFileRows[mapFileRowIndex - 1].Item1; List<TradeBar> tickerDailyData; if (!dailyPricesByTicker.TryGetValue(ticker, out tickerDailyData)) { Log.Error($"CoarseUniverseGeneratorProgram.Run(): Daily data for ticker {ticker.ToUpperInvariant()} not found!"); continue; } var tickerFineFundamentalFolder = Path.Combine(_fineFundamentalFolder.FullName, ticker); var fineAvailableDates = Enumerable.Empty<DateTime>(); if (Directory.Exists(tickerFineFundamentalFolder)) { fineAvailableDates = Directory.GetFiles(tickerFineFundamentalFolder, "*.zip") .Select(f => DateTime.ParseExact(Path.GetFileNameWithoutExtension(f), DateFormat.EightCharacter, CultureInfo.InvariantCulture)) .ToList(); } else { Log.Debug($"CoarseUniverseGeneratorProgram.Run(): fine folder was not found at '{tickerFineFundamentalFolder}'"); } // Get daily data only for the time the ticker was foreach (var tradeBar in tickerDailyData.Where(tb => tb.Time >= startDate && tb.Time <= endDate)) { var coarseRow = GenerateFactorFileRow(ticker, sidContext, factorFile as CorporateFactorProvider, tradeBar, fineAvailableDates, _fineFundamentalFolder); outputCoarseContent.AddOrUpdate(tradeBar.Time, new List<string> { coarseRow }, (time, list) => { lock (list) { list.Add(coarseRow); return list; } }); } } if (symbolCount % 1000 == 0) { var elapsed = DateTime.UtcNow - startTime; Log.Trace($"CoarseUniverseGeneratorProgram.Run(): Processed {symbolCount} in {elapsed:g} at {symbolCount / elapsed.TotalMinutes:F2} symbols/minute "); } }); _destinationFolder.Create(); var startWriting = DateTime.UtcNow; Parallel.ForEach(outputCoarseContent, coarseByDate => { var filename = $"{coarseByDate.Key.ToString(DateFormat.EightCharacter, CultureInfo.InvariantCulture)}.csv"; var filePath = Path.Combine(_destinationFolder.FullName, filename); Log.Debug($"CoarseUniverseGeneratorProgram.Run(): Saving {filename} with {coarseByDate.Value.Count} entries."); File.WriteAllLines(filePath, coarseByDate.Value.OrderBy(cr => cr)); var filesCount = Interlocked.Increment(ref coarseFilesGenerated); if (filesCount % 1000 == 0) { var elapsed = DateTime.UtcNow - startWriting; Log.Trace($"CoarseUniverseGeneratorProgram.Run(): Processed {filesCount} in {elapsed:g} at {filesCount / elapsed.TotalSeconds:F2} files/second "); } }); Log.Trace($"\n\nTotal of {coarseFilesGenerated} coarse files generated in {DateTime.UtcNow - startTime:g}:\n" + $"\t => {filesRead} daily data files read.\n"); } catch (Exception e) { Log.Error(e, $"CoarseUniverseGeneratorProgram.Run(): FAILED!"); success = false; } return success; } /// <summary> /// Generates the factor file row. /// </summary> /// <param name="ticker">The ticker.</param> /// <param name="sidContext">The sid context.</param> /// <param name="factorFile">The factor file.</param> /// <param name="tradeBar">The trade bar.</param> /// <param name="fineAvailableDates">The fine available dates.</param> /// <param name="fineFundamentalFolder">The fine fundamental folder.</param> /// <returns></returns> private static string GenerateFactorFileRow(string ticker, SecurityIdentifierContext sidContext, CorporateFactorProvider factorFile, TradeBar tradeBar, IEnumerable<DateTime> fineAvailableDates, DirectoryInfo fineFundamentalFolder) { var date = tradeBar.Time; var factorFileRow = factorFile?.GetScalingFactors(date); var dollarVolume = Math.Truncate(tradeBar.Close * tradeBar.Volume); var priceFactor = factorFileRow?.PriceFactor.Normalize() ?? 1m; var splitFactor = factorFileRow?.SplitFactor.Normalize() ?? 1m; bool hasFundamentalData = CheckFundamentalData(date, sidContext.MapFile, fineAvailableDates, fineFundamentalFolder); // sid,symbol,close,volume,dollar volume,has fundamental data,price factor,split factor var coarseFileLine = $"{sidContext.SID},{ticker.ToUpperInvariant()},{tradeBar.Close.Normalize()},{tradeBar.Volume.Normalize()},{Math.Truncate(dollarVolume)},{hasFundamentalData},{priceFactor},{splitFactor}"; return coarseFileLine; } /// <summary> /// Checks if there is fundamental data for /// </summary> /// <param name="ticker">The ticker.</param> /// <param name="date">The date.</param> /// <param name="mapFile">The map file.</param> /// <param name="fineAvailableDates"></param> /// <param name="fineFundamentalFolder">The fine fundamental folder.</param> /// <returns></returns> private static bool CheckFundamentalData(DateTime date, MapFile mapFile, IEnumerable<DateTime> fineAvailableDates, DirectoryInfo fineFundamentalFolder) { // Check if security has fine file within a trailing month for a date-ticker set. // There are tricky cases where a folder named by a ticker can have data for multiple securities. // e.g GOOG -> GOOGL (GOOG T1AZ164W5VTX) / GOOCV -> GOOG (GOOCV VP83T1ZUHROL) case. // The fine data in the 'fundamental/fine/goog' folder will be for 'GOOG T1AZ164W5VTX' up to the 2014-04-02 and for 'GOOCV VP83T1ZUHROL' afterward. // Therefore, date before checking if the security has fundamental data for a date, we need to filter the fine files the map's first date. var firstDate = mapFile?.FirstDate ?? DateTime.MinValue; var hasFundamentalDataForDate = fineAvailableDates.Where(d => d >= firstDate).Any(d => date.AddMonths(-1) <= d && d <= date); // The following section handles mergers and acquisitions cases. // e.g. YHOO -> AABA (YHOO R735QTJ8XC9X) // The dates right after the acquisition, valid fine fundamental data for AABA are still under the former ticker folder. // Therefore if no fine fundamental data is found in the 'fundamental/fine/aaba' folder, it searches into the 'yhoo' folder. if (mapFile != null && mapFile.Count() > 2 && !hasFundamentalDataForDate) { var previousTicker = mapFile.LastOrDefault(m => m.Date < date)?.MappedSymbol; if (previousTicker != null) { var previousTickerFineFundamentalFolder = Path.Combine(fineFundamentalFolder.FullName, previousTicker); if (Directory.Exists(previousTickerFineFundamentalFolder)) { var previousTickerFineAvailableDates = Directory.GetFiles(previousTickerFineFundamentalFolder, "*.zip") .Select(f => DateTime.ParseExact(Path.GetFileNameWithoutExtension(f), DateFormat.EightCharacter, CultureInfo.InvariantCulture)) .ToList(); hasFundamentalDataForDate = previousTickerFineAvailableDates.Where(d => d >= firstDate).Any(d => date.AddMonths(-1) <= d && d <= date); } else { Log.Debug($"CoarseUniverseGeneratorProgram.CheckFundamentalData(): fine folder was not found at '{previousTickerFineFundamentalFolder}'"); } } } return hasFundamentalDataForDate; } /// <summary> /// Parses the daily file. /// </summary> /// <param name="dailyFile">The daily file.</param> /// <returns></returns> private static List<TradeBar> ParseDailyFile(FileInfo dailyFile) { var scaleFactor = 1 / 10000m; var output = new List<TradeBar>(); using (var fileStream = dailyFile.OpenRead()) using (var stream = Compression.UnzipStreamToStreamReader(fileStream)) { while (!stream.EndOfStream) { var tradeBar = new TradeBar { Time = stream.GetDateTime(), Open = stream.GetDecimal() * scaleFactor, High = stream.GetDecimal() * scaleFactor, Low = stream.GetDecimal() * scaleFactor, Close = stream.GetDecimal() * scaleFactor, Volume = stream.GetDecimal() }; output.Add(tradeBar); } } return output; } /// <summary> /// Populates the sid contex. /// </summary> /// <param name="mapFileResolver">The map file resolver.</param> /// <param name="exclusions">The exclusions.</param> /// <returns></returns> private IEnumerable<SecurityIdentifierContext> PopulateSidContex(MapFileResolver mapFileResolver, HashSet<string> exclusions) { Log.Trace("CoarseUniverseGeneratorProgram.PopulateSidContex(): Generating SID context from QuantQuote's map files."); foreach (var mapFile in mapFileResolver) { if (exclusions.Contains(mapFile.Last().MappedSymbol)) { continue; } yield return new SecurityIdentifierContext(mapFile, _market); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // 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.Globalization; using System.Linq; namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Targets; /// <summary> /// Keeps logging configuration and provides simple API /// to modify it. /// </summary> public class LoggingConfiguration { private readonly IDictionary<string, Target> targets = new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase); private object[] configItems; /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration() { this.LoggingRules = new List<LoggingRule>(); } /// <summary> /// Gets the variables defined in the configuration. /// </summary> /// <remarks> /// Returns null if not configured using XML configuration. /// </remarks> public virtual Dictionary<string, string> Variables { get { throw new NotSupportedException("Variables is only supported in XmlConfiguration"); } } /// <summary> /// Gets a collection of named targets specified in the configuration. /// </summary> /// <returns> /// A list of named targets. /// </returns> /// <remarks> /// Unnamed targets (such as those wrapped by other targets) are not returned. /// </remarks> public ReadOnlyCollection<Target> ConfiguredNamedTargets { get { return new List<Target>(this.targets.Values).AsReadOnly(); } } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// </summary> public virtual IEnumerable<string> FileNamesToWatch { get { return new string[0]; } } /// <summary> /// Gets the collection of logging rules. /// </summary> public IList<LoggingRule> LoggingRules { get; private set; } /// <summary> /// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get; set; } /// <summary> /// Gets all targets. /// </summary> public ReadOnlyCollection<Target> AllTargets { get { return this.configItems.OfType<Target>().ToList().AsReadOnly(); } } /// <summary> /// Registers the specified target object under a given name. /// </summary> /// <param name="name"> /// Name of the target. /// </param> /// <param name="target"> /// The target object. /// </param> public void AddTarget(string name, Target target) { if (name == null) { throw new ArgumentException("Target name cannot be null", "name"); } InternalLogger.Debug("Registering target {0}: {1}", name, target.GetType().FullName); this.targets[name] = target; } /// <summary> /// Finds the target with the specified name. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <returns> /// Found target or <see langword="null"/> when the target is not found. /// </returns> public Target FindTargetByName(string name) { Target value; if (!this.targets.TryGetValue(name, out value)) { return null; } return value; } /// <summary> /// Called by LogManager when one of the log configuration files changes. /// </summary> /// <returns> /// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration. /// </returns> public virtual LoggingConfiguration Reload() { return this; } /// <summary> /// Removes the specified named target. /// </summary> /// <param name="name"> /// Name of the target. /// </param> public void RemoveTarget(string name) { this.targets.Remove(name); } /// <summary> /// Installs target-specific objects on current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Installation typically runs with administrative permissions. /// </remarks> public void Install(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); foreach (IInstallable installable in this.configItems.OfType<IInstallable>()) { installationContext.Info("Installing '{0}'", installable); try { installable.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installable); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } installationContext.Error("'{0}' installation failed: {1}.", installable, exception); } } } /// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); foreach (IInstallable installable in this.configItems.OfType<IInstallable>()) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } installationContext.Error("Uninstallation of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Closes all targets and releases any unmanaged resources. /// </summary> internal void Close() { InternalLogger.Debug("Closing logging configuration..."); foreach (ISupportsInitialize initialize in this.configItems.OfType<ISupportsInitialize>()) { InternalLogger.Trace("Closing {0}", initialize); try { initialize.Close(); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Exception while closing {0}", exception); } } InternalLogger.Debug("Finished closing logging configuration."); } internal void Dump() { if (!InternalLogger.IsDebugEnabled) { return; } InternalLogger.Debug("--- NLog configuration dump. ---"); InternalLogger.Debug("Targets:"); foreach (Target target in this.targets.Values) { InternalLogger.Info("{0}", target); } InternalLogger.Debug("Rules:"); foreach (LoggingRule rule in this.LoggingRules) { InternalLogger.Info("{0}", rule); } InternalLogger.Debug("--- End of NLog configuration dump ---"); } /// <summary> /// Flushes any pending log messages on all appenders. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> internal void FlushAllTargets(AsyncContinuation asyncContinuation) { var uniqueTargets = new List<Target>(); foreach (var rule in this.LoggingRules) { foreach (var t in rule.Targets) { if (!uniqueTargets.Contains(t)) { uniqueTargets.Add(t); } } } AsyncHelpers.ForEachItemInParallel(uniqueTargets, asyncContinuation, (target, cont) => target.Flush(cont)); } /// <summary> /// Validates the configuration. /// </summary> internal void ValidateConfig() { var roots = new List<object>(); foreach (LoggingRule r in this.LoggingRules) { roots.Add(r); } foreach (Target target in this.targets.Values) { roots.Add(target); } this.configItems = ObjectGraphScanner.FindReachableObjects<object>(roots.ToArray()); // initialize all config items starting from most nested first // so that whenever the container is initialized its children have already been InternalLogger.Info("Found {0} configuration items", this.configItems.Length); foreach (object o in this.configItems) { PropertyHelper.CheckRequiredParameters(o); } } internal void InitializeAll() { this.ValidateConfig(); foreach (ISupportsInitialize initialize in this.configItems.OfType<ISupportsInitialize>().Reverse()) { InternalLogger.Trace("Initializing {0}", initialize); try { initialize.Initialize(this); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error during initialization of " + initialize, exception); } } } } internal void EnsureInitialized() { this.InitializeAll(); } } }
using System; /* * $Id: Inflate.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $ * Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) * and contributors of zlib. */ namespace Org.BouncyCastle.Utilities.Zlib { public enum InflateMode : int { /// <summary> ///waiting for method byte /// </summary> METHOD = 0, /// <summary> /// waiting for flag byte /// </summary> FLAG = 1, /// <summary> /// four dictionary check bytes to go /// </summary> DICT4 = 2, /// <summary> /// three dictionary check bytes to go /// </summary> DICT3 = 3, /// <summary> /// two dictionary check bytes to go /// </summary> DICT2 = 4, /// <summary> /// one dictionary check byte to go /// </summary> DICT1 = 5, /// <summary> /// waiting for inflateSetDictionary /// </summary> DICT0 = 6, /// <summary> /// decompressing blocks /// </summary> BLOCKS = 7, /// <summary> /// four check bytes to go /// </summary> CHECK4 = 8, /// <summary> /// three check bytes to go /// </summary> CHECK3 = 9, /// <summary> /// two check bytes to go /// </summary> CHECK2 = 10, /// <summary> /// one check byte to go /// </summary> CHECK1 = 11, /// <summary> /// finished check, done /// </summary> DONE = 12, /// <summary> /// got an error--stay here /// </summary> BAD = 13 } internal sealed class Inflate { /// <summary> /// 32K LZ77 window /// </summary> private const int MAX_WBITS = 15; /// <summary> /// Preset dictionary flag in zlib header /// </summary> private const int PRESET_DICT = 0x20; private const int Z_DEFLATED = 8; private static readonly byte[] mark = { (byte)0, (byte)0, (byte)0xff, (byte)0xff }; /// <summary> /// if FLAGS, method byte /// </summary> private int method; /// <summary> /// Computed check value /// </summary> private long[] was = new long[1]; /// <summary> /// The stream check value /// </summary> private long need; /// <summary> /// if BAD, inflateSync's marker bytes count /// </summary> private int marker; // mode independent information /// <summary> /// Flag for no wrapper /// </summary> private int nowrap; /// <summary> /// log2(window size) (8..15, defaults to 15) /// </summary> private int wbits; /// <summary> /// Current inflate_blocks state /// </summary> private InfBlocks blocks; /// <summary> /// Gets the current inflate mode. /// </summary> /// <value> /// The mode. /// </value> internal InflateMode Mode { get; private set; } internal ZLibStatus InflateReset(ZStream z) { if (z == null || z.istate == null) return ZLibStatus.Z_STREAM_ERROR; z.total_in = z.total_out = 0; z.msg = null; z.istate.Mode = z.istate.nowrap != 0 ? InflateMode.BLOCKS : InflateMode.METHOD; z.istate.blocks.Reset(z, null); return ZLibStatus.Z_OK; } internal ZLibStatus InflateEnd(ZStream z) { if (blocks != null) blocks.free(z); blocks = null; // ZFREE(z, z->state); return ZLibStatus.Z_OK; } internal ZLibStatus InflateInit(ZStream z, int w) { z.msg = null; blocks = null; // handle undocumented nowrap option (no zlib header or check) nowrap = 0; if (w < 0) { w = -w; nowrap = 1; } // set window size if (w < 8 || w > 15) { InflateEnd(z); return ZLibStatus.Z_STREAM_ERROR; } wbits = w; z.istate.blocks = new InfBlocks(z, z.istate.nowrap != 0 ? null : this, 1 << w); // reset state InflateReset(z); return ZLibStatus.Z_OK; } internal ZLibStatus inflate(ZStream z, FlushType ff) { ZLibStatus r; int b; if (z == null || z.istate == null || z.next_in == null) return ZLibStatus.Z_STREAM_ERROR; var f = ff == FlushType.Z_FINISH ? ZLibStatus.Z_BUF_ERROR : ZLibStatus.Z_OK; r = ZLibStatus.Z_BUF_ERROR; while (true) { //System.out.println("mode: "+z.istate.mode); switch (z.istate.Mode) { case InflateMode.METHOD: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; if (((z.istate.method = z.next_in[z.next_in_index++]) & 0xf) != Z_DEFLATED) { z.istate.Mode = InflateMode.BAD; z.msg = "unknown compression method"; z.istate.marker = 5; // can't try inflateSync break; } if ((z.istate.method >> 4) + 8 > z.istate.wbits) { z.istate.Mode = InflateMode.BAD; z.msg = "invalid window size"; z.istate.marker = 5; // can't try inflateSync break; } z.istate.Mode = InflateMode.FLAG; goto case InflateMode.FLAG; case InflateMode.FLAG: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; b = (z.next_in[z.next_in_index++]) & 0xff; if ((((z.istate.method << 8) + b) % 31) != 0) { z.istate.Mode = InflateMode.BAD; z.msg = "incorrect header check"; z.istate.marker = 5; // can't try inflateSync break; } if ((b & PRESET_DICT) == 0) { z.istate.Mode = InflateMode.BLOCKS; break; } z.istate.Mode = InflateMode.DICT4; goto case InflateMode.DICT4; case InflateMode.DICT4: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & 0xff000000L; z.istate.Mode = InflateMode.DICT3; goto case InflateMode.DICT3; case InflateMode.DICT3: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L; z.istate.Mode = InflateMode.DICT2; goto case InflateMode.DICT2; case InflateMode.DICT2: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L; z.istate.Mode = InflateMode.DICT1; goto case InflateMode.DICT1; case InflateMode.DICT1: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (z.next_in[z.next_in_index++] & 0xffL); z.Adler = z.istate.need; z.istate.Mode = InflateMode.DICT0; return ZLibStatus.Z_NEED_DICT; case InflateMode.DICT0: z.istate.Mode = InflateMode.BAD; z.msg = "need dictionary"; z.istate.marker = 0; // can try inflateSync return ZLibStatus.Z_STREAM_ERROR; case InflateMode.BLOCKS: r = z.istate.blocks.ProcessBlocks(z, r); if (r == ZLibStatus.Z_DATA_ERROR) { z.istate.Mode = InflateMode.BAD; z.istate.marker = 0; // can try inflateSync break; } if (r == ZLibStatus.Z_OK) { r = f; } if (r != ZLibStatus.Z_STREAM_END) { return r; } r = f; z.istate.blocks.Reset(z, z.istate.was); if (z.istate.nowrap != 0) { z.istate.Mode = InflateMode.DONE; break; } z.istate.Mode = InflateMode.CHECK4; goto case InflateMode.CHECK4; case InflateMode.CHECK4: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & 0xff000000L; z.istate.Mode = InflateMode.CHECK3; goto case InflateMode.CHECK3; case InflateMode.CHECK3: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L; z.istate.Mode = InflateMode.CHECK2; goto case InflateMode.CHECK2; case InflateMode.CHECK2: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L; z.istate.Mode = InflateMode.CHECK1; goto case InflateMode.CHECK1; case InflateMode.CHECK1: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (z.next_in[z.next_in_index++] & 0xffL); if (((int)(z.istate.was[0])) != ((int)(z.istate.need))) { z.istate.Mode = InflateMode.BAD; z.msg = "incorrect data check"; z.istate.marker = 5; // can't try inflateSync break; } z.istate.Mode = InflateMode.DONE; goto case InflateMode.DONE; case InflateMode.DONE: return ZLibStatus.Z_STREAM_END; case InflateMode.BAD: return ZLibStatus.Z_DATA_ERROR; default: return ZLibStatus.Z_STREAM_ERROR; } } } //internal ZLibStatus InflateSetDictionary(ZStream z, byte[] dictionary, int dictLength) //{ // int index = 0; // int length = dictLength; // if (z == null || z.istate == null || z.istate.Mode != InflateMode.DICT0) // return ZLibStatus.Z_STREAM_ERROR; // if (z.Adler32(1L, dictionary, 0, dictLength) != z.Adler) // { // return ZLibStatus.Z_DATA_ERROR; // } // //z.adler = z.Adler32(0, null, 0, 0); // z.UpdateAdler(0, null, 0, 0); // if (length >= (1 << z.istate.wbits)) // { // length = (1 << z.istate.wbits) - 1; // index = dictLength - length; // } // z.istate.blocks.set_dictionary(dictionary, index, length); // z.istate.Mode = InflateMode.BLOCKS; // return ZLibStatus.Z_OK; //} internal ZLibStatus InflateSync(ZStream z) { int n; // number of bytes to look at int p; // pointer to bytes int m; // number of marker bytes found in a row long r, w; // temporaries to save total_in and total_out // set up if (z == null || z.istate == null) return ZLibStatus.Z_STREAM_ERROR; if (z.istate.Mode != InflateMode.BAD) { z.istate.Mode = InflateMode.BAD; z.istate.marker = 0; } if ((n = z.avail_in) == 0) return ZLibStatus.Z_BUF_ERROR; p = z.next_in_index; m = z.istate.marker; // search while (n != 0 && m < 4) { if (z.next_in[p] == mark[m]) { m++; } else if (z.next_in[p] != 0) { m = 0; } else { m = 4 - m; } p++; n--; } // restore z.total_in += p - z.next_in_index; z.next_in_index = p; z.avail_in = n; z.istate.marker = m; // return no joy or set up to restart on a new block if (m != 4) { return ZLibStatus.Z_DATA_ERROR; } r = z.total_in; w = z.total_out; InflateReset(z); z.total_in = r; z.total_out = w; z.istate.Mode = InflateMode.BLOCKS; return ZLibStatus.Z_OK; } // Returns true if inflate is currently at the end of a block generated // by FlushType.Z_SYNC_FLUSH or FlushType.Z_FULL_FLUSH. This function is used by one PPP // implementation to provide an additional safety check. PPP uses FlushType.Z_SYNC_FLUSH // but removes the length bytes of the resulting empty stored block. When // decompressing, PPP checks that at the end of input packet, inflate is // waiting for these length bytes. //internal ZLibStatus InflateSyncPoint(ZStream z) //{ // if (z == null || z.istate == null || z.istate.blocks == null) // return ZLibStatus.Z_STREAM_ERROR; // return z.istate.blocks.sync_point(); //} } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here * xxxx-xx-xx, author, fix bug about xxx */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; namespace rDSN.Tron.Utility { public class Configuration : Singleton<Configuration> { private Dictionary<string, Dictionary<string, string>> _sectionParams = new Dictionary<string, Dictionary<string, string>>(); private const string _defaultConfigFile = "config.ini"; public Configuration() { Set("TempDir", ".\\"); Set("Verbose", "true"); Set("PacketBatchSize", "64"); // KB Set("PacketBatchInterval", "5"); // ms Set("AppDomainEnabled", "false"); Set("LogFile", "stdout"); Set("VerboseRpc", "false"); Set("VerboseUDP", "false"); Set("LogPort", "localhost:50002"); Set("RpcThreadQueueThrottlingLength", "10000"); Set("MaxSendQueueBufferPerSocketInMB", "32"); Set("MaxLocalWorkingSetPerJobInMB", "512"); Set("TcpBufferSizeInMbPerSocket", "32"); Set("NodeStatReportInterval", "1000"); // ms Set("DefaultStageExecutionTimeout", "5000"); // ms //Set("Client", "XceedLicenseKey", "UNKNOWN"); Set("Client", "XceedLicenseKey", "CHT43-G1ENG-TRMGE-3YNA"); Set("Agent", "Port", "53001"); Set("Agent", "GracePeriod", "15"); Set("Agent", "LeasePeriod", "10"); Set("Agent", "MaxWorkingSetMB", "200"); LoadConfig(); SetupLogFile(); SetupMiniDump(); if (Get("DebugBreak", false)) { Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); } } public Configuration(string configFile) { LoadConfig(configFile); } private void SetupLogFile() { var logFile = Get<string>("LogFile"); var consumer = new LogConsumer(logFile); Trace.Listeners.Add(consumer); //Debug.Listeners.Add(consumer); } private void SetupMiniDump() { AppDomain.CurrentDomain.UnhandledException += MyUnhandledExceptionEventHandler; } private void MyUnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { MiniDumper.Write((".\\Minidump." + DateTime.Now.ToLongTimeString()).Replace(':', '-') + ".mdmp"); } /// <summary> /// Load config from the specified config file. /// </summary> /// <param name="configFile">The path of the config file.</param> public void LoadConfig(string configFile = _defaultConfigFile) { var currSec = ""; StreamReader sr = null; Dictionary<string, string> currentDict = null; try { sr = new StreamReader(configFile); while (true) { if (sr.EndOfStream) { break; } var line = sr.ReadLine(); if (line.IndexOf('#') != -1) { line = line.Substring(0, line.IndexOf('#')); } line = line.Trim(' ', '\t', '\r', '\n'); if ((line == "") || (line[0] == '#')) continue; if (line[0] == '[') { var newSec = line.Substring(1, line.Length - 2).Trim(); if (_sectionParams.TryGetValue(newSec, out currentDict) == false) { currentDict = new Dictionary<string, string>(); _sectionParams.Add(newSec, currentDict); } currSec = newSec; } else { if (currentDict == null) { Console.WriteLine("No section defined for current config line: " + line); continue; } // New value pair string name, value = ""; var ep = line.IndexOf('='); if (ep == -1) { name = line.Trim(); } else { name = line.Substring(0, ep).Trim(); value = line.Substring(ep + 1).Trim(); } if (currentDict.ContainsKey(name)) { Console.WriteLine("[" + currSec + "]" + name + " is redefined: " + currentDict[name] + " -> " + value); currentDict[name] = value; } else { currentDict.Add(name, value); } } } sr.Close(); } catch (Exception e) { if (e.GetType() == typeof(FileNotFoundException)) { Console.WriteLine("Config file not found. Using default."); } else { Console.WriteLine("Error loading config. " + e.Message); } sr?.Close(); } } /// <summary> /// Set an option in a section to some value. /// </summary> /// <param name="section">The section of the option.</param> /// <param name="name">The name of the option.</param> /// <param name="value">The value of the option.</param> public void Set(string section, string name, string value) { if (!_sectionParams.ContainsKey(section)) _sectionParams[section] = new Dictionary<string, string>(); _sectionParams[section][name] = value; } public void Set(string name, string value) { Set("general", name, value); } public Dictionary<string, string> GetSection(string sectionName) { Dictionary<string, string> dict; _sectionParams.TryGetValue(sectionName, out dict); return dict; } /// <summary> /// Get the value of an option in one section of type T. /// </summary> /// <typeparam name="T">The type of the option.</typeparam> /// <param name="section">The section of the option.</param> /// <param name="name">The name of the option.</param> /// <returns>The value of the option.</returns> /// private T GetValue<T>(string value, string name) { if (typeof(T) == typeof(string)) return (T)(object)value; MethodInfo method = null; try { method = typeof(T).GetMethod("Parse", new[] { typeof(string) }); } catch (Exception) { // ignored } if (method != null) { try { return (T)(method.Invoke(null, new object[] { value })); } catch (Exception e) { if (e.InnerException.GetType() == typeof(FormatException)) { Console.WriteLine("format wrong for item " + name); } return default(T); } } if (typeof(T).IsEnum) { return (T)Enum.Parse(typeof(T), value); } Console.WriteLine("config item type wrong: " + name); return default(T); } public bool TryGet<T>(string section, string name, out T val) { val = default(T); Dictionary<string, string> s; if (!_sectionParams.TryGetValue(section, out s)) return false; string ret; if (!s.TryGetValue(name, out ret) || ret == null) return false; val = GetValue<T>(ret, name); return true; } public T Get<T>(string section, string name, T defaultValue = default(T)) { T v; if (TryGet(section, name, out v)) return v; return defaultValue; } public bool TryGet<T>(string name, out T val) { return TryGet("general", name, out val); } public T Get<T>(string name, T defaultValue = default(T)) { return Get("general", name, defaultValue); } public List<string> GetAllSectionNames() { return _sectionParams.Select(kv => kv.Key).ToList(); } /// <summary> /// Save config the the specified config file. /// </summary> /// <param name="configFile">The path of the config file.</param> public void SaveConfig(string configFile = _defaultConfigFile) { var sw = new StreamWriter(configFile); foreach (var sections in _sectionParams) { sw.WriteLine("[" + sections.Key + "]"); foreach (var pair in sections.Value) { sw.WriteLine(pair.Key + " = " + pair.Value); } sw.WriteLine(); } sw.Close(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.IO; using System.Reflection; namespace Python.Runtime { /// <summary> /// Implements a Python type that provides access to CLR namespaces. The /// type behaves like a Python module, and can contain other sub-modules. /// </summary> [Serializable] internal class ModuleObject : ExtensionType { private readonly Dictionary<string, PyObject> cache = new(); internal string moduleName; internal PyDict dict; protected string _namespace; private readonly PyList __all__ = new (); // Attributes to be set on the module according to PEP302 and 451 // by the import machinery. static readonly HashSet<string?> settableAttributes = new () {"__spec__", "__file__", "__name__", "__path__", "__loader__", "__package__"}; #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. /// <remarks><seealso cref="dict"/> is initialized in <seealso cref="Create(string)"/></remarks> protected ModuleObject(string name) #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { if (name == string.Empty) { throw new ArgumentException("Name must not be empty!"); } moduleName = name; _namespace = name; } internal static NewReference Create(string name) => new ModuleObject(name).Alloc(); public override NewReference Alloc() { var py = base.Alloc(); if (dict is null) { // Use the filename from any of the assemblies just so there's something for // anything that expects __file__ to be set. var filename = "unknown"; var docstring = "Namespace containing types from the following assemblies:\n\n"; foreach (Assembly a in AssemblyManager.GetAssemblies(moduleName)) { if (!a.IsDynamic && a.Location != null) { filename = a.Location; } docstring += "- " + a.FullName + "\n"; } using var dictRef = Runtime.PyObject_GenericGetDict(py.Borrow()); dict = new PyDict(dictRef.StealOrThrow()); using var pyname = Runtime.PyString_FromString(moduleName); using var pyfilename = Runtime.PyString_FromString(filename); using var pydocstring = Runtime.PyString_FromString(docstring); BorrowedReference pycls = TypeManager.GetTypeReference(GetType()); Runtime.PyDict_SetItem(dict, PyIdentifier.__name__, pyname.Borrow()); Runtime.PyDict_SetItem(dict, PyIdentifier.__file__, pyfilename.Borrow()); Runtime.PyDict_SetItem(dict, PyIdentifier.__doc__, pydocstring.Borrow()); Runtime.PyDict_SetItem(dict, PyIdentifier.__class__, pycls); } else { SetObjectDict(py.Borrow(), new NewReference(dict).Steal()); } InitializeModuleMembers(); return py; } /// <summary> /// Returns a ClassBase object representing a type that appears in /// this module's namespace or a ModuleObject representing a child /// namespace (or null if the name is not found). This method does /// not increment the Python refcount of the returned object. /// </summary> public NewReference GetAttribute(string name, bool guess) { cache.TryGetValue(name, out var cached); if (cached != null) { return new NewReference(cached); } Type type; //if (AssemblyManager.IsValidNamespace(name)) //{ // IntPtr py_mod_name = Runtime.PyString_FromString(name); // IntPtr modules = Runtime.PyImport_GetModuleDict(); // IntPtr module = Runtime.PyDict_GetItem(modules, py_mod_name); // if (module != IntPtr.Zero) // return (ManagedType)this; // return null; //} string qname = _namespace == string.Empty ? name : _namespace + "." + name; // If the fully-qualified name of the requested attribute is // a namespace exported by a currently loaded assembly, return // a new ModuleObject representing that namespace. if (AssemblyManager.IsValidNamespace(qname)) { var m = ModuleObject.Create(qname); this.StoreAttribute(name, m.Borrow()); return m; } // Look for a type in the current namespace. Note that this // includes types, delegates, enums, interfaces and structs. // Only public namespace members are exposed to Python. type = AssemblyManager.LookupTypes(qname).FirstOrDefault(t => t.IsPublic); if (type != null) { var c = ClassManager.GetClass(type); StoreAttribute(name, c); return new NewReference(c); } // We didn't find the name, so we may need to see if there is a // generic type with this base name. If so, we'll go ahead and // return it. Note that we store the mapping of the unmangled // name to generic type - it is technically possible that some // future assembly load could contribute a non-generic type to // the current namespace with the given basename, but unlikely // enough to complicate the implementation for now. if (guess) { string? gname = GenericUtil.GenericNameForBaseName(this._namespace, name); if (gname != null) { var o = this.GetAttribute(gname, false); if (!o.IsNull()) { this.StoreAttribute(name, o.Borrow()); return o; } } } return default; } /// <summary> /// Stores an attribute in the instance dict for future lookups. /// </summary> private void StoreAttribute(string name, BorrowedReference ob) { if (Runtime.PyDict_SetItemString(dict, name, ob) != 0) { throw PythonException.ThrowLastAsClrException(); } cache[name] = new PyObject(ob); } /// <summary> /// Preloads all currently-known names for the module namespace. This /// can be called multiple times, to add names from assemblies that /// may have been loaded since the last call to the method. /// </summary> public void LoadNames() { foreach (string name in AssemblyManager.GetNames(_namespace)) { cache.TryGetValue(name, out var m); if (m != null) { continue; } BorrowedReference attr = Runtime.PyDict_GetItemString(dict, name); // If __dict__ has already set a custom property, skip it. if (!attr.IsNull) { continue; } using var attrVal = GetAttribute(name, true); if (!attrVal.IsNull()) { // if it's a valid attribute, add it to __all__ using var pyname = Runtime.PyString_FromString(name); if (Runtime.PyList_Append(__all__, pyname.Borrow()) != 0) { throw PythonException.ThrowLastAsClrException(); } } } } const BindingFlags ModuleMethodFlags = BindingFlags.Public | BindingFlags.Static; /// <summary> /// Initialize module level functions and attributes /// </summary> internal void InitializeModuleMembers() { Type funcmarker = typeof(ModuleFunctionAttribute); Type propmarker = typeof(ModulePropertyAttribute); Type ftmarker = typeof(ForbidPythonThreadsAttribute); Type type = GetType(); while (type != null) { MethodInfo[] methods = type.GetMethods(ModuleMethodFlags); foreach (MethodInfo method in methods) { object[] attrs = method.GetCustomAttributes(funcmarker, false); object[] forbid = method.GetCustomAttributes(ftmarker, false); bool allow_threads = forbid.Length == 0; if (attrs.Length > 0) { string name = method.Name; var mi = new MethodInfo[1]; mi[0] = method; using var m = new ModuleFunctionObject(type, name, mi, allow_threads).Alloc(); StoreAttribute(name, m.Borrow()); } } PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { object[] attrs = property.GetCustomAttributes(propmarker, false); if (attrs.Length > 0) { string name = property.Name; using var p = new ModulePropertyObject(property).Alloc(); StoreAttribute(name, p.Borrow()); } } type = type.BaseType; } } internal void ResetModuleMembers() { Type type = GetType(); var methods = type.GetMethods(ModuleMethodFlags) .Where(m => m.GetCustomAttribute<ModuleFunctionAttribute>() is not null) .OfType<MemberInfo>(); var properties = type.GetProperties().Where(p => p.GetCustomAttribute<ModulePropertyAttribute>() is not null); foreach (string memberName in methods.Concat(properties).Select(m => m.Name)) { if (Runtime.PyDict_DelItemString(dict, memberName) != 0) { if (!PythonException.CurrentMatches(Exceptions.KeyError)) { throw PythonException.ThrowLastAsClrException(); } Runtime.PyErr_Clear(); } cache.Remove(memberName); } } /// <summary> /// ModuleObject __getattribute__ implementation. Module attributes /// are always either classes or sub-modules representing subordinate /// namespaces. CLR modules implement a lazy pattern - the sub-modules /// and classes are created when accessed and cached for future use. /// </summary> public static NewReference tp_getattro(BorrowedReference ob, BorrowedReference key) { var self = (ModuleObject)GetManagedObject(ob)!; if (!Runtime.PyString_Check(key)) { Exceptions.SetError(Exceptions.TypeError, "string expected"); return default; } Debug.Assert(!self.dict.IsDisposed); BorrowedReference op = Runtime.PyDict_GetItem(self.dict, key); if (op != null) { return new NewReference(op); } string? name = InternString.GetManagedString(key); if (name == "__dict__") { return new NewReference(self.dict); } if (name == "__all__") { self.LoadNames(); return new NewReference(self.__all__); } NewReference attr; try { if (name is null) throw new ArgumentNullException(); attr = self.GetAttribute(name, true); } catch (Exception e) { Exceptions.SetError(e); return default; } if (attr.IsNull()) { Exceptions.SetError(Exceptions.AttributeError, name); return default; } return attr; } /// <summary> /// ModuleObject __repr__ implementation. /// </summary> public static NewReference tp_repr(BorrowedReference ob) { var self = (ModuleObject)GetManagedObject(ob)!; return Runtime.PyString_FromString($"<module '{self.moduleName}'>"); } public static int tp_traverse(BorrowedReference ob, IntPtr visit, IntPtr arg) { var self = (ModuleObject?)GetManagedObject(ob); if (self is null) return 0; Debug.Assert(self.dict == GetObjectDict(ob)); int res = PyVisit(self.dict, visit, arg); if (res != 0) return res; foreach (var attr in self.cache.Values) { res = PyVisit(attr, visit, arg); if (res != 0) return res; } return 0; } /// <summary> /// Override the setattr implementation. /// This is needed because the import mechanics need /// to set a few attributes /// </summary> [ForbidPythonThreads] public new static int tp_setattro(BorrowedReference ob, BorrowedReference key, BorrowedReference val) { var managedKey = Runtime.GetManagedString(key); if ((settableAttributes.Contains(managedKey)) || (ManagedType.GetManagedObject(val) is ModuleObject) ) { var self = (ModuleObject)ManagedType.GetManagedObject(ob)!; return Runtime.PyDict_SetItem(self.dict, key, val); } return ExtensionType.tp_setattro(ob, key, val); } protected override Dictionary<string, object?>? OnSave(BorrowedReference ob) { var context = base.OnSave(ob); System.Diagnostics.Debug.Assert(dict == GetObjectDict(ob)); // destroy the cache(s) foreach (var pair in cache) { if ((Runtime.PyDict_DelItemString(dict, pair.Key) == -1) && (Exceptions.ExceptionMatches(Exceptions.KeyError))) { // Trying to remove a key that's not in the dictionary // raises an error. We don't care about it. Runtime.PyErr_Clear(); } else if (Exceptions.ErrorOccurred()) { throw PythonException.ThrowLastAsClrException(); } } cache.Clear(); return context; } protected override void OnLoad(BorrowedReference ob, Dictionary<string, object?>? context) { base.OnLoad(ob, context); SetObjectDict(ob, new NewReference(dict).Steal()); } } /// <summary> /// The CLR module is the root handler used by the magic import hook /// to import assemblies. It has a fixed module name "clr" and doesn't /// provide a namespace. /// </summary> [Serializable] internal class CLRModule : ModuleObject { protected static bool interactive_preload = true; internal static bool preload; // XXX Test performance of new features // internal static bool _SuppressDocs = false; internal static bool _SuppressOverloads = false; static CLRModule() { Reset(); } private CLRModule() : base("clr") { _namespace = string.Empty; } internal static NewReference Create(out CLRModule module) { module = new CLRModule(); return module.Alloc(); } public static void Reset() { interactive_preload = true; preload = false; // XXX Test performance of new features // _SuppressDocs = false; _SuppressOverloads = false; } /// <summary> /// The initializing of the preload hook has to happen as late as /// possible since sys.ps1 is created after the CLR module is /// created. /// </summary> internal void InitializePreload() { if (interactive_preload) { interactive_preload = false; if (!Runtime.PySys_GetObject("ps1").IsNull) { preload = true; } else { Exceptions.Clear(); preload = false; } } } [ModuleFunction] public static bool getPreload() { return preload; } [ModuleFunction] public static void setPreload(bool preloadFlag) { preload = preloadFlag; } //[ModuleProperty] public static bool SuppressDocs { get { return _SuppressDocs; } set { _SuppressDocs = value; } } //[ModuleProperty] public static bool SuppressOverloads { get { return _SuppressOverloads; } set { _SuppressOverloads = value; } } [ModuleFunction] [ForbidPythonThreads] public static Assembly AddReference(string name) { AssemblyManager.UpdatePath(); var origNs = AssemblyManager.GetNamespaces(); Assembly? assembly = null; assembly = AssemblyManager.FindLoadedAssembly(name); if (assembly == null) { assembly = AssemblyManager.LoadAssemblyPath(name); } if (assembly == null && AssemblyManager.TryParseAssemblyName(name) is { } parsedName) { assembly = AssemblyManager.LoadAssembly(parsedName); } if (assembly == null) { assembly = AssemblyManager.LoadAssemblyFullPath(name); } if (assembly == null) { throw new FileNotFoundException($"Unable to find assembly '{name}'."); } // Classes that are not in a namespace needs an extra nudge to be found. ImportHook.UpdateCLRModuleDict(); // A bit heavyhanded, but we can't use the AssemblyManager's AssemblyLoadHandler // method because it may be called from other threads, leading to deadlocks // if it is called while Python code is executing. var currNs = AssemblyManager.GetNamespaces().Except(origNs); foreach(var ns in currNs) { ImportHook.AddNamespaceWithGIL(ns); } return assembly; } /// <summary> /// Get a Type instance for a class object. /// clr.GetClrType(IComparable) gives you the Type for IComparable, /// that you can e.g. perform reflection on. Similar to typeof(IComparable) in C# /// or clr.GetClrType(IComparable) in IronPython. /// /// </summary> /// <param name="type"></param> /// <returns>The Type object</returns> [ModuleFunction] [ForbidPythonThreads] public static Type GetClrType(Type type) { return type; } [ModuleFunction] [ForbidPythonThreads] public static string FindAssembly(string name) { AssemblyManager.UpdatePath(); return AssemblyManager.FindAssembly(name); } [ModuleFunction] public static string[] ListAssemblies(bool verbose) { AssemblyName[] assnames = AssemblyManager.ListAssemblies(); var names = new string[assnames.Length]; for (var i = 0; i < assnames.Length; i++) { if (verbose) { names[i] = assnames[i].FullName; } else { names[i] = assnames[i].Name; } } return names; } /// <summary> /// Note: This should *not* be called directly. /// The function that get/import a CLR assembly as a python module. /// This function should only be called by the import machinery as seen /// in importhook.cs /// </summary> /// <param name="spec">A ModuleSpec Python object</param> /// <returns>A new reference to the imported module, as a PyObject.</returns> [ModuleFunction] [ForbidPythonThreads] public static PyObject _load_clr_module(PyObject spec) { using var modname = spec.GetAttr("name"); string name = modname.As<string?>() ?? throw new ArgumentException("name must not be None"); var mod = ImportHook.Import(name); return mod; } [ModuleFunction] [ForbidPythonThreads] public static int _add_pending_namespaces() => ImportHook.AddPendingNamespaces(); } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class Directory { #region .NET /// <summary>Deletes an empty directory from a specified path.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param> [SecurityCritical] public static void Delete(string path) { DeleteDirectoryCore(null, null, path, false, false, true, false, PathFormat.RelativePath); } /// <summary>Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> [SecurityCritical] public static void Delete(string path, bool recursive) { DeleteDirectoryCore(null, null, path, recursive, false, !recursive, false, PathFormat.RelativePath); } #endregion // .NET /// <summary>[AlphaFS] Deletes an empty directory from a specified path.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static void Delete(string path, PathFormat pathFormat) { DeleteDirectoryCore(null, null, path, false, false, true, false, pathFormat); } /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static void Delete(string path, bool recursive, PathFormat pathFormat) { DeleteDirectoryCore(null, null, path, recursive, false, !recursive, false, pathFormat); } /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param> [SecurityCritical] public static void Delete(string path, bool recursive, bool ignoreReadOnly) { DeleteDirectoryCore(null, null, path, recursive, ignoreReadOnly, !recursive, false, PathFormat.RelativePath); } /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static void Delete(string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteDirectoryCore(null, null, path, recursive, ignoreReadOnly, !recursive, false, pathFormat); } #region Transactional /// <summary>[AlphaFS] Deletes an empty directory from a specified path.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param> [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path) { DeleteDirectoryCore(null, transaction, path, false, false, true, false, PathFormat.RelativePath); } /// <summary>[AlphaFS] Deletes an empty directory from a specified path.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { DeleteDirectoryCore(null, transaction, path, false, false, true, false, pathFormat); } /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive) { DeleteDirectoryCore(null, transaction, path, recursive, false, !recursive, false, PathFormat.RelativePath); } /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, PathFormat pathFormat) { DeleteDirectoryCore(null, transaction, path, recursive, false, !recursive, false, pathFormat); } /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param> [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly) { DeleteDirectoryCore(null, transaction, path, recursive, ignoreReadOnly, !recursive, false, PathFormat.RelativePath); } /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The name of the directory to remove.</param> /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param> /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteDirectoryCore(null, transaction, path, recursive, ignoreReadOnly, !recursive, false, pathFormat); } #endregion // Transactional #region Internal Methods /// <summary>Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary> /// <remarks>The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.</remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="fileSystemEntryInfo">A FileSystemEntryInfo instance. Use either <paramref name="fileSystemEntryInfo"/> or <paramref name="path"/>, not both.</param> /// <param name="transaction">The transaction.</param> /// <param name="path">The name of the directory to remove. Use either <paramref name="path"/> or <paramref name="fileSystemEntryInfo"/>, not both.</param> /// <param name="recursive"><see langword="true"/> to remove all files and subdirectories recursively; <see langword="false"/> otherwise only the top level empty directory.</param> /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only attribute of files and directories.</param> /// <param name="requireEmpty"><see langword="true"/> requires the directory must be empty.</param> /// <param name="continueOnNotExist"><see langword="true"/> does not throw an Exception when the file system object does not exist.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SecurityCritical] internal static void DeleteDirectoryCore(FileSystemEntryInfo fileSystemEntryInfo, KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, bool requireEmpty, bool continueOnNotExist, PathFormat pathFormat) { #region Setup if (pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); if (fileSystemEntryInfo == null) { // MSDN: .NET 3.5+: DirectoryNotFoundException: // Path does not exist or could not be found. // Path refers to a file instead of a directory. // The specified path is invalid (for example, it is on an unmapped drive). fileSystemEntryInfo = File.GetFileSystemEntryInfoCore(true, transaction, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator), continueOnNotExist, pathFormat); } if (fileSystemEntryInfo == null) return; string pathLp = fileSystemEntryInfo.LongFullPath; #endregion // Setup // Do not follow mount points nor symbolic links, but do delete the reparse point itself. // If directory is reparse point, disable recursion. if (recursive && fileSystemEntryInfo.IsReparsePoint) recursive = false; // Check to see if this is a mount point, and unmount it. if (fileSystemEntryInfo.IsMountPoint) { int lastError = Volume.DeleteVolumeMountPointCore(pathLp, true); if (lastError != Win32Errors.ERROR_SUCCESS && lastError != Win32Errors.ERROR_PATH_NOT_FOUND) NativeError.ThrowException(lastError, pathLp); // Now it is safe to delete the actual directory. } if (recursive) { // Enumerate all file system objects. foreach (var fsei in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(transaction, pathLp, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.LongFullPath)) { if (fsei.IsDirectory) DeleteDirectoryCore(fsei, transaction, null, true, ignoreReadOnly, requireEmpty, true, PathFormat.LongFullPath); else File.DeleteFileCore(transaction, fsei.LongFullPath, ignoreReadOnly, PathFormat.LongFullPath); } } #region Remove startRemoveDirectory: if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista // RemoveDirectory() / RemoveDirectoryTransacted() // In the ANSI version of this function, the name is limited to MAX_PATH characters. // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. // 2014-09-09: MSDN confirms LongPath usage. // RemoveDirectory on a symbolic link will remove the link itself. ? NativeMethods.RemoveDirectory(pathLp) : NativeMethods.RemoveDirectoryTransacted(pathLp, transaction.SafeHandle))) { int lastError = Marshal.GetLastWin32Error(); switch ((uint) lastError) { case Win32Errors.ERROR_DIR_NOT_EMPTY: if (requireEmpty) // MSDN: .NET 3.5+: IOException: The directory specified by path is not an empty directory. throw new DirectoryNotEmptyException(pathLp); goto startRemoveDirectory; case Win32Errors.ERROR_DIRECTORY: // MSDN: .NET 3.5+: DirectoryNotFoundException: Path refers to a file instead of a directory. if (File.ExistsCore(false, transaction, pathLp, PathFormat.LongFullPath)) throw new DirectoryNotFoundException(string.Format(CultureInfo.CurrentCulture, "({0}) {1}", Win32Errors.ERROR_INVALID_PARAMETER, string.Format(CultureInfo.CurrentCulture, Resources.Target_Directory_Is_A_File, pathLp))); break; case Win32Errors.ERROR_PATH_NOT_FOUND: if (continueOnNotExist) return; break; case Win32Errors.ERROR_SHARING_VIOLATION: // MSDN: .NET 3.5+: IOException: The directory is being used by another process or there is an open handle on the directory. NativeError.ThrowException(lastError, pathLp); break; case Win32Errors.ERROR_ACCESS_DENIED: var data = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = File.FillAttributeInfoCore(transaction, pathLp, ref data, false, true); if (data.dwFileAttributes != (FileAttributes) (-1)) { if ((data.dwFileAttributes & FileAttributes.ReadOnly) != 0) { // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only. if (ignoreReadOnly) { // Reset directory attributes. File.SetAttributesCore(true, transaction, pathLp, FileAttributes.Normal, true, PathFormat.LongFullPath); goto startRemoveDirectory; } // MSDN: .NET 3.5+: IOException: The directory is read-only. throw new DirectoryReadOnlyException(pathLp); } } if (dataInitialised == Win32Errors.ERROR_SUCCESS) // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission. NativeError.ThrowException(lastError, pathLp); break; } // MSDN: .NET 3.5+: IOException: // A file with the same name and location specified by path exists. // The directory specified by path is read-only, or recursive is false and path is not an empty directory. // The directory is the application's current working directory. // The directory contains a read-only file. // The directory is being used by another process. NativeError.ThrowException(lastError, pathLp); } #endregion // Remove } #endregion // Internal Methods } }
// 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. using System; using System.Collections; using System.Configuration; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Reflection; using System.Globalization; using System.DirectoryServices; using System.Security; using System.Security.Principal; using System.Security.AccessControl; using System.Management.Automation; using System.Management.Automation.Runspaces; using WebsitePanel.Providers; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.Utils; using WebsitePanel.Server.Utils; using Microsoft.Exchange.Data.Directory.Recipient; using Microsoft.Win32; using WebsitePanel.Providers.Common; using WebsitePanel.Providers.ResultObjects; using Microsoft.Exchange.Data; using Microsoft.Exchange.Data.Directory; using Microsoft.Exchange.Data.Storage; namespace WebsitePanel.Providers.HostedSolution { public class Exchange2010 : Exchange2007 { #region Static constructor static Exchange2010() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveExchangeAssembly); ExchangeRegistryPath = "SOFTWARE\\Microsoft\\ExchangeServer\\v14\\Setup"; } #endregion #region Mailboxes internal override void SetCalendarSettings(Runspace runspace, string id) { ExchangeLog.LogStart("SetCalendarSettings"); Command cmd = new Command("Set-CalendarProcessing"); cmd.Parameters.Add("Identity", id); cmd.Parameters.Add("AutomateProcessing", CalendarProcessingFlags.AutoAccept); ExecuteShellCommand(runspace, cmd); ExchangeLog.LogEnd("SetCalendarSettings"); } internal override ExchangeMailbox GetMailboxGeneralSettingsInternal(string accountName) { ExchangeLog.LogStart("GetMailboxGeneralSettingsInternal"); ExchangeLog.DebugInfo("Account: {0}", accountName); ExchangeMailbox info = new ExchangeMailbox(); info.AccountName = accountName; Runspace runSpace = null; try { runSpace = OpenRunspace(); Collection<PSObject> result = GetMailboxObject(runSpace, accountName); PSObject mailbox = result[0]; string id = GetResultObjectDN(result); string path = AddADPrefix(id); DirectoryEntry entry = GetADObject(path); //ADAccountOptions userFlags = (ADAccountOptions)entry.Properties["userAccountControl"].Value; //info.Disabled = ((userFlags & ADAccountOptions.UF_ACCOUNTDISABLE) != 0); info.Disabled = (bool)entry.InvokeGet("AccountDisabled"); info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); info.HideFromAddressBook = (bool)GetPSObjectProperty(mailbox, "HiddenFromAddressListsEnabled"); info.EnableLitigationHold = (bool)GetPSObjectProperty(mailbox, "LitigationHoldEnabled"); Command cmd = new Command("Get-User"); cmd.Parameters.Add("Identity", accountName); result = ExecuteShellCommand(runSpace, cmd); PSObject user = result[0]; info.FirstName = (string)GetPSObjectProperty(user, "FirstName"); info.Initials = (string)GetPSObjectProperty(user, "Initials"); info.LastName = (string)GetPSObjectProperty(user, "LastName"); info.Address = (string)GetPSObjectProperty(user, "StreetAddress"); info.City = (string)GetPSObjectProperty(user, "City"); info.State = (string)GetPSObjectProperty(user, "StateOrProvince"); info.Zip = (string)GetPSObjectProperty(user, "PostalCode"); info.Country = CountryInfoToString((CountryInfo)GetPSObjectProperty(user, "CountryOrRegion")); info.JobTitle = (string)GetPSObjectProperty(user, "Title"); info.Company = (string)GetPSObjectProperty(user, "Company"); info.Department = (string)GetPSObjectProperty(user, "Department"); info.Office = (string)GetPSObjectProperty(user, "Office"); info.ManagerAccount = GetManager(entry); //GetExchangeAccount(runSpace, ObjToString(GetPSObjectProperty(user, "Manager"))); info.BusinessPhone = (string)GetPSObjectProperty(user, "Phone"); info.Fax = (string)GetPSObjectProperty(user, "Fax"); info.HomePhone = (string)GetPSObjectProperty(user, "HomePhone"); info.MobilePhone = (string)GetPSObjectProperty(user, "MobilePhone"); info.Pager = (string)GetPSObjectProperty(user, "Pager"); info.WebPage = (string)GetPSObjectProperty(user, "WebPage"); info.Notes = (string)GetPSObjectProperty(user, "Notes"); } finally { CloseRunspace(runSpace); } ExchangeLog.LogEnd("GetMailboxGeneralSettingsInternal"); return info; } internal override ExchangeMailbox GetMailboxAdvancedSettingsInternal(string accountName) { ExchangeLog.LogStart("GetMailboxAdvancedSettingsInternal"); ExchangeLog.DebugInfo("Account: {0}", accountName); ExchangeMailbox info = new ExchangeMailbox(); info.AccountName = accountName; Runspace runSpace = null; try { runSpace = OpenRunspace(); Collection<PSObject> result = GetMailboxObject(runSpace, accountName); PSObject mailbox = result[0]; info.IssueWarningKB = ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "IssueWarningQuota")); info.ProhibitSendKB = ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "ProhibitSendQuota")); info.ProhibitSendReceiveKB = ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); info.KeepDeletedItemsDays = ConvertEnhancedTimeSpanToDays((EnhancedTimeSpan)GetPSObjectProperty(mailbox, "RetainDeletedItemsFor")); info.EnableLitigationHold = (bool)GetPSObjectProperty(mailbox, "LitigationHoldEnabled"); info.RecoverabelItemsSpace = ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "RecoverableItemsQuota")); info.RecoverabelItemsWarning = ConvertUnlimitedToKB((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "RecoverableItemsWarningQuota")); //Client Access Command cmd = new Command("Get-CASMailbox"); cmd.Parameters.Add("Identity", accountName); result = ExecuteShellCommand(runSpace, cmd); mailbox = result[0]; info.EnableActiveSync = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); info.EnableOWA = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); info.EnableMAPI = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); info.EnablePOP = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); info.EnableIMAP = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); //Statistics cmd = new Command("Get-MailboxStatistics"); cmd.Parameters.Add("Identity", accountName); result = ExecuteShellCommand(runSpace, cmd); if (result.Count > 0) { PSObject statistics = result[0]; Unlimited<ByteQuantifiedSize> totalItemSize = (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(statistics, "TotalItemSize"); info.TotalSizeMB = ConvertUnlimitedToMB(totalItemSize); uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); info.TotalItems = ConvertNullableToInt32(itemCount); DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); ; DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); ; info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); info.LastLogon = ConvertNullableToDateTime(lastLogonTime); } else { info.TotalSizeMB = 0; info.TotalItems = 0; info.LastLogoff = DateTime.MinValue; info.LastLogon = DateTime.MinValue; } //domain info.Domain = GetNETBIOSDomainName(); } finally { CloseRunspace(runSpace); } ExchangeLog.LogEnd("GetMailboxAdvancedSettingsInternal"); return info; } internal override ExchangeMailboxStatistics GetMailboxStatisticsInternal(string id) { ExchangeLog.LogStart("GetMailboxStatisticsInternal"); ExchangeLog.DebugInfo("Account: {0}", id); ExchangeMailboxStatistics info = new ExchangeMailboxStatistics(); Runspace runSpace = null; try { runSpace = OpenRunspace(); Collection<PSObject> result = GetMailboxObject(runSpace, id); PSObject mailbox = result[0]; string dn = GetResultObjectDN(result); string path = AddADPrefix(dn); DirectoryEntry entry = GetADObject(path); info.Enabled = !(bool)entry.InvokeGet("AccountDisabled"); info.LitigationHoldEnabled = (bool)GetPSObjectProperty(mailbox, "LitigationHoldEnabled"); info.DisplayName = (string)GetPSObjectProperty(mailbox, "DisplayName"); SmtpAddress smtpAddress = (SmtpAddress)GetPSObjectProperty(mailbox, "PrimarySmtpAddress"); if (smtpAddress != null) info.PrimaryEmailAddress = smtpAddress.ToString(); info.MaxSize = ConvertUnlimitedToBytes((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "ProhibitSendReceiveQuota")); info.LitigationHoldMaxSize = ConvertUnlimitedToBytes((Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(mailbox, "RecoverableItemsQuota")); DateTime? whenCreated = (DateTime?)GetPSObjectProperty(mailbox, "WhenCreated"); info.AccountCreated = ConvertNullableToDateTime(whenCreated); //Client Access Command cmd = new Command("Get-CASMailbox"); cmd.Parameters.Add("Identity", id); result = ExecuteShellCommand(runSpace, cmd); mailbox = result[0]; info.ActiveSyncEnabled = (bool)GetPSObjectProperty(mailbox, "ActiveSyncEnabled"); info.OWAEnabled = (bool)GetPSObjectProperty(mailbox, "OWAEnabled"); info.MAPIEnabled = (bool)GetPSObjectProperty(mailbox, "MAPIEnabled"); info.POPEnabled = (bool)GetPSObjectProperty(mailbox, "PopEnabled"); info.IMAPEnabled = (bool)GetPSObjectProperty(mailbox, "ImapEnabled"); //Statistics cmd = new Command("Get-MailboxStatistics"); cmd.Parameters.Add("Identity", id); result = ExecuteShellCommand(runSpace, cmd); if (result.Count > 0) { PSObject statistics = result[0]; Unlimited<ByteQuantifiedSize> totalItemSize = (Unlimited<ByteQuantifiedSize>)GetPSObjectProperty(statistics, "TotalItemSize"); info.TotalSize = ConvertUnlimitedToBytes(totalItemSize); uint? itemCount = (uint?)GetPSObjectProperty(statistics, "ItemCount"); info.TotalItems = ConvertNullableToInt32(itemCount); DateTime? lastLogoffTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogoffTime"); DateTime? lastLogonTime = (DateTime?)GetPSObjectProperty(statistics, "LastLogonTime"); info.LastLogoff = ConvertNullableToDateTime(lastLogoffTime); info.LastLogon = ConvertNullableToDateTime(lastLogonTime); } else { info.TotalSize = 0; info.TotalItems = 0; info.LastLogoff = DateTime.MinValue; info.LastLogon = DateTime.MinValue; } if (info.LitigationHoldEnabled) { cmd = new Command("Get-MailboxFolderStatistics"); cmd.Parameters.Add("FolderScope", "RecoverableItems"); cmd.Parameters.Add("Identity", id); result = ExecuteShellCommand(runSpace, cmd); if (result.Count > 0) { PSObject statistics = result[0]; ByteQuantifiedSize totalItemSize = (ByteQuantifiedSize)GetPSObjectProperty(statistics, "FolderAndSubfolderSize"); info.LitigationHoldTotalSize = (totalItemSize == null) ? 0 : ConvertUnlimitedToBytes(totalItemSize); Int32 itemCount = (Int32)GetPSObjectProperty(statistics, "ItemsInFolder"); info.LitigationHoldTotalItems = (itemCount == 0) ? 0 : itemCount; } } else { info.LitigationHoldTotalSize = 0; info.LitigationHoldTotalItems = 0; } } finally { CloseRunspace(runSpace); } ExchangeLog.LogEnd("GetMailboxStatisticsInternal"); return info; } internal override void SetMailboxAdvancedSettingsInternal(string organizationId, string accountName, bool enablePOP, bool enableIMAP, bool enableOWA, bool enableMAPI, bool enableActiveSync, long issueWarningKB, long prohibitSendKB, long prohibitSendReceiveKB, int keepDeletedItemsDays, int maxRecipients, int maxSendMessageSizeKB, int maxReceiveMessageSizeKB, bool enabledLitigationHold, long recoverabelItemsSpace, long recoverabelItemsWarning, string litigationHoldUrl, string litigationHoldMsg) { ExchangeLog.LogStart("SetMailboxAdvancedSettingsInternal"); ExchangeLog.DebugInfo("Account: {0}", accountName); Runspace runSpace = null; try { runSpace = OpenRunspace(); Command cmd = new Command("Set-Mailbox"); cmd.Parameters.Add("Identity", accountName); cmd.Parameters.Add("IssueWarningQuota", ConvertKBToUnlimited(issueWarningKB)); cmd.Parameters.Add("ProhibitSendQuota", ConvertKBToUnlimited(prohibitSendKB)); cmd.Parameters.Add("ProhibitSendReceiveQuota", ConvertKBToUnlimited(prohibitSendReceiveKB)); cmd.Parameters.Add("RetainDeletedItemsFor", ConvertDaysToEnhancedTimeSpan(keepDeletedItemsDays)); cmd.Parameters.Add("RecipientLimits", ConvertInt32ToUnlimited(maxRecipients)); cmd.Parameters.Add("MaxSendSize", ConvertKBToUnlimited(maxSendMessageSizeKB)); cmd.Parameters.Add("MaxReceiveSize", ConvertKBToUnlimited(maxReceiveMessageSizeKB)); cmd.Parameters.Add("LitigationHoldEnabled", enabledLitigationHold); cmd.Parameters.Add("RecoverableItemsQuota", ConvertKBToUnlimited(recoverabelItemsSpace)); cmd.Parameters.Add("RetentionUrl", litigationHoldUrl); cmd.Parameters.Add("RetentionComment", litigationHoldMsg); if (recoverabelItemsSpace != -1) cmd.Parameters.Add("RecoverableItemsWarningQuota", ConvertKBToUnlimited(recoverabelItemsWarning)); ExecuteShellCommand(runSpace, cmd); //Client Access cmd = new Command("Set-CASMailbox"); cmd.Parameters.Add("Identity", accountName); cmd.Parameters.Add("ActiveSyncEnabled", enableActiveSync); if (enableActiveSync) { cmd.Parameters.Add("ActiveSyncMailboxPolicy", organizationId); } cmd.Parameters.Add("OWAEnabled", enableOWA); cmd.Parameters.Add("MAPIEnabled", enableMAPI); cmd.Parameters.Add("PopEnabled", enablePOP); cmd.Parameters.Add("ImapEnabled", enableIMAP); ExecuteShellCommand(runSpace, cmd); } finally { CloseRunspace(runSpace); } ExchangeLog.LogEnd("SetMailboxAdvancedSettingsInternal"); } protected override ExchangeAccount[] GetMailboxCalendarAccounts(Runspace runSpace, string organizationId, string accountName) { ExchangeLog.LogStart("GetMailboxCalendarAccounts"); string cn = GetMailboxCommonName(runSpace, accountName); ExchangeAccount[] ret = GetCalendarAccounts(runSpace, organizationId, cn); ExchangeLog.LogEnd("GetMailboxCalendarAccounts"); return ret; } protected override ExchangeAccount[] GetMailboxContactAccounts(Runspace runSpace, string organizationId, string accountName) { ExchangeLog.LogStart("GetMailboxContactAccounts"); string cn = GetMailboxCommonName(runSpace, accountName); ExchangeAccount[] ret = GetContactAccounts(runSpace, organizationId, cn); ExchangeLog.LogEnd("GetMailboxContactAccounts"); return ret; } private ExchangeAccount[] GetCalendarAccounts(Runspace runSpace, string organizationId, string accountId) { ExchangeLog.LogStart("GetContactAccounts"); var folderPath = GetMailboxFolderPath(accountId, ExchangeFolders.Calendar); var accounts = GetMailboxFolderPermissions(runSpace, organizationId, folderPath); ExchangeLog.LogEnd("GetContactAccounts"); return accounts.ToArray(); } private ExchangeAccount[] GetContactAccounts(Runspace runSpace, string organizationId, string accountId) { ExchangeLog.LogStart("GetContactAccounts"); var folderPath = GetMailboxFolderPath(accountId, ExchangeFolders.Contacts); var accounts = GetMailboxFolderPermissions(runSpace, organizationId, folderPath); ExchangeLog.LogEnd("GetContactAccounts"); return accounts.ToArray(); } private List<ExchangeAccount> GetMailboxFolderPermissions(Runspace runSpace, string organizationId, string folderPath) { Command cmd = new Command("Get-MailboxFolderPermission"); cmd.Parameters.Add("Identity", folderPath); Collection<PSObject> results = ExecuteShellCommand(runSpace, cmd); List<ExchangeAccount> accounts = new List<ExchangeAccount>(); foreach (PSObject current in results) { string user = GetPSObjectProperty(current, "User").ToString(); var accessRights = GetPSObjectProperty(current, "AccessRights") as IEnumerable; if (accessRights == null) { continue; } ExchangeAccount account = GetOrganizationAccount(runSpace, organizationId, user); if (account != null) { account.PublicFolderPermission = accessRights.Cast<object>().First().ToString(); accounts.Add(account); } } return accounts; } protected override void SetMailboxFolderPermissions(Runspace runSpace, ExchangeAccount[] existingAccounts, string folderPath, ExchangeAccount[] accounts) { ExchangeLog.LogStart("SetMailboxFolderPermissions"); if (string.IsNullOrEmpty(folderPath)) throw new ArgumentNullException("folderPath"); if (accounts == null) throw new ArgumentNullException("accounts"); ExchangeTransaction transaction = StartTransaction(); try { SetMailboxFolderPermissions(runSpace, folderPath, existingAccounts, accounts, transaction); } catch (Exception) { RollbackTransaction(transaction); throw; } ExchangeLog.LogEnd("SetMailboxFolderPermissions"); } private void SetMailboxFolderPermissions(Runspace runSpace, string folderPath, ExchangeAccount[] existingAccounts, ExchangeAccount[] newAccounts, ExchangeTransaction transaction) { ResetMailboxFolderPermissions(runSpace, folderPath, existingAccounts, transaction); AddMailboxFolderPermissions(runSpace, folderPath, newAccounts, transaction); } private void AddMailboxFolderPermissions(Runspace runSpace, string folderPath, ExchangeAccount[] accounts, ExchangeTransaction transaction) { ExchangeLog.LogStart("SetMailboxCalendarPermissions"); foreach (var account in accounts) { AddMailboxFolderPermission(runSpace, folderPath, account); transaction.AddMailboxFolderPermission(folderPath, account); } ExchangeLog.LogEnd("SetMailboxCalendarPermissions"); } private void ResetMailboxFolderPermissions(Runspace runSpace, string folderPath, ExchangeAccount[] accounts, ExchangeTransaction transaction) { ExchangeLog.LogStart("ResetMailboxFolderPermissions"); foreach (var account in accounts) { RemoveMailboxFolderPermission(runSpace, folderPath, account); transaction.RemoveMailboxFolderPermissions(folderPath, account); } ExchangeLog.LogEnd("ResetMailboxFolderPermissions"); } protected override void AddMailboxFolderPermission(Runspace runSpace, string folderPath, ExchangeAccount account) { Command cmd = new Command("Add-MailboxFolderPermission"); cmd.Parameters.Add("Identity", folderPath); cmd.Parameters.Add("User", account.AccountName); cmd.Parameters.Add("AccessRights", account.PublicFolderPermission); ExecuteShellCommand(runSpace, cmd); } protected override void RemoveMailboxFolderPermission(Runspace runSpace, string folderPath, ExchangeAccount account) { Command cmd = new Command("Remove-MailboxFolderPermission"); cmd.Parameters.Add("Identity", folderPath); cmd.Parameters.Add("User", account.AccountName); ExecuteShellCommand(runSpace, cmd); } #endregion #region Distribution Lists internal override string GetGroupManager(PSObject group) { string ret = null; MultiValuedProperty<ADObjectId> ids = (MultiValuedProperty<ADObjectId>)GetPSObjectProperty(group, "ManagedBy"); if (ids.Count > 0) ret = ObjToString(ids[0]); return ret; } internal override void RemoveDistributionGroup(Runspace runSpace, string id) { ExchangeLog.LogStart("RemoveDistributionGroup"); Command cmd = new Command("Remove-DistributionGroup"); cmd.Parameters.Add("Identity", id); cmd.Parameters.Add("Confirm", false); cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); ExecuteShellCommand(runSpace, cmd); ExchangeLog.LogEnd("RemoveDistributionGroup"); } internal override void SetDistributionGroup(Runspace runSpace, string id, string displayName, bool hideFromAddressBook) { Command cmd = new Command("Set-DistributionGroup"); cmd.Parameters.Add("Identity", id); cmd.Parameters.Add("DisplayName", displayName); cmd.Parameters.Add("HiddenFromAddressListsEnabled", hideFromAddressBook); cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); ExecuteShellCommand(runSpace, cmd); } internal override void SetGroup(Runspace runSpace, string id, string managedBy, string notes) { Command cmd = new Command("Set-Group"); cmd.Parameters.Add("Identity", id); cmd.Parameters.Add("ManagedBy", managedBy); cmd.Parameters.Add("Notes", notes); cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); ExecuteShellCommand(runSpace, cmd); } internal override void RemoveDistributionGroupMember(Runspace runSpace, string group, string member) { Command cmd = new Command("Remove-DistributionGroupMember"); cmd.Parameters.Add("Identity", group); cmd.Parameters.Add("Member", member); cmd.Parameters.Add("Confirm", false); cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); ExecuteShellCommand(runSpace, cmd); } internal override void AddDistributionGroupMember(Runspace runSpace, string group, string member) { Command cmd = new Command("Add-DistributionGroupMember"); cmd.Parameters.Add("Identity", group); cmd.Parameters.Add("Member", member); cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); ExecuteShellCommand(runSpace, cmd); } internal override void SetDistributionListSendOnBehalfAccounts(Runspace runspace, string accountName, string[] sendOnBehalfAccounts) { ExchangeLog.LogStart("SetDistributionListSendOnBehalfAccounts"); Command cmd = new Command("Set-DistributionGroup"); cmd.Parameters.Add("Identity", accountName); cmd.Parameters.Add("GrantSendOnBehalfTo", SetSendOnBehalfAccounts(runspace, sendOnBehalfAccounts)); cmd.Parameters.Add("BypassSecurityGroupManagerCheck"); ExecuteShellCommand(runspace, cmd); ExchangeLog.LogEnd("SetDistributionListSendOnBehalfAccounts"); } #endregion #region PowerShell integration internal override string ExchangeSnapInName { get { return "Microsoft.Exchange.Management.PowerShell.E2010"; } } internal override Runspace OpenRunspace() { Runspace runspace = base.OpenRunspace(); Command cmd = new Command("Set-ADServerSettings"); cmd.Parameters.Add("PreferredServer", PrimaryDomainController); ExecuteShellCommand(runspace, cmd, false); return runspace; } internal static Assembly ResolveExchangeAssembly(object p, ResolveEventArgs args) { //Add path for the Exchange 2007 DLLs if (args.Name.Contains("Microsoft.Exchange")) { string exchangePath = GetExchangePath(); if (string.IsNullOrEmpty(exchangePath)) return null; string path = Path.Combine(exchangePath, args.Name.Split(',')[0] + ".dll"); if (!File.Exists(path)) return null; ExchangeLog.DebugInfo("Resolved assembly: {0}", path); return Assembly.LoadFrom(path); } else { return null; } } internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, ResultObject res, bool setIsSuccess) { object[] errors; Collection<PSObject> ret = ExecuteShellCommand(runSpace, cmd, out errors); if (errors.Length > 0) { foreach (object error in errors) res.ErrorCodes.Add(error.ToString()); if (setIsSuccess) res.IsSuccess = false; } return ret; } #endregion #region Storage internal override string CreateStorageGroup(Runspace runSpace, string name, string server) { return string.Empty; } internal override string CreateMailboxDatabase(Runspace runSpace, string name, string storageGroup) { ExchangeLog.LogStart("CreateMailboxDatabase"); string id; if (name != "*") { Command cmd = new Command("Get-MailboxDatabase"); cmd.Parameters.Add("Identity", name); Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd); if (result != null && result.Count > 0) { id = GetResultObjectIdentity(result); } else { throw new Exception(string.Format("Mailbox database {0} not found", name)); } } else { id = "*"; } ExchangeLog.LogEnd("CreateMailboxDatabase"); return id; } #endregion #region Picture public virtual ResultObject SetPicture(string accountName, byte[] picture) { ExchangeLog.LogStart("SetPicture"); ResultObject res = new ResultObject() { IsSuccess = true }; Runspace runSpace = null; try { runSpace = OpenRunspace(); Command cmd; cmd = new Command("Import-RecipientDataProperty"); cmd.Parameters.Add("Identity", accountName); cmd.Parameters.Add("Picture", true); cmd.Parameters.Add("FileData", picture); ExecuteShellCommand(runSpace, cmd, res, true); } finally { CloseRunspace(runSpace); } ExchangeLog.LogEnd("SetPicture"); return res; } public virtual BytesResult GetPicture(string accountName) { ExchangeLog.LogStart("GetPicture"); BytesResult res = new BytesResult() { IsSuccess = true }; Runspace runSpace = null; try { runSpace = OpenRunspace(); Command cmd; cmd = new Command("Export-RecipientDataProperty"); cmd.Parameters.Add("Identity", accountName); cmd.Parameters.Add("Picture", true); Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, res, true); if (result.Count > 0) { res.Value = ((Microsoft.Exchange.Data.BinaryFileDataObject) (result[0].ImmediateBaseObject)).FileData; } } finally { CloseRunspace(runSpace); } ExchangeLog.LogEnd("GetPicture"); return res; } #endregion public override bool IsInstalled() { int value = 0; bool bResult = false; RegistryKey root = Registry.LocalMachine; RegistryKey rk = root.OpenSubKey(ExchangeRegistryPath); if (rk != null) { value = (int)rk.GetValue("MsiProductMajor", null); if (value == 14) { value = (int)rk.GetValue("MsiProductMinor", null); if ((value == 0) | (value == 1)) bResult = true; } rk.Close(); } return bResult; } } }
using System; using System.Collections; using System.IO; using NUnit.Framework; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Tests { [TestFixture] public class X509StoreTest : SimpleTest { private void certPairTest() { X509CertificateParser certParser = new X509CertificateParser(); X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); // Testing CollectionCertStore generation from List X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert); IList certList = new ArrayList(); certList.Add(pair1); certList.Add(new X509CertificatePair(interCert, finalCert)); IX509Store certStore = X509StoreFactory.Create( "CertificatePair/Collection", new X509CollectionStoreParameters(certList)); X509CertPairStoreSelector selector = new X509CertPairStoreSelector(); X509CertStoreSelector fwSelector = new X509CertStoreSelector(); fwSelector.SerialNumber = rootCert.SerialNumber; fwSelector.Subject = rootCert.IssuerDN; selector.ForwardSelector = fwSelector; IList col = new ArrayList(certStore.GetMatches(selector)); if (col.Count != 1 || !col.Contains(pair1)) { Fail("failed pair1 test"); } col = new ArrayList(certStore.GetMatches(null)); if (col.Count != 2) { Fail("failed null test"); } } public override void PerformTest() { X509CertificateParser certParser = new X509CertificateParser(); X509CrlParser crlParser = new X509CrlParser(); X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); X509Crl rootCrl = crlParser.ReadCrl(CertPathTest.rootCrlBin); X509Crl interCrl = crlParser.ReadCrl(CertPathTest.interCrlBin); // Testing CollectionCertStore generation from List IList certList = new ArrayList(); certList.Add(rootCert); certList.Add(interCert); certList.Add(finalCert); IX509Store certStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // set default to be the same as for SUN X500 name X509Name.DefaultReverse = true; // Searching for rootCert by subjectDN X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); IList certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by subjectDN"); } // Searching for rootCert by subjectDN encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded subjectDN"); } X509Name.DefaultReverse = false; // Searching for rootCert by public key encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.SubjectPublicKey = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCert.GetPublicKey()); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded public key"); } // Searching for interCert by issuerDN targetConstraints = new X509CertStoreSelector(); targetConstraints.Issuer = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 2) { Fail("did not found 2 certs"); } if (!certs.Contains(rootCert)) { Fail("rootCert not found"); } if (!certs.Contains(interCert)) { Fail("interCert not found"); } // Searching for rootCrl by issuerDN IList crlList = new ArrayList(); crlList.Add(rootCrl); crlList.Add(interCrl); IX509Store store = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(crlList)); X509CrlStoreSelector targetConstraintsCRL = new X509CrlStoreSelector(); ArrayList issuers = new ArrayList(); issuers.Add(rootCrl.IssuerDN); targetConstraintsCRL.Issuers = issuers; IList crls = new ArrayList(store.GetMatches(targetConstraintsCRL)); if (crls.Count != 1 || !crls.Contains(rootCrl)) { Fail("rootCrl not found"); } crls = new ArrayList(certStore.GetMatches(targetConstraintsCRL)); if (crls.Count != 0) { Fail("error using wrong selector (CRL)"); } certs = new ArrayList(store.GetMatches(targetConstraints)); if (certs.Count != 0) { Fail("error using wrong selector (certs)"); } // Searching for attribute certificates X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert); IX509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID); IList attrList = new ArrayList(); attrList.Add(attrCert); attrList.Add(attrCert2); store = X509StoreFactory.Create( "AttributeCertificate/Collection", new X509CollectionStoreParameters(attrList)); X509AttrCertStoreSelector attrSelector = new X509AttrCertStoreSelector(); attrSelector.Holder = attrCert.Holder; if (!attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } IList attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on holder"); } attrSelector.Holder = attrCert2.Holder; if (attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on holder"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.Issuer = attrCert.Issuer; if (!attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on issuer"); } attrSelector.Issuer = attrCert2.Issuer; if (attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on issuer"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCert = attrCert; if (!attrSelector.AttributeCert.Equals(attrCert)) { Fail("attrCert get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on attrCert"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.SerialNumber = attrCert.SerialNumber; if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = (X509AttrCertStoreSelector)attrSelector.Clone(); if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore); if (attrSelector.AttributeCertificateValid.Value != attrCert.NotBefore) { Fail("valid get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on valid"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore.AddMilliseconds(-100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on before"); } attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotAfter.AddMilliseconds(100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on after"); } attrSelector.SerialNumber = BigInteger.ValueOf(10000); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on wrong serial number"); } attrSelector.AttributeCert = null; attrSelector.AttributeCertificateValid = null; attrSelector.Holder = null; attrSelector.Issuer = null; attrSelector.SerialNumber = null; if (attrSelector.AttributeCert != null) { Fail("null attrCert"); } if (attrSelector.AttributeCertificateValid != null) { Fail("null attrCertValid"); } if (attrSelector.Holder != null) { Fail("null attrCert holder"); } if (attrSelector.Issuer != null) { Fail("null attrCert issuer"); } if (attrSelector.SerialNumber != null) { Fail("null attrCert serial"); } attrs = new ArrayList(certStore.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("error using wrong selector (attrs)"); } certPairTest(); } public override string Name { get { return "IX509Store"; } } public static void Main( string[] args) { RunTest(new X509StoreTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// 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.Text; using System.Diagnostics; namespace System { internal static class UriHelper { private static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // http://host/Path/Path/File?Query is the base of // - http://host/Path/Path/File/ ... (those "File" words may be different in semantic but anyway) // - http://host/Path/Path/#Fragment // - http://host/Path/Path/?Query // - http://host/Path/Path/MoreDir/ ... // - http://host/Path/Path/OtherFile?Query // - http://host/Path/Path/Fl // - http://host/Path/Path/ // // It is not a base for // - http://host/Path/Path (that last "Path" is not considered as a directory) // - http://host/Path/Path?Query // - http://host/Path/Path#Fragment // - http://host/Path/Path2/ // - http://host/Path/Path2/MoreDir // - http://host/Path/File // // ASSUMES that strings like http://host/Path/Path/MoreDir/../../ have been canonicalized before going to this method. // ASSUMES that back slashes already have been converted if applicable. // internal static unsafe bool TestForSubPath(char* selfPtr, ushort selfLength, char* otherPtr, ushort otherLength, bool ignoreCase) { ushort i = 0; char chSelf; char chOther; bool AllSameBeforeSlash = true; for (; i < selfLength && i < otherLength; ++i) { chSelf = *(selfPtr + i); chOther = *(otherPtr + i); if (chSelf == '?' || chSelf == '#') { // survived so far and selfPtr does not have any more path segments return true; } // If selfPtr terminates a path segment, so must otherPtr if (chSelf == '/') { if (chOther != '/') { // comparison has failed return false; } // plus the segments must be the same if (!AllSameBeforeSlash) { // comparison has failed return false; } //so far so good AllSameBeforeSlash = true; continue; } // if otherPtr terminates then selfPtr must not have any more path segments if (chOther == '?' || chOther == '#') { break; } if (!ignoreCase) { if (chSelf != chOther) { AllSameBeforeSlash = false; } } else { if (char.ToLowerInvariant(chSelf) != char.ToLowerInvariant(chOther)) { AllSameBeforeSlash = false; } } } // If self is longer then it must not have any more path segments for (; i < selfLength; ++i) { if ((chSelf = *(selfPtr + i)) == '?' || chSelf == '#') { return true; } if (chSelf == '/') { return false; } } //survived by getting to the end of selfPtr return true; } // - forceX characters are always escaped if found // - rsvd character will remain unescaped // // start - starting offset from input // end - the exclusive ending offset in input // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output. // // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos // // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos // private const short c_MaxAsciiCharsReallocate = 40; private const short c_MaxUnicodeCharsReallocate = 40; private const short c_MaxUTF_8BytesPerUnicodeChar = 4; private const short c_EncodedCharsPerByte = 3; internal unsafe static char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { if (end - start >= Uri.c_MaxUriBufferSize) throw new UriFormatException(SR.net_uri_SizeLimit); int i = start; int prevInputPos = start; byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160 fixed (char* pStr = input) { for (; i < end; ++i) { char ch = pStr[i]; // a Unicode ? if (ch > '\x7F') { short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1); short count = 1; for (; count < maxSize && pStr[i + count] > '\x7f'; ++count) ; // Is the last a high surrogate? if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF) { // Should be a rare case where the app tries to feed an invalid Unicode surrogates pair if (count == 1 || count == end - i) throw new UriFormatException(SR.net_uri_BadString); // need to grab one more char as a Surrogate except when it's a bogus input ++count; } dest = EnsureDestinationSize(pStr, dest, i, (short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte), c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte, ref destPos, prevInputPos); short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes, c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar); // This is the only exception that built in UriParser can throw after a Uri ctor. // Should not happen unless the app tries to feed an invalid Unicode String if (numberOfBytes == 0) throw new UriFormatException(SR.net_uri_BadString); i += (count - 1); for (count = 0; count < numberOfBytes; ++count) EscapeAsciiChar((char)bytes[count], dest, ref destPos); prevInputPos = i + 1; } else if (ch == '%' && rsvd == '%') { // Means we don't reEncode '%' but check for the possible escaped sequence dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != Uri.c_DummyChar) { // leave it escaped dest[destPos++] = '%'; dest[destPos++] = pStr[i + 1]; dest[destPos++] = pStr[i + 2]; i += 2; } else { EscapeAsciiChar('%', dest, ref destPos); } prevInputPos = i + 1; } else if (ch == force1 || ch == force2) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch))) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } } if (prevInputPos != i) { // need to fill up the dest array ? if (prevInputPos != start || dest != null) dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos); } } return dest; } // // ensure destination array has enough space and contains all the needed input stuff // private unsafe static char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; if ((object)dest != null && destPos != 0) Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); dest = newresult; } // ensuring we copied everything form the input string left before last escaping while (prevInputPos != currentInputPos) dest[destPos++] = pStr[prevInputPos++]; return dest; } // // This method will assume that any good Escaped Sequence will be unescaped in the output // - Assumes Dest.Length - detPosition >= end-start // - UnescapeLevel controls various modes of operation // - Any "bad" escape sequence will remain as is or '%' will be escaped. // - destPosition tells the starting index in dest for placing the result. // On return destPosition tells the last character + 1 position in the "dest" array. // - The control chars and chars passed in rsdvX parameters may be re-escaped depending on UnescapeLevel // - It is a RARE case when Unescape actually needs escaping some characters mentioned above. // For this reason it returns a char[] that is usually the same ref as the input "dest" value. // internal unsafe static char[] UnescapeString(string input, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery) { fixed (char* pStr = input) { return UnescapeString(pStr, start, end, dest, ref destPosition, rsvd1, rsvd2, rsvd3, unescapeMode, syntax, isQuery); } } internal unsafe static char[] UnescapeString(char* pStr, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery) { byte[] bytes = null; byte escapedReallocations = 0; bool escapeReserved = false; int next = start; bool iriParsing = Uri.IriParsingStatic(syntax) && ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.EscapeUnescape); while (true) { // we may need to re-pin dest[] fixed (char* pDest = dest) { if ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.CopyOnly) { while (start < end) pDest[destPosition++] = pStr[start++]; return dest; } while (true) { char ch = (char)0; for (; next < end; ++next) { if ((ch = pStr[next]) == '%') { if ((unescapeMode & UnescapeMode.Unescape) == 0) { // re-escape, don't check anything else escapeReserved = true; } else if (next + 2 < end) { ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); // Unescape a good sequence if full unescape is requested if (unescapeMode >= UnescapeMode.UnescapeAll) { if (ch == Uri.c_DummyChar) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } continue; } } // re-escape % from an invalid sequence else if (ch == Uri.c_DummyChar) { if ((unescapeMode & UnescapeMode.Escape) != 0) escapeReserved = true; else continue; // we should throw instead but since v1.0 would just print '%' } // Do not unescape '%' itself unless full unescape is requested else if (ch == '%') { next += 2; continue; } // Do not unescape a reserved char unless full unescape is requested else if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { next += 2; continue; } // Do not unescape a dangerous char unless it's V1ToStringFlags mode else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && IsNotSafeForUnescape(ch)) { next += 2; continue; } else if (iriParsing && ((ch <= '\x9F' && IsNotSafeForUnescape(ch)) || (ch > '\x9F' && !IriHelper.CheckIriUnicodeRange(ch, isQuery)))) { // check if unenscaping gives a char outside iri range // if it does then keep it escaped next += 2; continue; } // unescape escaped char or escape % break; } else if (unescapeMode >= UnescapeMode.UnescapeAll) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } // keep a '%' as part of a bogus sequence continue; } else { escapeReserved = true; } // escape (escapeReserved==true) or otherwise unescape the sequence break; } else if ((unescapeMode & (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) == (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) { continue; } else if ((unescapeMode & UnescapeMode.Escape) != 0) { // Could actually escape some of the characters if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F'))) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } } } //copy off previous characters from input while (start < next) pDest[destPosition++] = pStr[start++]; if (next != end) { if (escapeReserved) { //escape that char // Since this should be _really_ rare case, reallocate with constant size increase of 30 rsvd-type characters. if (escapedReallocations == 0) { escapedReallocations = 30; char[] newDest = new char[dest.Length + escapedReallocations * 3]; fixed (char* pNewDest = newDest) { for (int i = 0; i < destPosition; ++i) pNewDest[i] = pDest[i]; } dest = newDest; // re-pin new dest[] array goto dest_fixed_loop_break; } else { --escapedReallocations; EscapeAsciiChar(pStr[next], dest, ref destPosition); escapeReserved = false; start = ++next; continue; } } // unescaping either one Ascii or possibly multiple Unicode if (ch <= '\x7F') { //ASCII dest[destPosition++] = ch; next += 3; start = next; continue; } // Unicode int byteCount = 1; // lazy initialization of max size, will reuse the array for next sequences if ((object)bytes == null) bytes = new byte[end - next]; bytes[0] = (byte)ch; next += 3; while (next < end) { // Check on exit criterion if ((ch = pStr[next]) != '%' || next + 2 >= end) break; // already made sure we have 3 characters in str ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); //invalid hex sequence ? if (ch == Uri.c_DummyChar) break; // character is not part of a UTF-8 sequence ? else if (ch < '\x80') break; else { //a UTF-8 sequence bytes[byteCount++] = (byte)ch; next += 3; } } Encoding noFallbackCharUTF8 = Encoding.GetEncoding( Encoding.UTF8.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback("")); char[] unescapedChars = new char[bytes.Length]; int charCount = noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0); start = next; // match exact bytes // Do not unescape chars not allowed by Iri // need to check for invalid utf sequences that may not have given any chars MatchUTF8Sequence(pDest, dest, ref destPosition, unescapedChars, charCount, bytes, byteCount, isQuery, iriParsing); } if (next == end) goto done; } dest_fixed_loop_break:; } } done: return dest; } // // Need to check for invalid utf sequences that may not have given any chars. // We got the unescaped chars, we then re-encode them and match off the bytes // to get the invalid sequence bytes that we just copy off // internal static unsafe void MatchUTF8Sequence(char* pDest, char[] dest, ref int destOffset, char[] unescapedChars, int charCount, byte[] bytes, int byteCount, bool isQuery, bool iriParsing) { int count = 0; fixed (char* unescapedCharsPtr = unescapedChars) { for (int j = 0; j < charCount; ++j) { bool isHighSurr = char.IsHighSurrogate(unescapedCharsPtr[j]); byte[] encodedBytes = Encoding.UTF8.GetBytes(unescapedChars, j, isHighSurr ? 2 : 1); int encodedBytesLength = encodedBytes.Length; // we have to keep unicode chars outside Iri range escaped bool inIriRange = false; if (iriParsing) { if (!isHighSurr) inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], isQuery); else { bool surrPair = false; inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], unescapedChars[j + 1], ref surrPair, isQuery); } } while (true) { // Escape any invalid bytes that were before this character while (bytes[count] != encodedBytes[0]) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } // check if all bytes match bool allBytesMatch = true; int k = 0; for (; k < encodedBytesLength; ++k) { if (bytes[count + k] != encodedBytes[k]) { allBytesMatch = false; break; } } if (allBytesMatch) { count += encodedBytesLength; if (iriParsing) { if (!inIriRange) { // need to keep chars not allowed as escaped for (int l = 0; l < encodedBytes.Length; ++l) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)encodedBytes[l], dest, ref destOffset); } } else if (!UriHelper.IsBidiControlCharacter(unescapedCharsPtr[j])) { //copy chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j]; if (isHighSurr) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j + 1]; } } } else { //copy chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j]; if (isHighSurr) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j + 1]; } } break; // break out of while (true) since we've matched this char bytes } else { // copy bytes till place where bytes don't match for (int l = 0; l < k; ++l) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } } } if (isHighSurr) j++; } } // Include any trailing invalid sequences while (count < byteCount) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } } internal static void EscapeAsciiChar(char ch, char[] to, ref int pos) { to[pos++] = '%'; to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4]; to[pos++] = s_hexUpperChars[ch & 0xf]; } internal static char EscapedAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { return Uri.c_DummyChar; } int res = (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { return Uri.c_DummyChar; } return (char)((res << 4) + ((next <= '9') ? ((int)next - (int)'0') : (((next <= 'F') ? ((int)next - (int)'A') : ((int)next - (int)'a')) + 10))); } // Do not unescape these in safe mode: // 1) reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," // 2) excluded = control | "#" | "%" | "\" // // That will still give plenty characters unescaped by SafeUnesced mode such as // 1) Unicode characters // 2) Unreserved = alphanum | "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" // 3) DelimitersAndUnwise = "<" | ">" | <"> | "{" | "}" | "|" | "^" | "[" | "]" | "`" internal static bool IsNotSafeForUnescape(char ch) { if (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F')) return true; else if ((ch >= ';' && ch <= '@' && (ch | '\x2') != '>') || (ch >= '#' && ch <= '&') || ch == '+' || ch == ',' || ch == '/' || ch == '\\') return true; return false; } private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;="; private const string RFC3986UnreservedMarks = @"-._~"; private static unsafe bool IsReservedUnreservedOrHash(char c) { if (IsUnreserved(c)) { return true; } return (RFC3986ReservedMarks.IndexOf(c) >= 0); } internal static unsafe bool IsUnreserved(char c) { if (UriHelper.IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.IndexOf(c) >= 0); } internal static bool Is3986Unreserved(char c) { if (UriHelper.IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.IndexOf(c) >= 0); } // // Is this a gen delim char from RFC 3986 // internal static bool IsGenDelim(char ch) { return (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@'); } // // IsHexDigit // // Determines whether a character is a valid hexadecimal digit in the range // [0..9] | [A..F] | [a..f] // // Inputs: // <argument> character // Character to test // // Returns: // true if <character> is a hexadecimal digit character // // Throws: // Nothing // internal static bool IsHexDigit(char character) { return ((character >= '0') && (character <= '9')) || ((character >= 'A') && (character <= 'F')) || ((character >= 'a') && (character <= 'f')); } // // Returns: // Number in the range 0..15 // // Throws: // ArgumentException // internal static int FromHex(char digit) { if (((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f'))) { return (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); } throw new ArgumentOutOfRangeException(nameof(digit)); } internal static readonly char[] s_WSchars = new char[] { ' ', '\n', '\r', '\t' }; internal static bool IsLWS(char ch) { return (ch <= ' ') && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'); } //Only consider ASCII characters internal static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } internal static bool IsAsciiLetterOrDigit(char character) { return IsAsciiLetter(character) || (character >= '0' && character <= '9'); } // // Is this a Bidirectional control char.. These get stripped // internal static bool IsBidiControlCharacter(char ch) { return (ch == '\u200E' /*LRM*/ || ch == '\u200F' /*RLM*/ || ch == '\u202A' /*LRE*/ || ch == '\u202B' /*RLE*/ || ch == '\u202C' /*PDF*/ || ch == '\u202D' /*LRO*/ || ch == '\u202E' /*RLO*/); } // // Strip Bidirectional control characters from this string // internal static unsafe string StripBidiControlCharacter(char* strToClean, int start, int length) { if (length <= 0) return ""; char[] cleanStr = new char[length]; int count = 0; for (int i = 0; i < length; ++i) { char c = strToClean[start + i]; if (c < '\u200E' || c > '\u202E' || !IsBidiControlCharacter(c)) { cleanStr[count++] = c; } } return new string(cleanStr, 0, count); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Threading; using Htc.Vita.Core.Crypto; using Htc.Vita.Core.Diagnostics; using Htc.Vita.Core.Interop; using Htc.Vita.Core.Log; namespace Htc.Vita.Core.Runtime { /// <summary> /// Class NamedPipeIpcChannel. /// </summary> public class NamedPipeIpcChannel { #pragma warning disable CA1416 /// <summary> /// Class Client. /// Implements the <see cref="IpcChannel.Client" /> /// </summary> /// <seealso cref="IpcChannel.Client" /> public class Client : IpcChannel.Client { private const int PipeBufferSize = 512; private readonly Dictionary<string, string> _translatedNameMap = new Dictionary<string, string>(); private string _pipeName; /// <summary> /// Initializes a new instance of the <see cref="Client" /> class. /// </summary> public Client() { _pipeName = ""; } /// <inheritdoc /> protected override bool OnIsReady(Dictionary<string, string> options) { var shouldVerifyProvider = false; if (options.ContainsKey(OptionVerifyProvider)) { shouldVerifyProvider = Util.Convert.ToBool(options[OptionVerifyProvider]); } using (var clientStream = new NamedPipeClientStream(OnOverrideTranslateName(_pipeName))) { try { clientStream.Connect(100); clientStream.ReadMode = PipeTransmissionMode.Message; var outputBuilder = new StringBuilder(); var outputBuffer = new byte[PipeBufferSize]; var verified = !shouldVerifyProvider || VerifyServerSignature(clientStream); clientStream.Write(outputBuffer, 0, outputBuffer.Length); do { clientStream.Read(outputBuffer, 0, outputBuffer.Length); var outputChunk = Encoding.UTF8.GetString(outputBuffer); outputBuilder.Append(outputChunk); outputBuffer = new byte[outputBuffer.Length]; } while (!clientStream.IsMessageComplete); return verified; } catch (TimeoutException) { // Ignore } catch (IOException) { // Ignore } } return false; } /// <summary> /// Called when overriding translating name. /// </summary> /// <param name="name">The name.</param> /// <returns>System.String.</returns> protected virtual string OnOverrideTranslateName(string name) { string translatedName = null; if (_translatedNameMap.ContainsKey(name)) { translatedName = _translatedNameMap[name]; } if (!string.IsNullOrWhiteSpace(translatedName)) { return translatedName; } translatedName = Sha1.GetInstance().GenerateInHex(name); _translatedNameMap[name] = translatedName; return translatedName; } /// <inheritdoc /> protected override string OnRequest(string input) { using (var clientStream = new NamedPipeClientStream(OnOverrideTranslateName(_pipeName))) { clientStream.Connect(); clientStream.ReadMode = PipeTransmissionMode.Message; var outputBuilder = new StringBuilder(); var outputBuffer = new byte[PipeBufferSize]; var inputBytes = Encoding.UTF8.GetBytes(input); clientStream.Write(inputBytes, 0, inputBytes.Length); do { clientStream.Read(outputBuffer, 0, outputBuffer.Length); var outputChunk = Encoding.UTF8.GetString(outputBuffer); outputBuilder.Append(outputChunk); outputBuffer = new byte[outputBuffer.Length]; } while (!clientStream.IsMessageComplete); return FilterOutInvalidChars(outputBuilder.ToString()); } } /// <inheritdoc /> protected override bool OnSetName(string name) { if (!string.IsNullOrWhiteSpace(name)) { _pipeName = name; } return true; } } /// <summary> /// Class Provider. /// Implements the <see cref="IpcChannel.Provider" /> /// </summary> /// <seealso cref="IpcChannel.Provider" /> public class Provider : IpcChannel.Provider { private const int PipeBufferSize = 512; private const int PipeThreadNumber = 16; private readonly Dictionary<string, string> _translatedNameMap = new Dictionary<string, string>(); private readonly Thread[] _workerThreads = new Thread[PipeThreadNumber]; private bool _isRunning; private bool _shouldStopWorkers; private string _pipeName; /// <summary> /// Initializes a new instance of the <see cref="Provider" /> class. /// </summary> public Provider() { _pipeName = ""; } private static Windows.PipeModes ConvertPipeModeFrom(PipeTransmissionMode transmissionMode) { if (transmissionMode == PipeTransmissionMode.Message) { return Windows.PipeModes.TypeMessage | Windows.PipeModes.ReadModeMessage; } return Windows.PipeModes.TypeByte | Windows.PipeModes.ReadModeByte; } private static Windows.PipeOpenModes ConvertPipeOpenModeFrom( PipeDirection pipeDirection, PipeOptions pipeOptions, int maxNumberOfServerInstances) { var result = Windows.PipeOpenModes.None; if (pipeDirection == PipeDirection.In) { result = Windows.PipeOpenModes.AccessInbound; } else if (pipeDirection == PipeDirection.Out) { result = Windows.PipeOpenModes.AccessOutbound; } else if (pipeDirection == PipeDirection.InOut) { result = Windows.PipeOpenModes.AccessDuplex; } if (pipeOptions == PipeOptions.Asynchronous) { result |= Windows.PipeOpenModes.FlagOverlapped; } else if (pipeOptions == PipeOptions.WriteThrough) { result |= Windows.PipeOpenModes.FlagWriteThrough; } else if (pipeOptions == (PipeOptions)0x20000000 /* PipeOptions.CurrentUserOnly */) { result |= Windows.PipeOpenModes.CurrentUserOnly; } if (maxNumberOfServerInstances == 1) { result |= Windows.PipeOpenModes.FlagFirstPipeInstance; } return result; } private static NamedPipeServerStream NewNamedPipeServerStreamInstance( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity) { if (pipeSecurity == null) { return new NamedPipeServerStream( pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize ); } if (string.IsNullOrWhiteSpace(pipeName)) { throw new ArgumentNullException(nameof(pipeName)); } if ("anonymous".Equals(pipeName)) { throw new ArgumentException("pipeName \"anonymous\" is reserved"); } if (inBufferSize < 0) { throw new ArgumentOutOfRangeException(nameof(inBufferSize), "buffer size should be non-negative"); } if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && maxNumberOfServerInstances != -1) { throw new ArgumentOutOfRangeException(nameof(maxNumberOfServerInstances), "requested server instance should between 1 to 254"); } var fullPath = Path.GetFullPath($"\\\\.\\pipe\\{pipeName}"); var pipeOpenMode = ConvertPipeOpenModeFrom( direction, options, maxNumberOfServerInstances ); var pipeMode = ConvertPipeModeFrom(transmissionMode); if (maxNumberOfServerInstances == -1) { maxNumberOfServerInstances = byte.MaxValue; } var securityDescriptorInBytes = pipeSecurity.GetSecurityDescriptorBinaryForm(); var securityDescriptorHandle = Marshal.AllocHGlobal(securityDescriptorInBytes.Length); Marshal.Copy( securityDescriptorInBytes, 0, securityDescriptorHandle, securityDescriptorInBytes.Length ); var securityAttributes = new Windows.SecurityAttributes { lpSecurityDescriptor = securityDescriptorHandle }; securityAttributes.nLength = Marshal.SizeOf(securityAttributes); try { var safePipeHandle = Windows.CreateNamedPipeW( fullPath, pipeOpenMode, pipeMode, (uint) maxNumberOfServerInstances, (uint) outBufferSize, (uint) inBufferSize, 0, securityAttributes ); if (safePipeHandle.IsInvalid) { return null; } return new NamedPipeServerStream( direction, options.HasFlag(PipeOptions.Asynchronous), false, safePipeHandle ) { ReadMode = transmissionMode }; } finally { Marshal.FreeHGlobal(securityDescriptorHandle); } } /// <inheritdoc /> protected override bool OnIsRunning() { return _isRunning; } /// <inheritdoc /> protected override bool OnSetName(string name) { if (!string.IsNullOrWhiteSpace(name)) { _pipeName = name; } return true; } /// <inheritdoc /> protected override bool OnStart() { Logger.GetInstance(typeof(Provider)).Info($"Channel name: {OnOverrideTranslateName(_pipeName)}, thread number: {PipeThreadNumber}"); if (_isRunning) { return true; } _isRunning = true; _shouldStopWorkers = false; for (var i = 0; i < _workerThreads.Length; i++) { _workerThreads[i] = new Thread(OnHandleRequest) { IsBackground = true }; _workerThreads[i].Start(); } return true; } /// <inheritdoc /> protected override bool OnStop() { if (!_isRunning) { return true; } _shouldStopWorkers = true; var runningThreadNumber = PipeThreadNumber; while (runningThreadNumber > 0) { ConnectSelfToBreakConnectionWaiting(OnOverrideTranslateName(_pipeName), runningThreadNumber / 2 + 1); for (var i = 0; i < PipeThreadNumber; i++) { if (_workerThreads[i] == null || !_workerThreads[i].Join(250)) { continue; } _workerThreads[i] = null; runningThreadNumber--; } } _isRunning = false; return true; } private void OnHandleRequest(object data) { var threadId = Thread.CurrentThread.ManagedThreadId; var pipeSecurity = new PipeSecurity(); pipeSecurity.AddAccessRule( new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow ) ); pipeSecurity.AddAccessRule( new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, null), PipeAccessRights.FullControl, AccessControlType.Allow ) ); pipeSecurity.AddAccessRule( new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.FullControl, AccessControlType.Allow ) ); while (!_shouldStopWorkers) { try { using (var serverStream = NewNamedPipeServerStreamInstance( OnOverrideTranslateName(_pipeName), PipeDirection.InOut, PipeThreadNumber, PipeTransmissionMode.Message, PipeOptions.None, /* default */ 0, /* default */ 0, pipeSecurity )) { if (serverStream == null) { Logger.GetInstance(typeof(Provider)).Error("Can not create named pipe server stream"); return; } while (!_shouldStopWorkers) { if (serverStream.IsConnected) { serverStream.Disconnect(); } serverStream.WaitForConnection(); var outputBuilder = new StringBuilder(); var outputBuffer = new byte[PipeBufferSize]; do { serverStream.Read(outputBuffer, 0, outputBuffer.Length); var outputChunk = Encoding.UTF8.GetString(outputBuffer); outputBuilder.Append(outputChunk); outputBuffer = new byte[outputBuffer.Length]; } while (!serverStream.IsMessageComplete); var channel = new IpcChannel { Output = FilterOutInvalidChars(outputBuilder.ToString()) }; if (!string.IsNullOrEmpty(channel.Output)) { if (OnMessageHandled == null) { Logger.GetInstance(typeof(Provider)).Error("Can not find OnMessageHandled delegates to handle messages"); } else { OnMessageHandled(channel, GetClientSignature(serverStream)); } } if (!string.IsNullOrEmpty(channel.Input)) { var inputBytes = Encoding.UTF8.GetBytes(channel.Input); serverStream.Write(inputBytes, 0, inputBytes.Length); } } if (serverStream.IsConnected) { serverStream.Disconnect(); } } } catch (Exception e) { Logger.GetInstance(typeof(Provider)).Error($"Error happened on thread[{threadId}]: {e.Message}"); } } } /// <summary> /// Called when overriding translating name. /// </summary> /// <param name="name">The name.</param> /// <returns>System.String.</returns> protected virtual string OnOverrideTranslateName(string name) { string translatedName = null; if (_translatedNameMap.ContainsKey(name)) { translatedName = _translatedNameMap[name]; } if (!string.IsNullOrWhiteSpace(translatedName)) { return translatedName; } translatedName = Sha1.GetInstance().GenerateInHex(name); _translatedNameMap[name] = translatedName; return translatedName; } private static void ConnectSelfToBreakConnectionWaiting(string pipeName, int times) { if (string.IsNullOrWhiteSpace(pipeName) || times < 0) { return; } for (var i = 0; i < times; i++) { using (var clientStream = new NamedPipeClientStream(pipeName)) { try { clientStream.Connect(100); } catch (TimeoutException) { continue; } clientStream.ReadMode = PipeTransmissionMode.Message; var inputBuilder = new StringBuilder(); var inputBuffer = new byte[PipeBufferSize]; var outputBuffer = new byte[1]; clientStream.Write( outputBuffer, 0, outputBuffer.Length ); do { clientStream.Read( inputBuffer, 0, inputBuffer.Length ); var inputChunk = Encoding.UTF8.GetString(inputBuffer); inputBuilder.Append(inputChunk); inputBuffer = new byte[inputBuffer.Length]; } while (!clientStream.IsMessageComplete); // Logger.GetInstance(typeof(Provider)).Info($"Dump return: \"{FilterOutInvalidChars(inputBuilder.ToString())}\""); } } } } private static string FilterOutInvalidChars(string input) { if (string.IsNullOrEmpty(input)) { return input; } return input.Replace("\0", string.Empty); } private static bool VerifyServerSignature(PipeStream pipeStream) { if (pipeStream == null) { return false; } var processId = 0u; if (!Windows.GetNamedPipeServerProcessId(pipeStream.SafePipeHandle, ref processId)) { Logger.GetInstance(typeof(NamedPipeIpcChannel)).Error($"Can not get named pipe server process id, error code: {Marshal.GetLastWin32Error()}"); return false; } string processPath = null; try { using (var process = Process.GetProcessById((int) processId)) { processPath = process.MainModule?.FileName; } } catch (Exception e) { Logger.GetInstance(typeof(NamedPipeIpcChannel)).Error($"Can not get named pipe server process path: {e.Message}"); } if (processPath == null) { return false; } var filePropertiesInfo = FilePropertiesInfo.GetPropertiesInfo(new FileInfo(processPath)); return filePropertiesInfo != null && filePropertiesInfo.Verified; } private static FilePropertiesInfo GetClientSignature(PipeStream pipeStream) { if (pipeStream == null) { return null; } var processId = 0u; if (!Windows.GetNamedPipeClientProcessId(pipeStream.SafePipeHandle, ref processId)) { Logger.GetInstance(typeof(NamedPipeIpcChannel)).Error($"Can not get named pipe client process id, error code: {Marshal.GetLastWin32Error()}"); return null; } var processPath = ProcessManager.GetProcessPathById((int) processId); if (string.IsNullOrWhiteSpace(processPath)) { return null; } return FilePropertiesInfo.GetPropertiesInfo(new FileInfo(processPath)); } #pragma warning restore CA1416 } }
// Copyright (c) 2017 Jan Pluskal // //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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.8009 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Xml.Schema; using System.Xml.Serialization; namespace Netfox.NBARDatabase { // // This source code was auto-generated by xsd, Version=2.0.50727.3038. // /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] [XmlRoot(Namespace = "", IsNullable = false)] public partial class parameter { private string helpstringField; private string idField; private string nameField; /// <remarks/> [XmlElement("help-string", Form = XmlSchemaForm.Unqualified) ] public string helpstring { get { return this.helpstringField; } set { this.helpstringField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string name { get { return this.nameField; } set { this.nameField = value; } } } /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] [XmlRoot("NBAR2-Taxonomy", Namespace = "", IsNullable = false)] public partial class NBAR2Taxonomy { private object[] itemsField; /// <remarks/> [XmlElement("info", typeof (NBAR2TaxonomyInfo), Form = XmlSchemaForm.Unqualified)] [XmlElement("parameter", typeof (parameter))] [XmlElement("protocol", typeof (NBAR2TaxonomyProtocol), Form = XmlSchemaForm.Unqualified)] public object[] Items { get { return this.itemsField; } set { this.itemsField = value; } } } /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] public partial class NBAR2TaxonomyInfo { private string nameField; private string fileversionField; private string ppversionField; private string iosversionField; private string platformField; private string engineversionField; /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [XmlElement("file-version", Form = XmlSchemaForm.Unqualified )] public string fileversion { get { return this.fileversionField; } set { this.fileversionField = value; } } /// <remarks/> [XmlElement("pp-version", Form = XmlSchemaForm.Unqualified)] public string ppversion { get { return this.ppversionField; } set { this.ppversionField = value; } } /// <remarks/> [XmlElement("ios-version", Form = XmlSchemaForm.Unqualified) ] public string iosversion { get { return this.iosversionField; } set { this.iosversionField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string platform { get { return this.platformField; } set { this.platformField = value; } } /// <remarks/> [XmlElement("engine-version", Form = XmlSchemaForm.Unqualified)] public string engineversion { get { return this.engineversionField; } set { this.engineversionField = value; } } } /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] public partial class NBAR2TaxonomyProtocol { private string commonnameField; private string enabledField; private string engineidField; private string globalidField; private string helpstringField; private string idField; private string longdescriptionField; private string nameField; private string pdlversionField; private string referencesField; private string selectoridField; private string staticField; private string underlyingprotocolsField; private string usesbundlingField; private NBAR2TaxonomyProtocolAttributes[] attributesField; private NBAR2TaxonomyProtocolIpversion[] ipversionField; private NBAR2TaxonomyProtocolParameters[] parametersField; private NBAR2TaxonomyProtocolPorts[] portsField; /// <remarks/> [XmlElement("common-name", Form = XmlSchemaForm.Unqualified) ] public string commonname { get { return this.commonnameField; } set { this.commonnameField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string enabled { get { return this.enabledField; } set { this.enabledField = value; } } /// <remarks/> [XmlElement("engine-id", Form = XmlSchemaForm.Unqualified)] public string engineid { get { return this.engineidField; } set { this.engineidField = value; } } /// <remarks/> [XmlElement("global-id", Form = XmlSchemaForm.Unqualified)] public string globalid { get { return this.globalidField; } set { this.globalidField = value; } } /// <remarks/> [XmlElement("help-string", Form = XmlSchemaForm.Unqualified) ] public string helpstring { get { return this.helpstringField; } set { this.helpstringField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [XmlElement("long-description", Form = XmlSchemaForm.Unqualified)] public string longdescription { get { return this.longdescriptionField; } set { this.longdescriptionField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [XmlElement("pdl-version", Form = XmlSchemaForm.Unqualified) ] public string pdlversion { get { return this.pdlversionField; } set { this.pdlversionField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string references { get { return this.referencesField; } set { this.referencesField = value; } } /// <remarks/> [XmlElement("selector-id", Form = XmlSchemaForm.Unqualified) ] public string selectorid { get { return this.selectoridField; } set { this.selectoridField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string @static { get { return this.staticField; } set { this.staticField = value; } } /// <remarks/> [XmlElement("underlying-protocols", Form = XmlSchemaForm.Unqualified)] public string underlyingprotocols { get { return this.underlyingprotocolsField; } set { this.underlyingprotocolsField = value; } } /// <remarks/> [XmlElement("uses-bundling", Form = XmlSchemaForm.Unqualified)] public string usesbundling { get { return this.usesbundlingField; } set { this.usesbundlingField = value; } } /// <remarks/> [XmlElement("attributes", Form = XmlSchemaForm.Unqualified)] public NBAR2TaxonomyProtocolAttributes[] attributes { get { return this.attributesField; } set { this.attributesField = value; } } /// <remarks/> [XmlElement("ip-version", Form = XmlSchemaForm.Unqualified)] public NBAR2TaxonomyProtocolIpversion[] ipversion { get { return this.ipversionField; } set { this.ipversionField = value; } } /// <remarks/> [XmlElement("parameters", Form = XmlSchemaForm.Unqualified)] public NBAR2TaxonomyProtocolParameters[] parameters { get { return this.parametersField; } set { this.parametersField = value; } } /// <remarks/> [XmlElement("ports", Form = XmlSchemaForm.Unqualified)] public NBAR2TaxonomyProtocolPorts[] ports { get { return this.portsField; } set { this.portsField = value; } } } /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] public partial class NBAR2TaxonomyProtocolAttributes { private string applicationgroupField; private string categoryField; private string encryptedField; private string p2ptechnologyField; private string subcategoryField; private string tunnelField; /// <remarks/> [XmlElement("application-group", Form = XmlSchemaForm.Unqualified)] public string applicationgroup { get { return this.applicationgroupField; } set { this.applicationgroupField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string category { get { return this.categoryField; } set { this.categoryField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string encrypted { get { return this.encryptedField; } set { this.encryptedField = value; } } /// <remarks/> [XmlElement("p2p-technology", Form = XmlSchemaForm.Unqualified)] public string p2ptechnology { get { return this.p2ptechnologyField; } set { this.p2ptechnologyField = value; } } /// <remarks/> [XmlElement("sub-category", Form = XmlSchemaForm.Unqualified )] public string subcategory { get { return this.subcategoryField; } set { this.subcategoryField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string tunnel { get { return this.tunnelField; } set { this.tunnelField = value; } } } /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] public partial class NBAR2TaxonomyProtocolIpversion { private string ipv4Field; private string ipv6Field; /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string ipv4 { get { return this.ipv4Field; } set { this.ipv4Field = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string ipv6 { get { return this.ipv6Field; } set { this.ipv6Field = value; } } } /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] public partial class NBAR2TaxonomyProtocolParameters { private parameter[] fieldextractionField; private parameter[] subclassificationField; /// <remarks/> [XmlArray("field-extraction", Form = XmlSchemaForm.Unqualified)] [XmlArrayItem("parameter", typeof (parameter), IsNullable = false)] public parameter[] fieldextraction { get { return this.fieldextractionField; } set { this.fieldextractionField = value; } } /// <remarks/> [XmlArray("sub-classification", Form = XmlSchemaForm.Unqualified)] [XmlArrayItem("parameter", typeof (parameter), IsNullable = false)] public parameter[] subclassification { get { return this.subclassificationField; } set { this.subclassificationField = value; } } } /// <remarks/> [GeneratedCode("xsd", "2.0.50727.3038")] [Serializable()] [DebuggerStepThrough()] [DesignerCategory("code")] [XmlType(AnonymousType = true)] public partial class NBAR2TaxonomyProtocolPorts { private string ipField; private string tcpField; private string udpField; /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string ip { get { return this.ipField; } set { this.ipField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string tcp { get { return this.tcpField; } set { this.tcpField = value; } } /// <remarks/> [XmlElement(Form = XmlSchemaForm.Unqualified)] public string udp { get { return this.udpField; } set { this.udpField = value; } } } }
/////////////////////////////////////////////////////////////////////////// // Description: Data Access class for the table 'RS_KelompokPemeriksaan' // Generated by LLBLGen v1.21.2003.712 Final on: Thursday, October 11, 2007, 2:03:11 AM // Because the Base Class already implements IDispose, this class doesn't. /////////////////////////////////////////////////////////////////////////// using System; using System.Data; using System.Data.SqlTypes; using System.Data.SqlClient; namespace SIMRS.DataAccess { /// <summary> /// Purpose: Data Access class for the table 'RS_KelompokPemeriksaan'. /// </summary> public class RS_KelompokPemeriksaan : DBInteractionBase { #region Class Member Declarations private SqlBoolean _published; private SqlDateTime _createdDate, _modifiedDate; private SqlInt32 _createdBy, _modifiedBy, _ordering, _id, _jenisPemeriksaanId; private SqlString _kode, _nama, _keterangan, _jenisPemeriksaan; #endregion /// <summary> /// Purpose: Class constructor. /// </summary> public RS_KelompokPemeriksaan() { // Nothing for now. } /// <summary> /// Purpose: IsExist method. This method will check Exsisting data from database. /// </summary> /// <returns></returns> public bool IsExist() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_IsExist]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@JenisPemeriksaanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _jenisPemeriksaanId)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString()); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_IsExist' reported the ErrorCode: " + _errorCode); } return IsExist == 1; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::IsExist::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Insert method. This method will insert one new row into the database. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>Keterangan. May be SqlString.Null</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>ModifiedBy. May be SqlInt32.Null</LI> /// <LI>ModifiedDate. May be SqlDateTime.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Insert() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_Insert]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@JenisPemeriksaanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _jenisPemeriksaanId)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published)); cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_Insert' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::Insert::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Update method. This method will Update one existing row in the database. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>Keterangan. May be SqlString.Null</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>ModifiedBy. May be SqlInt32.Null</LI> /// <LI>ModifiedDate. May be SqlDateTime.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Update() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_Update]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@JenisPemeriksaanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _jenisPemeriksaanId)); cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode)); cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published)); cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_Update' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::Update::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key. /// </summary> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override bool Delete() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_Delete]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_Delete' reported the ErrorCode: " + _errorCode); } return true; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::Delete::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>Id</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// <LI>Id</LI> /// <LI>Kode</LI> /// <LI>Nama</LI> /// <LI>Keterangan</LI> /// <LI>Published</LI> /// <LI>Ordering</LI> /// <LI>CreatedBy</LI> /// <LI>CreatedDate</LI> /// <LI>ModifiedBy</LI> /// <LI>ModifiedDate</LI> /// </UL> /// Will fill all properties corresponding with a field in the table with the value of the row selected. /// </remarks> public override DataTable SelectOne() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_SelectOne]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_KelompokPemeriksaan"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_SelectOne' reported the ErrorCode: " + _errorCode); } if (toReturn.Rows.Count > 0) { _id = (Int32)toReturn.Rows[0]["Id"]; _jenisPemeriksaanId = (Int32)toReturn.Rows[0]["JenisPemeriksaanId"]; _kode = (string)toReturn.Rows[0]["Kode"]; _nama = (string)toReturn.Rows[0]["Nama"]; _keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"]; _published = (bool)toReturn.Rows[0]["Published"]; _ordering = (Int32)toReturn.Rows[0]["Ordering"]; _createdBy = (Int32)toReturn.Rows[0]["CreatedBy"]; _createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"]; _modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"]; _modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"]; } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::SelectOne::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: SelectAll method. This method will Select all rows from the table. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override DataTable SelectAll() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_SelectAll]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_KelompokPemeriksaan"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_SelectAll' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::SelectAll::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } public DataTable SelectAll2() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_SelectAll2]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("V_KelompokPemeriksaan"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_SelectAll2' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::SelectAll2::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: GetList method. This method will Select all rows from the table where is active. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable GetList() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_GetList]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_KelompokPemeriksaan"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_GetList' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::GetList::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } public DataTable GetListByJenisPemeriksaanId() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_KelompokPemeriksaan_GetListByJenisPemeriksaanId]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_KelompokPemeriksaan"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@JenisPemeriksaanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _jenisPemeriksaanId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if (_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_KelompokPemeriksaan_GetListByJenisPemeriksaanId' reported the ErrorCode: " + _errorCode); } return toReturn; } catch (Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_KelompokPemeriksaan::GetListByJenisPemeriksaanId::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } #region Class Property Declarations public SqlInt32 Id { get { return _id; } set { SqlInt32 idTmp = (SqlInt32)value; if (idTmp.IsNull) { throw new ArgumentOutOfRangeException("Id", "Id can't be NULL"); } _id = value; } } public SqlInt32 JenisPemeriksaanId { get { return _jenisPemeriksaanId; } set { _jenisPemeriksaanId = value; } } public SqlString Kode { get { return _kode; } set { SqlString kodeTmp = (SqlString)value; if (kodeTmp.IsNull) { throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL"); } _kode = value; } } public SqlString Nama { get { return _nama; } set { SqlString namaTmp = (SqlString)value; if (namaTmp.IsNull) { throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL"); } _nama = value; } } public SqlString Keterangan { get { return _keterangan; } set { _keterangan = value; } } public SqlBoolean Published { get { return _published; } set { _published = value; } } public SqlInt32 Ordering { get { return _ordering; } set { SqlInt32 orderingTmp = (SqlInt32)value; if (orderingTmp.IsNull) { throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL"); } _ordering = value; } } public SqlInt32 CreatedBy { get { return _createdBy; } set { SqlInt32 createdByTmp = (SqlInt32)value; if (createdByTmp.IsNull) { throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL"); } _createdBy = value; } } public SqlDateTime CreatedDate { get { return _createdDate; } set { SqlDateTime createdDateTmp = (SqlDateTime)value; if (createdDateTmp.IsNull) { throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL"); } _createdDate = value; } } public SqlInt32 ModifiedBy { get { return _modifiedBy; } set { _modifiedBy = value; } } public SqlDateTime ModifiedDate { get { return _modifiedDate; } set { _modifiedDate = value; } } public SqlString JenisPemeriksaan { get { return _jenisPemeriksaan; } set { _jenisPemeriksaan = value; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.MachineLearningCompute { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// These APIs allow end users to operate on Azure Machine Learning Compute /// resources. They support the following /// operations:&lt;ul&gt;&lt;li&gt;Create or update a /// cluster&lt;/li&gt;&lt;li&gt;Get a cluster&lt;/li&gt;&lt;li&gt;Patch a /// cluster&lt;/li&gt;&lt;li&gt;Delete a cluster&lt;/li&gt;&lt;li&gt;Get /// keys for a cluster&lt;/li&gt;&lt;li&gt;Check if updates are available /// for system services in a cluster&lt;/li&gt;&lt;li&gt;Update system /// services in a cluster&lt;/li&gt;&lt;li&gt;Get all clusters in a /// resource group&lt;/li&gt;&lt;li&gt;Get all clusters in a /// subscription&lt;/li&gt;&lt;/ul&gt; /// </summary> public partial class MachineLearningComputeManagementClient : ServiceClient<MachineLearningComputeManagementClient>, IMachineLearningComputeManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The Azure subscription ID. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The version of the Microsoft.MachineLearningCompute resource provider API /// to use. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IOperationalizationClustersOperations. /// </summary> public virtual IOperationalizationClustersOperations OperationalizationClusters { get; private set; } /// <summary> /// Gets the IMachineLearningComputeOperations. /// </summary> public virtual IMachineLearningComputeOperations MachineLearningCompute { get; private set; } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MachineLearningComputeManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MachineLearningComputeManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MachineLearningComputeManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MachineLearningComputeManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MachineLearningComputeManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MachineLearningComputeManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MachineLearningComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MachineLearningComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MachineLearningComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { OperationalizationClusters = new OperationalizationClustersOperations(this); MachineLearningCompute = new MachineLearningComputeOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2017-08-01-preview"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.IO; using Mono.Data.Sqlite; using System.Collections.Generic; using StriderMqtt; namespace NumbersTest { public class NumbersPersistence : IDisposable { readonly string ConnectionString; public SqliteConnection conn { get; private set; } public NumbersPersistence(string filename) { this.ConnectionString = "Data Source=" + filename; if (!File.Exists(filename)) { SqliteConnection.CreateFile(filename); } this.conn = new SqliteConnection(ConnectionString); this.conn.Open(); CreateTables(); } void CreateTables() { using (var trans = conn.BeginTransaction()) { // stores messages that were published to the broker using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = "CREATE TABLE IF NOT EXISTS published_numbers " + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, number INT)"; command.ExecuteNonQuery(); } // stores messages that were received from broker using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = "CREATE TABLE IF NOT EXISTS received_numbers " + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "topic TEXT, number INT)"; command.ExecuteNonQuery(); } // stores messages that were received from broker using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = @"CREATE TABLE IF NOT EXISTS last_received_per_topic (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, topic TEXT, number INT)"; command.ExecuteNonQuery(); } trans.Commit(); } } public void RegisterReceivedNumber(string topic, int number) { using (var trans = conn.BeginTransaction()) { using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = "INSERT INTO received_numbers (topic, number) VALUES (@topic, @number)"; command.Parameters.AddWithValue("@topic", topic); command.Parameters.AddWithValue("@number", number); command.ExecuteNonQuery(); } UpdateLastReceivedPerTopic(topic, number, trans); trans.Commit(); } } void UpdateLastReceivedPerTopic(string topic, int number, SqliteTransaction trans) { // check if row exists for the given topic to insert (if not exists) or update (if exists) object result; using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = "SELECT 1 FROM last_received_per_topic WHERE topic = @topic LIMIT 1"; command.Parameters.AddWithValue("@topic", topic); result = command.ExecuteScalar(); } string commandText; if (IsNull(result)) { commandText = @"INSERT INTO last_received_per_topic (topic, number) VALUES (@topic, @number)"; } else { commandText = @"UPDATE last_received_per_topic SET number = @number WHERE topic = @topic"; } using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = commandText; command.Parameters.AddWithValue("@topic", topic); command.Parameters.AddWithValue("@number", number); command.ExecuteNonQuery(); } } public int GetLastReceived(string topic) { object result; using (var command = conn.CreateCommand()) { command.CommandText = @"SELECT number FROM last_received_per_topic WHERE topic = @topic"; command.Parameters.AddWithValue("@topic", topic); result = command.ExecuteScalar(); } return IsNull(result) ? 0 : Convert.ToInt32(result); } public bool IsDoneReceiving(int maxNumber) { bool result = true; using (var trans = conn.BeginTransaction()) { using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = "SELECT number FROM last_received_per_topic"; SqliteDataReader reader = command.ExecuteReader(); while (reader.Read()) { if (reader.GetInt32(0) < maxNumber) { result = false; break; } } } trans.Commit(); } return result; } public int GetLastNumberSent() { object result; // if there is no outgoing message, return the last published number using (var command = conn.CreateCommand()) { command.CommandText = "SELECT MAX(number) FROM published_numbers"; result = command.ExecuteScalar(); } return IsNull(result) ? 0 : Convert.ToInt32(result); } public void RegisterPublishedNumber(int n) { using (var trans = conn.BeginTransaction()) { RegisterPublishedNumber(n, trans); trans.Commit(); } } void RegisterPublishedNumber(int n, SqliteTransaction trans) { using (var command = conn.CreateCommand()) { command.Transaction = trans; command.CommandText = "INSERT INTO published_numbers (number) VALUES (@number)"; command.Parameters.AddWithValue("@number", n); command.ExecuteNonQuery(); } } public void Dispose() { conn.Close(); conn.Dispose(); } bool IsNull(object result) { return result == null || result == DBNull.Value; } } }
using System; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.UI.WebControls; using ClientDependency.Core; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.propertytype; using Umbraco.Core; using Umbraco.Core.Configuration; namespace umbraco.controls.GenericProperties { /// <summary> /// Summary description for GenericProperty. /// </summary> [ClientDependency(ClientDependencyType.Css, "GenericProperty/genericproperty.css", "UmbracoClient")] [ClientDependency(ClientDependencyType.Javascript, "GenericProperty/genericproperty.js", "UmbracoClient")] public partial class GenericProperty : System.Web.UI.UserControl { /// <summary> /// Constructor /// </summary> public GenericProperty() { FullId = ""; AllowPropertyEdit = true; } private cms.businesslogic.datatype.DataTypeDefinition[] _dataTypeDefinitions; private int _tabId = 0; public event EventHandler Delete; /// <summary> /// Defines whether the property can be edited in the UI /// </summary> [Obsolete("Use the combination of AllowAliasEdit,AllowValidationEdit,AllowDelete,AllowDataTypeEdit instead")] public bool AllowPropertyEdit { get { return AllowAliasEdit && AllowValidationEdit && AllowDelete && AllowDataTypeEdit; } set { AllowAliasEdit = AllowValidationEdit = AllowDelete = AllowDataTypeEdit = true; } } /// <summary> /// Defines whether the property's name can be edited in the UI /// </summary> public bool AllowNameEdit { get; set; } public bool AllowAliasEdit { get; set; } public bool AllowDataTypeEdit { get; set; } public bool AllowTabEdit { get; set; } public bool AllowValidationEdit { get; set; } public bool AllowDescriptionEdit { get; set; } public bool AllowDelete { get; set; } public cms.businesslogic.datatype.DataTypeDefinition[] DataTypeDefinitions { set { _dataTypeDefinitions = value; } } public int TabId { set { _tabId = value; } } public PropertyType PropertyType { get; set; } public ContentType.TabI[] Tabs { get; set; } public string Name { get { return tbName.Text; } } public string Alias { get { return tbAlias.Text; } // FIXME so we blindly trust the UI for safe aliases?! } public string Description { get { return tbDescription.Text; } } public string Validation { get { return tbValidation.Text; } } public bool Mandatory { get { return checkMandatory.Checked; } } public int Tab { get { return int.Parse(ddlTab.SelectedValue); } } public string FullId { get; set; } public int Id { get; set; } public int Type { get { return int.Parse(ddlTypes.SelectedValue); } } public void Clear() { tbName.Text = ""; tbAlias.Text = ""; tbValidation.Text = ""; tbDescription.Text = ""; ddlTab.SelectedIndex = 0; SetDefaultDocumentTypeProperty(); checkMandatory.Checked = false; } protected void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { UpdateInterface(); } } //SD: this is temporary in v4, in v6 we have a proper user control hierarchy //containing this property. //this is required due to this issue: http://issues.umbraco.org/issue/u4-493 //because we need to execute some code in async but due to the localization //framework requiring an httpcontext.current, it will not work. //http://issues.umbraco.org/issue/u4-2143 //so, we are going to make a property here and ensure that the basepage has //resolved the user before we execute the async task so that in this method //our calls to ui.text will include the current user and not rely on the //httpcontext.current. This also makes it perform better: // http://issues.umbraco.org/issue/U4-2142 private User CurrentUser { get { return ((BasePage)Page).getUser(); } } public void UpdateInterface() { // Name and alias if (PropertyType != null) { Id = PropertyType.Id; //form.Attributes.Add("style", "display: none;"); tbName.Text = PropertyType.GetRawName(); tbAlias.Text = PropertyType.Alias; FullHeader.Text = PropertyType.GetRawName() + " (" + PropertyType.Alias + "), Type: " + PropertyType.DataTypeDefinition.Text; ; Header.Text = PropertyType.GetRawName(); DeleteButton.CssClass = "delete-button"; DeleteButton.Attributes.Add("onclick", "return confirm('" + ui.Text("areyousure", CurrentUser) + "');"); DeleteButton2.CssClass = "delete-button"; DeleteButton2.Attributes.Add("onclick", "return confirm('" + ui.Text("areyousure", CurrentUser) + "');"); DeleteButton.Visible = AllowDelete; DeleteButton2.Visible = AllowDelete; //alias visibility PropertyPanel2.Visible = AllowAliasEdit; //chk mandatory visibility PropertyPanel5.Visible = AllowValidationEdit; // validation visibility PropertyPanel6.Visible = AllowValidationEdit; // drop down data types visibility PropertyPanel3.Visible = AllowDataTypeEdit; // name visibility PropertyPanel1.Visible = AllowNameEdit; // desc visibility PropertyPanel7.Visible = AllowDescriptionEdit; } else { // Add new header FullHeader.Text = "Click here to add a new property"; Header.Text = "Create new property"; // Hide image button DeleteButton.Visible = false; DeleteButton2.Visible = false; } validationLink.NavigateUrl = "#"; validationLink.Attributes["onclick"] = ClientTools.Scripts.OpenModalWindow("dialogs/regexWs.aspx?target=" + tbValidation.ClientID, "Search for regular expression", 600, 500) + ";return false;"; // Data type definitions if (_dataTypeDefinitions != null) { ddlTypes.Items.Clear(); var itemSelected = false; foreach (cms.businesslogic.datatype.DataTypeDefinition dt in _dataTypeDefinitions) { var li = new ListItem(dt.Text, dt.Id.ToString(CultureInfo.InvariantCulture)); if ((PropertyType != null && PropertyType.DataTypeDefinition.Id == dt.Id)) { li.Selected = true; itemSelected = true; } ddlTypes.Items.Add(li); } // If item not selected from previous edit or load, set to default according to settings if (!itemSelected) { SetDefaultDocumentTypeProperty(); } } // tabs if (Tabs != null) { ddlTab.Items.Clear(); for (int i = 0; i < Tabs.Length; i++) { ListItem li = new ListItem(Tabs[i].Caption, Tabs[i].Id.ToString()); if (Tabs[i].Id == _tabId) li.Selected = true; ddlTab.Items.Add(li); } } ListItem liGeneral = new ListItem("Generic Properties", "0"); if (_tabId == 0) liGeneral.Selected = true; ddlTab.Items.Add(liGeneral); // mandatory if (PropertyType != null && PropertyType.Mandatory) checkMandatory.Checked = true; // validation if (PropertyType != null && string.IsNullOrEmpty(PropertyType.ValidationRegExp) == false) tbValidation.Text = PropertyType.ValidationRegExp; // description if (PropertyType != null && PropertyType.Description != "") tbDescription.Text = PropertyType.GetRawDescription(); } private void SetDefaultDocumentTypeProperty() { var itemToSelect = ddlTypes.Items.Cast<ListItem>() .FirstOrDefault(item => item.Text.ToLowerInvariant() == UmbracoConfig.For.UmbracoSettings().Content.DefaultDocumentTypeProperty.ToLowerInvariant()); if (itemToSelect != null) { itemToSelect.Selected = true; } else { ddlTypes.SelectedIndex = -1; } } protected void defaultDeleteHandler(object sender, EventArgs e) { } override protected void OnInit(EventArgs e) { base.OnInit(e); DeleteButton.Click += DeleteButton_Click; DeleteButton2.Click += DeleteButton2_Click; Delete += defaultDeleteHandler; // [ClientDependency(ClientDependencyType.Javascript, "js/UmbracoCasingRules.aspx", "UmbracoRoot")] var loader = ClientDependency.Core.Controls.ClientDependencyLoader.GetInstance(new HttpContextWrapper(Context)); var helper = new UrlHelper(new RequestContext(new HttpContextWrapper(Context), new RouteData())); loader.RegisterDependency(helper.GetCoreStringsControllerPath() + "ServicesJavaScript", ClientDependencyType.Javascript); } void DeleteButton2_Click(object sender, EventArgs e) { Delete(this, new EventArgs()); } void DeleteButton_Click(object sender, EventArgs e) { Delete(this, new EventArgs()); } /// <summary> /// DeleteButton2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton DeleteButton2; /// <summary> /// FullHeader control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal FullHeader; /// <summary> /// DeleteButton control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton DeleteButton; /// <summary> /// Header control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal Header; /// <summary> /// tbName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbName; /// <summary> /// PropertyPanel1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel PropertyPanel1; /// <summary> /// tbAlias control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbAlias; /// <summary> /// PropertyPanel2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel PropertyPanel2; /// <summary> /// ddlTypes control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlTypes; /// <summary> /// PropertyPanel3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel PropertyPanel3; /// <summary> /// ddlTab control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlTab; /// <summary> /// PropertyPanel4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel PropertyPanel4; /// <summary> /// checkMandatory control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox checkMandatory; /// <summary> /// PropertyPanel5 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel PropertyPanel5; /// <summary> /// tbValidation control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbValidation; /// <summary> /// validationLink control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink validationLink; /// <summary> /// PropertyPanel6 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel PropertyPanel6; /// <summary> /// tbDescription control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbDescription; protected global::umbraco.uicontrols.PropertyPanel PropertyPanel7; } }
using System; using System.Diagnostics.CodeAnalysis; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Threading; namespace Burden { /// <summary> Wraps up the durable storage and in-memory execution of jobs into something more convenient to use. </summary> /// <remarks> 7/24/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <typeparam name="TPoison"> Type of the poison. </typeparam> [SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes", Justification = "The heavy use of generics is mitigated by numerous static helpers that use compiler inference")] public class MonitoredJobQueue<TInput, TOutput, TPoison> : IMonitoredJobQueue<TInput, TOutput, TPoison> { private bool _disposed; private readonly ObservableDurableJobQueue<TInput, TPoison> _durableQueue; private readonly AutoJobExecutionQueue<TInput, TOutput> _jobQueue; private readonly DurableJobQueueMonitor<TInput, TPoison> _monitor; private readonly JobResultJournalWriter<TInput, TOutput, TPoison> _resultJournaler; private readonly IDisposable _subscription; private readonly IScheduler _scheduler; //creation calls should go through the static factory internal MonitoredJobQueue(ObservableDurableJobQueue<TInput, TPoison> durableQueue, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration, IJobResultInspector<TInput, TOutput, TPoison> resultsInspector, Func<IObservable<TInput>, IObservable<TInput>> notificationFilter, IScheduler scheduler) { //perform null checks only, knowing that additional checks are performed by the new() calls below and will bubble up if (null == durableQueue) { throw new ArgumentNullException("durableQueue"); } if (null == jobAction) { throw new ArgumentNullException("jobAction"); } if (null == jobQueueConfiguration) { throw new ArgumentNullException("jobQueueConfiguration"); } if (null == resultsInspector) { throw new ArgumentNullException("resultsInspector"); } if (null == scheduler) { throw new ArgumentNullException("scheduler"); } if (scheduler == System.Reactive.Concurrency.Scheduler.Immediate) { throw new ArgumentException("Scheduler.Immediate can have horrible side affects, like totally locking up on Subscribe calls, so don't use it", "scheduler"); } this._scheduler = scheduler; this._durableQueue = durableQueue; this._monitor = new DurableJobQueueMonitor<TInput, TPoison>(durableQueue, jobQueueConfiguration.MaxQueueItemsToPublishPerInterval, jobQueueConfiguration.PollingInterval, scheduler); this._jobQueue = new AutoJobExecutionQueue<TInput, TOutput>(scheduler, jobQueueConfiguration.MaxConcurrentJobsToExecute, jobQueueConfiguration.MaxConcurrentJobsToExecute); this._resultJournaler = new JobResultJournalWriter<TInput, TOutput, TPoison>(_jobQueue.WhenJobCompletes, resultsInspector, durableQueue, null, scheduler); //apply a user-specified filter i this._subscription = (null == notificationFilter ? _monitor : notificationFilter(_monitor)) .SubscribeOn(scheduler) .Subscribe(input => _jobQueue.Add(input, jobAction)); } /// <summary> Dispose of this object, cleaning up any resources it uses. </summary> /// <remarks> 7/24/2011. </remarks> public void Dispose() { if (!this._disposed) { Dispose(true); GC.SuppressFinalize(this); } } /// <summary> /// Dispose of this object, cleaning up any resources it uses. Will cancel any outstanding un-executed jobs, and will wait on jobs /// currently executing to complete. /// </summary> /// <remarks> 7/24/2011. </remarks> /// <param name="disposing"> true if resources should be disposed, false if not. </param> protected virtual void Dispose(bool disposing) { if (disposing) { this._disposed = true; CancelQueuedAndWaitForExecutingJobsToComplete(TimeSpan.FromSeconds(20)); _jobQueue.Dispose(); _subscription.Dispose(); _resultJournaler.Dispose(); _durableQueue.Dispose(); } } /// <summary> Gets the scheduler. </summary> /// <value> The scheduler. </value> public IScheduler Scheduler { get { return _scheduler; } } /// <summary> Gets notifications as items are moved around the durable queue. </summary> /// <value> A sequence of observable durable queue notifications. </value> public IObservable<DurableJobQueueAction<TInput, TPoison>> OnQueueAction { get { return _durableQueue.OnQueueAction; } } /// <summary> /// The Observable that monitors job completion, where completion can be either run to completion, exception or cancellation. /// </summary> /// <value> A sequence of observable job completion notifications. </value> public IObservable<JobResult<TInput, TOutput>> OnJobCompletion { get { return _jobQueue.WhenJobCompletes; } } /// <summary> Gets the maximum number of concurrent jobs allowed to execute for this queue. </summary> /// <value> The maximum allowed concurrent jobs. </value> public int MaxConcurrent { get { return _jobQueue.MaxConcurrent; } set { _jobQueue.MaxConcurrent = value; } } /// <summary> Gets the number of running jobs from the job execution queue. </summary> /// <value> The number of running jobs. </value> public int RunningCount { get { return _jobQueue.RunningCount; } } /// <summary> Gets the number of queued jobs from the job execution queue. </summary> /// <value> The number of queued jobs. </value> public int QueuedCount { get { return _jobQueue.QueuedCount; } } /// <summary> Gets the maximum allowable queue items to publish per interval, presently 50000. </summary> /// <value> The maximum allowable queue items to publish per interval, presently 50000. </value> public int MaxQueueItemsToPublishPerInterval { get { return this._monitor.MaxQueueItemsToPublishPerInterval; } } /// <summary> Gets the polling interval. </summary> /// <value> The polling interval. </value> public TimeSpan PollingInterval { get { return this._monitor.PollingInterval; } } /// <summary> Adds a job. </summary> /// <remarks> 7/24/2011. </remarks> /// <param name="input"> The input. </param> public void AddJob(TInput input) { _durableQueue.Queue(input); } /// <summary> Cancel queued and wait for executing jobs to complete. </summary> /// <remarks> 7/24/2011. </remarks> public void CancelQueuedAndWaitForExecutingJobsToComplete(TimeSpan timeout) { var manualResetEventSlim = new ManualResetEventSlim(false); using (var completed = _jobQueue.WhenQueueEmpty .Do(n => {}, () => manualResetEventSlim.Set()) .Subscribe()) { _jobQueue.CancelOutstandingJobs(); if (_jobQueue.RunningCount != 0) { manualResetEventSlim.Wait(timeout); } } } } /// <summary> /// A simple helper class for creating a simplified IMonitoredJobQueue facade given an IDurableJobQueueFactory and job action. Overloads /// provide the ability to inspect given job output via a custom result inspection method. /// </summary> /// <remarks> 7/24/2011. </remarks> public static class MonitoredJobQueue { private static ObservableDurableJobQueue<TQueue, TQueuePoison> CreateQueue<TQueue, TQueuePoison>(IDurableJobQueueFactory durableQueueFactory) { if (null == durableQueueFactory) { throw new ArgumentNullException("durableQueueFactory"); } return new ObservableDurableJobQueue<TQueue, TQueuePoison>(durableQueueFactory.CreateDurableJobQueue<TQueue, TQueuePoison>()); } /// <summary> /// Creates a simplified IMonitoredJobQueue interface given a durable queue factory, job action and maximum items to queue per interval. /// Poison is defaulted to Poison{TInput}. JobResultInspector is defaulted based on the job specification. /// DurableJobQueueMonitor.DefaultPollingInterval is used as a polling interval. /// </summary> /// <remarks> 7/27/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <param name="durableQueueFactory"> A durable queue factory. </param> /// <param name="jobAction"> The job action. </param> /// <param name="maxConcurrentJobsToExecute"> The maximum queue items to execute (which manipulates the maximum queue items published /// per interval based on an assumed 1/2 sec per job). </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory or action are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, Poison<TInput>> Create<TInput, TOutput>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, int maxConcurrentJobsToExecute) { return new MonitoredJobQueue<TInput, TOutput, Poison<TInput>>(CreateQueue<TInput, Poison<TInput>>(durableQueueFactory), jobAction, new MonitoredJobQueueConfiguration(maxConcurrentJobsToExecute), JobResultInspector.FromJobSpecification(jobAction), null, LocalScheduler.Default); } /// <summary> /// Creates a simplified IMonitoredJobQueue interface given a durable queue factory, job action and maximum items to queue per interval. /// Poison is defaulted to Poison{TInput}. JobResultInspector is defaulted based on the job specification. /// DurableJobQueueMonitor.DefaultPollingInterval is used as a polling interval. /// </summary> /// <remarks> 7/27/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <param name="durableQueueFactory"> A durable queue factory. </param> /// <param name="jobAction"> The job action. </param> /// <param name="jobQueueConfiguration"> Defines the maximum queue items to execute concurrently, polling interval and how many items /// should be removed from the durable queue and entered into the job queue over the course of a /// given interval,. </param> /// <param name="notificationFilter"> Provides a way to filter job requests after they're pulled from the durable queue, and /// just before they are to enter the execution queue (for instance, for duplicates). Null values are ignored. </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory or action are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, Poison<TInput>> Create<TInput, TOutput>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration, Func<IObservable<TInput>, IObservable<TInput>> notificationFilter) { return new MonitoredJobQueue<TInput, TOutput, Poison<TInput>>(CreateQueue<TInput, Poison<TInput>>(durableQueueFactory), jobAction, jobQueueConfiguration, JobResultInspector.FromJobSpecification(jobAction), notificationFilter, LocalScheduler.Default); } /// <summary> /// Creates a simplified IMonitoredJobQueue interface given a durable queue factory, job action and maximum items to queue per interval. /// Poison is defaulted to Poison{TInput}. JobResultInspector is defaulted based on the job specification. /// </summary> /// <remarks> 7/27/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <param name="durableQueueFactory"> A durable queue factory. </param> /// <param name="jobAction"> The job action. </param> /// <param name="jobQueueConfiguration"> Defines the maximum queue items to execute concurrently, polling interval and how many items /// should be removed from the durable queue and entered into the job queue over the course of a /// given interval,. </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory or action are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low, /// or the polling interval is too fast or slow. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, Poison<TInput>> Create<TInput, TOutput>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration) { return new MonitoredJobQueue<TInput, TOutput, Poison<TInput>>(CreateQueue<TInput, Poison<TInput>>(durableQueueFactory), jobAction, jobQueueConfiguration, JobResultInspector.FromJobSpecification(jobAction), null, LocalScheduler.Default); } /// <summary> /// Creates a simplified IMonitoredJobQueue interface given a durable queue factory, a job action, a results inspector and maximum items /// to queue per interval. DurableJobQueueMonitor. /// </summary> /// <remarks> 7/24/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <typeparam name="TPoison"> Type of the poison. </typeparam> /// <param name="durableQueueFactory"> A durable queue factory. </param> /// <param name="jobAction"> The job action. </param> /// <param name="resultsInspector"> The results inspector. </param> /// <param name="jobQueueConfiguration"> Defines the maximum queue items to execute concurrently, polling interval and how many items /// should be removed from the durable queue and entered into the job queue over the course of a /// given interval,. </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory, job queue or results inspectors are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low, /// or the polling interval is too fast or slow. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, TPoison> Create<TInput, TOutput, TPoison>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration, IJobResultInspector<TInput, TOutput, TPoison> resultsInspector) { return new MonitoredJobQueue<TInput, TOutput, TPoison>(CreateQueue<TInput, TPoison>(durableQueueFactory), jobAction, jobQueueConfiguration, resultsInspector, null, LocalScheduler.Default); } /// <summary> /// Creates a simplified IMonitoredJobQueue interface given a durable queue factory, a job action, a results inspector and maximum items /// to queue per interval. DurableJobQueueMonitor. /// </summary> /// <remarks> 7/24/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <typeparam name="TPoison"> Type of the poison. </typeparam> /// <param name="durableQueueFactory"> A durable queue factory. </param> /// <param name="jobAction"> The job action. </param> /// <param name="resultsInspector"> The results inspector. </param> /// <param name="jobQueueConfiguration"> Defines the maximum queue items to execute concurrently, polling interval and how many items /// should be removed from the durable queue and entered into the job queue over the course of a /// given interval,. </param> /// <param name="notificationFilter"> Provides a way to filter job requests after they're pulled from the durable queue, and /// just before they are to enter the execution queue (for instance, for duplicates). Null values are ignored. </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory, job queue or results inspectors are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low, /// or the polling interval is too fast or slow. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, TPoison> Create<TInput, TOutput, TPoison>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration, IJobResultInspector<TInput, TOutput, TPoison> resultsInspector, Func<IObservable<TInput>, IObservable<TInput>> notificationFilter) { return new MonitoredJobQueue<TInput, TOutput, TPoison>(CreateQueue<TInput, TPoison>(durableQueueFactory), jobAction, jobQueueConfiguration, resultsInspector, notificationFilter, LocalScheduler.Default); } /// <summary> Creates a simplified IMonitoredJobQueue interface given a durable queue factory and a job queue. </summary> /// <remarks> 7/24/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <typeparam name="TPoison"> Type of the poison. </typeparam> /// <param name="durableQueueFactory"> A durable queue to which all job information is written in a fail-safe manner. </param> /// <param name="jobAction"> The job action. </param> /// <param name="resultsInspector"> The results inspector. </param> /// <param name="jobQueueConfiguration"> Defines the maximum queue items to execute concurrently, polling interval and how many items /// should be removed from the durable queue and entered into the job queue over the course of a /// given interval,. </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory, job queue or results inspectors are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low, /// or the polling interval is too fast or slow. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, TPoison> Create<TInput, TOutput, TPoison>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration, Func<JobResult<TInput, TOutput>, JobQueueAction<TPoison>> resultsInspector) { return new MonitoredJobQueue<TInput, TOutput, TPoison>(CreateQueue<TInput, TPoison>(durableQueueFactory), jobAction, jobQueueConfiguration, JobResultInspector.FromInspector(resultsInspector), null, LocalScheduler.Default); } /// <summary> Creates a simplified IMonitoredJobQueue interface given a durable queue factory and a job queue. </summary> /// <remarks> 7/24/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <typeparam name="TPoison"> Type of the poison. </typeparam> /// <param name="durableQueueFactory"> A durable queue to which all job information is written in a fail-safe manner. </param> /// <param name="jobAction"> The job action. </param> /// <param name="resultsInspector"> The results inspector. </param> /// <param name="jobQueueConfiguration"> Defines the maximum queue items to execute concurrently, polling interval and how many items /// should be removed from the durable queue and entered into the job queue over the course of a /// given interval,. </param> /// <param name="notificationFilter"> Provides a way to filter job requests after they're pulled from the durable queue, and /// just before they are to enter the execution queue (for instance, for duplicates). Null values are ignored. </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory, job queue or results inspectors are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low, /// or the polling interval is too fast or slow. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, TPoison> Create<TInput, TOutput, TPoison>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration, Func<JobResult<TInput, TOutput>, JobQueueAction<TPoison>> resultsInspector, Func<IObservable<TInput>, IObservable<TInput>> notificationFilter) { return new MonitoredJobQueue<TInput, TOutput, TPoison>(CreateQueue<TInput, TPoison>(durableQueueFactory), jobAction, jobQueueConfiguration, JobResultInspector.FromInspector(resultsInspector), notificationFilter, LocalScheduler.Default); } /// <summary> Creates a simplified IMonitoredJobQueue interface given a durable queue factory and a job queue. </summary> /// <remarks> 7/24/2011. </remarks> /// <typeparam name="TInput"> Type of the input. </typeparam> /// <typeparam name="TOutput"> Type of the output. </typeparam> /// <typeparam name="TPoison"> Type of the poison. </typeparam> /// <param name="durableQueueFactory"> A durable queue to which all job information is written in a fail-safe manner. </param> /// <param name="jobAction"> The job action. </param> /// <param name="jobQueueConfiguration"> Defines the maximum queue items to execute concurrently, polling interval and how many items /// should be removed from the durable queue and entered into the job queue over the course of a /// given interval,. </param> /// <param name="resultsInspector"> The results inspector. </param> /// <param name="notificationFilter"> Provides a way to filter job requests after they're pulled from the durable queue, and just /// before they are to enter the execution queue (for instance, for duplicates). Null values are /// ignored. </param> /// <param name="scheduler"> The scheduler that can be used to adjust scheduling policies. Use this only with great care. </param> /// <returns> An IMonitoredJobQueue instance that simplifies queuing inputs. </returns> /// <exception cref="ArgumentNullException"> Thrown when the factory, job queue or results inspectors are null. </exception> /// <exception cref="ArgumentOutOfRangeException"> Thrown when the maximum queue items to publish per interval is too high or low, /// or the polling interval is too fast or slow. </exception> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposables are now responsibility of MonitoredJobQueue")] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Nested generics, while advanced, are perfectly acceptable within Funcs and we get to use compiler inference here")] public static IMonitoredJobQueue<TInput, TOutput, TPoison> Create<TInput, TOutput, TPoison>(IDurableJobQueueFactory durableQueueFactory, Func<TInput, TOutput> jobAction, MonitoredJobQueueConfiguration jobQueueConfiguration, IJobResultInspector<TInput, TOutput, TPoison> resultsInspector, Func<IObservable<TInput>, IObservable<TInput>> notificationFilter, IScheduler scheduler) { return new MonitoredJobQueue<TInput, TOutput, TPoison>(CreateQueue<TInput, TPoison>(durableQueueFactory), jobAction, jobQueueConfiguration, resultsInspector, notificationFilter, scheduler); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.ObjectModel; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.Security.Principal; using System.Collections.Generic; using System.Globalization; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.Runtime.Diagnostics; namespace System.ServiceModel.Security { public abstract class IdentityVerifier { protected IdentityVerifier() { // empty } public static IdentityVerifier CreateDefault() { return DefaultIdentityVerifier.Instance; } public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext); public abstract bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity); static void AdjustAddress(ref EndpointAddress reference, Uri via) { // if we don't have an identity and we have differing Uris, we should use the Via if (reference.Identity == null && reference.Uri != via) { reference = new EndpointAddress(via); } } internal bool TryGetIdentity(EndpointAddress reference, Uri via, out EndpointIdentity identity) { AdjustAddress(ref reference, via); return this.TryGetIdentity(reference, out identity); } internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, Uri via, AuthorizationContext authorizationContext) { AdjustAddress(ref serviceReference, via); this.EnsureIdentity(serviceReference, authorizationContext, SR.IdentityCheckFailedForOutgoingMessage); } internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { if (authorizationPolicies == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies"); } AuthorizationContext ac = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies); EnsureIdentity(serviceReference, ac, SR.IdentityCheckFailedForOutgoingMessage); } private void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString) { if (authorizationContext == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext"); } EndpointIdentity identity; if (!TryGetIdentity(serviceReference, out identity)) { SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, this.GetType()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(errorString, identity, serviceReference))); } else { if (!CheckAccess(identity, authorizationContext)) { // CheckAccess performs a Trace on failure, no need to do it twice Exception e = CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference); throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(e); } } } private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference) { Exception result; if (identity.IdentityClaim != null && identity.IdentityClaim.ClaimType == ClaimTypes.Dns && identity.IdentityClaim.Right == Rights.PossessProperty && identity.IdentityClaim.Resource is string) { string expectedDnsName = (string)identity.IdentityClaim.Resource; string actualDnsName = null; for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authorizationContext.ClaimSets[i]; foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty)) { if (claim.Resource is string) { actualDnsName = (string)claim.Resource; break; } } if (actualDnsName != null) { break; } } if (SR.IdentityCheckFailedForIncomingMessage.Equals(errorString)) { if (actualDnsName == null) { result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName)); } else { result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName)); } } else if (SR.IdentityCheckFailedForOutgoingMessage.Equals(errorString)) { if (actualDnsName == null) { result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName)); } else { result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName)); } } else { result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference)); } } else { result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference)); } return result; } private class DefaultIdentityVerifier : IdentityVerifier { static readonly DefaultIdentityVerifier instance = new DefaultIdentityVerifier(); public static DefaultIdentityVerifier Instance { get { return instance; } } public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity) { if (reference == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reference"); identity = reference.Identity; if (identity == null) { identity = this.TryCreateDnsIdentity(reference); } if (identity == null) { SecurityTraceRecordHelper.TraceIdentityDeterminationFailure(reference, typeof(DefaultIdentityVerifier)); return false; } else { SecurityTraceRecordHelper.TraceIdentityDeterminationSuccess(reference, identity, typeof(DefaultIdentityVerifier)); return true; } } EndpointIdentity TryCreateDnsIdentity(EndpointAddress reference) { Uri toAddress = reference.Uri; if (!toAddress.IsAbsoluteUri) return null; return EndpointIdentity.CreateDnsIdentity(toAddress.DnsSafeHost); } internal Claim CheckDnsEquivalence(ClaimSet claimSet, string expectedSpn) { // host/<machine-name> satisfies the DNS identity claim IEnumerable<Claim> claims = claimSet.FindClaims(ClaimTypes.Spn, Rights.PossessProperty); foreach (Claim claim in claims) { if (expectedSpn.Equals((string)claim.Resource, StringComparison.OrdinalIgnoreCase)) { return claim; } } return null; } public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext) { EventTraceActivity eventTraceActivity = null; if (identity == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity"); if (authContext == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext"); if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null); } for (int i = 0; i < authContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authContext.ClaimSets[i]; if (claimSet.ContainsClaim(identity.IdentityClaim)) { SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType()); return true; } // try Claim equivalence string expectedSpn = null; if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType)) { expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource); Claim claim = CheckDnsEquivalence(claimSet, expectedSpn); if (claim != null) { SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType()); return true; } } // Allow a Sid claim to support UPN, and SPN identities // SID claims not available yet //SecurityIdentifier identitySid = null; //if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType)) //{ // throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid"); //} //else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType)) //{ // throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn"); //} //else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType)) //{ // throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn"); //} //else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType)) //{ // throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns"); //} //if (identitySid != null) //{ // Claim claim = CheckSidEquivalence(identitySid, claimSet); // if (claim != null) // { // SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType()); // return true; // } //} } SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType()); if (TD.SecurityIdentityVerificationFailureIsEnabled()) { TD.SecurityIdentityVerificationFailure(eventTraceActivity); } return false; } } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Semmle.Extraction.CSharp.Entities { internal abstract class Type : CachedSymbol<ITypeSymbol> { #nullable disable warnings protected Type(Context cx, ITypeSymbol? init) : base(cx, init) { } #nullable restore warnings public override bool NeedsPopulation => base.NeedsPopulation || Symbol.TypeKind == TypeKind.Dynamic || Symbol.TypeKind == TypeKind.TypeParameter; public static bool ConstructedOrParentIsConstructed(INamedTypeSymbol symbol) { return !SymbolEqualityComparer.Default.Equals(symbol, symbol.OriginalDefinition) || symbol.ContainingType is not null && ConstructedOrParentIsConstructed(symbol.ContainingType); } public Kinds.TypeKind GetTypeKind(Context cx, bool constructUnderlyingTupleType) { switch (Symbol.SpecialType) { case SpecialType.System_Int32: return Kinds.TypeKind.INT; case SpecialType.System_UInt32: return Kinds.TypeKind.UINT; case SpecialType.System_Int16: return Kinds.TypeKind.SHORT; case SpecialType.System_UInt16: return Kinds.TypeKind.USHORT; case SpecialType.System_UInt64: return Kinds.TypeKind.ULONG; case SpecialType.System_Int64: return Kinds.TypeKind.LONG; case SpecialType.System_Void: return Kinds.TypeKind.VOID; case SpecialType.System_Double: return Kinds.TypeKind.DOUBLE; case SpecialType.System_Byte: return Kinds.TypeKind.BYTE; case SpecialType.System_SByte: return Kinds.TypeKind.SBYTE; case SpecialType.System_Boolean: return Kinds.TypeKind.BOOL; case SpecialType.System_Char: return Kinds.TypeKind.CHAR; case SpecialType.System_Decimal: return Kinds.TypeKind.DECIMAL; case SpecialType.System_Single: return Kinds.TypeKind.FLOAT; case SpecialType.System_IntPtr: return Kinds.TypeKind.INT_PTR; default: if (Symbol.IsBoundNullable()) return Kinds.TypeKind.NULLABLE; switch (Symbol.TypeKind) { case TypeKind.Class: return Kinds.TypeKind.CLASS; case TypeKind.Struct: return ((INamedTypeSymbol)Symbol).IsTupleType && !constructUnderlyingTupleType ? Kinds.TypeKind.TUPLE : Kinds.TypeKind.STRUCT; case TypeKind.Interface: return Kinds.TypeKind.INTERFACE; case TypeKind.Array: return Kinds.TypeKind.ARRAY; case TypeKind.Enum: return Kinds.TypeKind.ENUM; case TypeKind.Delegate: return Kinds.TypeKind.DELEGATE; case TypeKind.Pointer: return Kinds.TypeKind.POINTER; case TypeKind.FunctionPointer: return Kinds.TypeKind.FUNCTION_POINTER; case TypeKind.Error: return Kinds.TypeKind.UNKNOWN; default: cx.ModelError(Symbol, $"Unhandled type kind '{Symbol.TypeKind}'"); return Kinds.TypeKind.UNKNOWN; } } } protected void PopulateType(TextWriter trapFile, bool constructUnderlyingTupleType = false) { PopulateMetadataHandle(trapFile); PopulateAttributes(); trapFile.Write("types("); trapFile.WriteColumn(this); trapFile.Write(','); trapFile.WriteColumn((int)GetTypeKind(Context, constructUnderlyingTupleType)); trapFile.Write(",\""); Symbol.BuildDisplayName(Context, trapFile, constructUnderlyingTupleType); trapFile.WriteLine("\")"); var baseTypes = GetBaseTypeDeclarations(); // Visit base types if (Symbol.GetNonObjectBaseType(Context) is INamedTypeSymbol @base) { var bts = GetBaseTypeDeclarations(baseTypes, @base); Context.PopulateLater(() => { var baseKey = Create(Context, @base); trapFile.extend(this, baseKey.TypeRef); if (Symbol.TypeKind != TypeKind.Struct) { foreach (var bt in bts) { TypeMention.Create(Context, bt.Type, this, baseKey); } } }); } // Visit implemented interfaces if (!(base.Symbol is IArrayTypeSymbol)) { foreach (var i in base.Symbol.Interfaces) { var bts = GetBaseTypeDeclarations(baseTypes, i); Context.PopulateLater(() => { var interfaceKey = Create(Context, i); trapFile.implement(this, interfaceKey.TypeRef); foreach (var bt in bts) { TypeMention.Create(Context, bt.Type, this, interfaceKey); } }); } } var containingType = ContainingType; if (containingType is not null && Symbol.Kind != SymbolKind.TypeParameter) { var originalDefinition = Symbol.TypeKind == TypeKind.Error ? this : Create(Context, Symbol.OriginalDefinition); trapFile.nested_types(this, containingType, originalDefinition); } else if (Symbol.ContainingNamespace is not null) { trapFile.parent_namespace(this, Namespace.Create(Context, Symbol.ContainingNamespace)); } if (Symbol is IArrayTypeSymbol array) { // They are in the namespace of the original object var elementType = array.ElementType; var ns = elementType.TypeKind == TypeKind.TypeParameter ? Context.Compilation.GlobalNamespace : elementType.ContainingNamespace; if (ns is not null) trapFile.parent_namespace(this, Namespace.Create(Context, ns)); } if (Symbol is IPointerTypeSymbol pointer) { var elementType = pointer.PointedAtType; var ns = elementType.TypeKind == TypeKind.TypeParameter ? Context.Compilation.GlobalNamespace : elementType.ContainingNamespace; if (ns is not null) trapFile.parent_namespace(this, Namespace.Create(Context, ns)); } if (Symbol.BaseType is not null && Symbol.BaseType.SpecialType == SpecialType.System_MulticastDelegate) { // This is a delegate. // The method "Invoke" has the return type. var invokeMethod = ((INamedTypeSymbol)Symbol).DelegateInvokeMethod!; ExtractParametersForDelegateLikeType(trapFile, invokeMethod, t => trapFile.delegate_return_type(this, t)); } if (Symbol is IFunctionPointerTypeSymbol functionPointer) { ExtractParametersForDelegateLikeType(trapFile, functionPointer.Signature, t => trapFile.function_pointer_return_type(this, t)); } Modifier.ExtractModifiers(Context, trapFile, this, Symbol); } private IEnumerable<BaseTypeSyntax> GetBaseTypeDeclarations() { if (!IsSourceDeclaration || !Symbol.FromSource()) { return Enumerable.Empty<BaseTypeSyntax>(); } var declSyntaxReferences = Symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax()).ToArray(); var baseLists = declSyntaxReferences.OfType<ClassDeclarationSyntax>().Select(c => c.BaseList); baseLists = baseLists.Concat(declSyntaxReferences.OfType<InterfaceDeclarationSyntax>().Select(c => c.BaseList)); baseLists = baseLists.Concat(declSyntaxReferences.OfType<StructDeclarationSyntax>().Select(c => c.BaseList)); return baseLists .Where(bl => bl is not null) .SelectMany(bl => bl!.Types) .ToList(); } private IEnumerable<BaseTypeSyntax> GetBaseTypeDeclarations(IEnumerable<BaseTypeSyntax> baseTypes, INamedTypeSymbol type) { return baseTypes.Where(bt => SymbolEqualityComparer.Default.Equals(Context.GetModel(bt).GetTypeInfo(bt.Type).Type, type)); } private void ExtractParametersForDelegateLikeType(TextWriter trapFile, IMethodSymbol invokeMethod, Action<Type> storeReturnType) { for (var i = 0; i < invokeMethod.Parameters.Length; ++i) { var param = invokeMethod.Parameters[i]; var originalParam = invokeMethod.OriginalDefinition.Parameters[i]; var originalParamEntity = SymbolEqualityComparer.Default.Equals(param, originalParam) ? null : DelegateTypeParameter.Create(Context, originalParam, Create(Context, ((INamedTypeSymbol)Symbol).OriginalDefinition)); DelegateTypeParameter.Create(Context, param, this, originalParamEntity); } var returnKey = Create(Context, invokeMethod.ReturnType); storeReturnType(returnKey.TypeRef); Method.ExtractRefReturn(trapFile, invokeMethod, this); } /// <summary> /// Called to extract all members and nested types. /// This is called on each member of a namespace, /// in either source code or an assembly. /// </summary> public void ExtractRecursive() { foreach (var l in Symbol.DeclaringSyntaxReferences.Select(s => s.GetSyntax().GetLocation())) { Context.BindComments(this, l); } foreach (var member in Symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.NamedType: Create(Context, (ITypeSymbol)member).ExtractRecursive(); break; default: Context.CreateEntity(member); break; } } } /// <summary> /// Extracts all members and nested types of this type. /// </summary> public void PopulateGenerics() { if (Symbol is null || !NeedsPopulation || !Context.ExtractGenerics(this)) return; var members = new List<ISymbol>(); foreach (var member in Symbol.GetMembers()) members.Add(member); foreach (var member in Symbol.GetTypeMembers()) members.Add(member); // Mono extractor puts all BASE interface members as members of the current interface. if (Symbol.TypeKind == TypeKind.Interface) { foreach (var baseInterface in Symbol.Interfaces) { foreach (var member in baseInterface.GetMembers()) members.Add(member); foreach (var member in baseInterface.GetTypeMembers()) members.Add(member); } } foreach (var member in members) { Context.CreateEntity(member); } if (Symbol.BaseType is not null) Create(Context, Symbol.BaseType).PopulateGenerics(); foreach (var i in Symbol.Interfaces) { Create(Context, i).PopulateGenerics(); } } public void ExtractRecursive(TextWriter trapFile, IEntity parent) { if (Symbol.ContainingSymbol.Kind == SymbolKind.Namespace && !Symbol.ContainingNamespace.IsGlobalNamespace) { trapFile.parent_namespace_declaration(this, (NamespaceDeclaration)parent); } ExtractRecursive(); } public static Type Create(Context cx, ITypeSymbol? type) { type = type.DisambiguateType(); return type is null ? NullType.Create(cx) : (Type)cx.CreateEntity(type); } public static Type Create(Context cx, AnnotatedTypeSymbol? type) => Create(cx, type?.Symbol); public virtual int Dimension => 0; public static bool IsDelegate(ITypeSymbol? symbol) => symbol is not null && symbol.TypeKind == TypeKind.Delegate; /// <summary> /// A copy of a delegate "Invoke" method or function pointer parameter. /// </summary> private class DelegateTypeParameter : Parameter { private DelegateTypeParameter(Context cx, IParameterSymbol init, IEntity parent, Parameter? original) : base(cx, init, parent, original) { } public static new DelegateTypeParameter Create(Context cx, IParameterSymbol param, IEntity parent, Parameter? original = null) => // We need to use a different cache key than `param` to avoid mixing up // `DelegateTypeParameter`s and `Parameter`s DelegateTypeParameterFactory.Instance.CreateEntity(cx, (typeof(DelegateTypeParameter), new SymbolEqualityWrapper(param)), (param, parent, original)); private class DelegateTypeParameterFactory : CachedEntityFactory<(IParameterSymbol, IEntity, Parameter?), DelegateTypeParameter> { public static DelegateTypeParameterFactory Instance { get; } = new DelegateTypeParameterFactory(); public override DelegateTypeParameter Create(Context cx, (IParameterSymbol, IEntity, Parameter?) init) => new DelegateTypeParameter(cx, init.Item1, init.Item2, init.Item3); } } /// <summary> /// Gets a reference to this type, if the type /// is defined in another assembly. /// </summary> public virtual Type TypeRef => this; public virtual IEnumerable<Type> TypeMentions { get { yield break; } } public override bool Equals(object? obj) { var other = obj as Type; return other?.GetType() == GetType() && SymbolEqualityComparer.Default.Equals(other.Symbol, Symbol); } public override int GetHashCode() => SymbolEqualityComparer.Default.GetHashCode(Symbol); } internal abstract class Type<T> : Type where T : ITypeSymbol { protected Type(Context cx, T init) : base(cx, init) { } public new T Symbol => (T)base.Symbol; } }
// 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.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Windows.Markup; using System.Xaml.Replacements; using TypeListConverter = System.Xaml.Replacements.TypeListConverter; namespace System.Xaml.Schema { internal class BuiltInValueConverter<TConverterBase> : XamlValueConverter<TConverterBase> where TConverterBase : class { private Func<TConverterBase> _factory; internal BuiltInValueConverter(Type converterType, Func<TConverterBase> factory) :base(converterType, null) { _factory = factory; } internal override bool IsPublic { get { return true; } } protected override TConverterBase CreateInstance() { return _factory.Invoke(); } } internal static class BuiltInValueConverter { private static XamlValueConverter<TypeConverter> s_String; private static XamlValueConverter<TypeConverter> s_Object; private static XamlValueConverter<TypeConverter> s_Int32; private static XamlValueConverter<TypeConverter> s_Int16; private static XamlValueConverter<TypeConverter> s_Int64; private static XamlValueConverter<TypeConverter> s_UInt32; private static XamlValueConverter<TypeConverter> s_UInt16; private static XamlValueConverter<TypeConverter> s_UInt64; private static XamlValueConverter<TypeConverter> s_Boolean; private static XamlValueConverter<TypeConverter> s_Double; private static XamlValueConverter<TypeConverter> s_Single; private static XamlValueConverter<TypeConverter> s_Byte; private static XamlValueConverter<TypeConverter> s_SByte; private static XamlValueConverter<TypeConverter> s_Char; private static XamlValueConverter<TypeConverter> s_Decimal; private static XamlValueConverter<TypeConverter> s_TimeSpan; private static XamlValueConverter<TypeConverter> s_Guid; private static XamlValueConverter<TypeConverter> s_Type; private static XamlValueConverter<TypeConverter> s_TypeList; private static XamlValueConverter<TypeConverter> s_DateTime; private static XamlValueConverter<TypeConverter> s_DateTimeOffset; private static XamlValueConverter<TypeConverter> s_CultureInfo; private static XamlValueConverter<ValueSerializer> s_StringSerializer; private static XamlValueConverter<TypeConverter> s_Delegate; private static XamlValueConverter<TypeConverter> s_Uri; internal static XamlValueConverter<TypeConverter> Int32 { get { if (s_Int32 is null) { s_Int32 = new BuiltInValueConverter<TypeConverter>(typeof(Int32Converter), () => new Int32Converter()); } return s_Int32; } } internal static XamlValueConverter<TypeConverter> String { get { if (s_String is null) { s_String = new BuiltInValueConverter<TypeConverter>(typeof(StringConverter), () => new StringConverter()); } return s_String; } } internal static XamlValueConverter<TypeConverter> Object { get { if (s_Object is null) { s_Object = new XamlValueConverter<TypeConverter>(null, XamlLanguage.Object); } return s_Object; } } internal static XamlValueConverter<TypeConverter> Event { get { if (s_Delegate is null) { s_Delegate = new BuiltInValueConverter<TypeConverter>(typeof(EventConverter), () => new EventConverter()); } return s_Delegate; } } internal static XamlValueConverter<TypeConverter> GetTypeConverter(Type targetType) { if (typeof(string) == targetType) { return String; } if (typeof(object) == targetType) { return Object; } if (typeof(Int32) == targetType) { return Int32; } if (typeof(Int16) == targetType) { if (s_Int16 is null) { s_Int16 = new BuiltInValueConverter<TypeConverter>(typeof(Int16Converter), () => new Int16Converter()); } return s_Int16; } if (typeof(Int64) == targetType) { if (s_Int64 is null) { s_Int64 = new BuiltInValueConverter<TypeConverter>(typeof(Int64Converter), () => new Int64Converter()); } return s_Int64; } if (typeof(UInt32) == targetType) { if (s_UInt32 is null) { s_UInt32 = new BuiltInValueConverter<TypeConverter>(typeof(UInt32Converter), () => new UInt32Converter()); } return s_UInt32; } if (typeof(UInt16) == targetType) { if (s_UInt16 is null) { s_UInt16 = new BuiltInValueConverter<TypeConverter>(typeof(UInt16Converter), () => new UInt16Converter()); } return s_UInt16; } if (typeof(UInt64) == targetType) { if (s_UInt64 is null) { s_UInt64 = new BuiltInValueConverter<TypeConverter>(typeof(UInt64Converter), () => new UInt64Converter()); } return s_UInt64; } if (typeof(Boolean) == targetType) { if (s_Boolean is null) { s_Boolean = new BuiltInValueConverter<TypeConverter>(typeof(BooleanConverter), () => new BooleanConverter()); } return s_Boolean; } if (typeof(Double) == targetType) { if (s_Double is null) { s_Double = new BuiltInValueConverter<TypeConverter>(typeof(DoubleConverter), () => new DoubleConverter()); } return s_Double; } if (typeof(Single) == targetType) { if (s_Single is null) { s_Single = new BuiltInValueConverter<TypeConverter>(typeof(SingleConverter), () => new SingleConverter()); } return s_Single; } if (typeof(Byte) == targetType) { if (s_Byte is null) { s_Byte = new BuiltInValueConverter<TypeConverter>(typeof(ByteConverter), () => new ByteConverter()); } return s_Byte; } if (typeof(SByte) == targetType) { if (s_SByte is null) { s_SByte = new BuiltInValueConverter<TypeConverter>(typeof(SByteConverter), () => new SByteConverter()); } return s_SByte; } if (typeof(Char) == targetType) { if (s_Char is null) { s_Char = new BuiltInValueConverter<TypeConverter>(typeof(CharConverter), () => new CharConverter()); } return s_Char; } if (typeof(Decimal) == targetType) { if (s_Decimal is null) { s_Decimal = new BuiltInValueConverter<TypeConverter>(typeof(DecimalConverter), () => new DecimalConverter()); } return s_Decimal; } if (typeof(TimeSpan) == targetType) { if (s_TimeSpan is null) { s_TimeSpan = new BuiltInValueConverter<TypeConverter>(typeof(TimeSpanConverter), () => new TimeSpanConverter()); } return s_TimeSpan; } if (typeof(Guid) == targetType) { if (s_Guid is null) { s_Guid = new BuiltInValueConverter<TypeConverter>(typeof(GuidConverter), () => new GuidConverter()); } return s_Guid; } if (typeof(Type).IsAssignableFrom(targetType)) { if (s_Type is null) { s_Type = new BuiltInValueConverter<TypeConverter>(typeof(TypeTypeConverter), () => new TypeTypeConverter()); } return s_Type; } if (typeof(Type[]).IsAssignableFrom(targetType)) { if (s_TypeList is null) { s_TypeList = new BuiltInValueConverter<TypeConverter>(typeof(TypeListConverter), () => new TypeListConverter()); } return s_TypeList; } if (typeof(DateTime) == targetType) { if (s_DateTime is null) { s_DateTime = new BuiltInValueConverter<TypeConverter>(typeof(DateTimeConverter2), () => new DateTimeConverter2()); } return s_DateTime; } if (typeof(DateTimeOffset) == targetType) { if (s_DateTimeOffset is null) { s_DateTimeOffset = new BuiltInValueConverter<TypeConverter>(typeof(DateTimeOffsetConverter2), () => new DateTimeOffsetConverter2()); } return s_DateTimeOffset; } if (typeof(CultureInfo).IsAssignableFrom(targetType)) { if (s_CultureInfo is null) { s_CultureInfo = new BuiltInValueConverter<TypeConverter>(typeof(CultureInfoConverter), () => new CultureInfoConverter()); } return s_CultureInfo; } if (typeof(Delegate).IsAssignableFrom(targetType)) { if (s_Delegate is null) { s_Delegate = new BuiltInValueConverter<TypeConverter>(typeof(EventConverter), () => new EventConverter()); } return s_Delegate; } if (typeof(Uri).IsAssignableFrom(targetType)) { if(s_Uri is null) { TypeConverter stdConverter = null; try { stdConverter = TypeDescriptor.GetConverter(typeof(Uri)); // The TypeConverter for Uri, if one is found, should be capable of converting from { String, Uri } // and converting to { String, Uri, System.ComponentModel.Design.Serialization.InstanceDescriptor } if (stdConverter == null || !stdConverter.CanConvertFrom(typeof(string)) || !stdConverter.CanConvertFrom(typeof(Uri)) || !stdConverter.CanConvertTo(typeof(string)) || !stdConverter.CanConvertTo(typeof(Uri)) || !stdConverter.CanConvertTo(typeof(InstanceDescriptor))) { stdConverter = null; } } catch (NotSupportedException) { } if (stdConverter == null) { s_Uri = new BuiltInValueConverter<TypeConverter>(typeof(TypeUriConverter), () => new TypeUriConverter()); } else { // There is a built-in TypeConverter available. Very likely, System.UriTypeConverter, but this was not naturally // discovered. this is probably due to the fact that System.Uri does not have [TypeConverterAttribute(typeof(UriConverter))] // in the .NET Core codebase. // Since a default converter was discovered, just use that instead of our own (very nearly equivalent) implementation. s_Uri = new BuiltInValueConverter<TypeConverter>(stdConverter.GetType(), () => TypeDescriptor.GetConverter(typeof(Uri))); } } return s_Uri; } return null; } internal static XamlValueConverter<ValueSerializer> GetValueSerializer(Type targetType) { if (typeof(string) == targetType) { if (s_StringSerializer is null) { // Once StringSerializer is TypeForwarded to S.X, this can be made more efficient ValueSerializer stringSerializer = ValueSerializer.GetSerializerFor(typeof(string)); s_StringSerializer = new BuiltInValueConverter<ValueSerializer>(stringSerializer.GetType(), () => stringSerializer); } return s_StringSerializer; } return null; } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion using NServiceKit.FluentValidation; using NServiceKit.FluentValidation.Resources; using NServiceKit.FluentValidation.Results; using NServiceKit.FluentValidation.Validators; namespace FluentValidation.Mvc { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web.Mvc; /// <summary>A fluent validation model metadata provider.</summary> public class FluentValidationModelMetadataProvider : DataAnnotationsModelMetadataProvider { readonly IValidatorFactory factory; /// <summary>Initializes a new instance of the FluentValidation.Mvc.FluentValidationModelMetadataProvider class.</summary> /// /// <param name="factory">The factory.</param> public FluentValidationModelMetadataProvider(IValidatorFactory factory) { this.factory = factory; } /// <summary>Returns the metadata for the specified property using the container type and property descriptor.</summary> /// /// <param name="modelAccessor"> The model accessor.</param> /// <param name="containerType"> The type of the container.</param> /// <param name="propertyDescriptor">The property descriptor.</param> /// /// <returns>The metadata for the specified property using the container type and property descriptor.</returns> protected override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, PropertyDescriptor propertyDescriptor) { var attributes = ConvertFVMetaDataToAttributes(containerType, propertyDescriptor.Name); return CreateMetadata(attributes, containerType, modelAccessor, propertyDescriptor.PropertyType, propertyDescriptor.Name); } IEnumerable<Attribute> ConvertFVMetaDataToAttributes(Type type, string name) { var validator = factory.GetValidator(type); if (validator == null) { return Enumerable.Empty<Attribute>(); } IEnumerable<IPropertyValidator> validators; // if (name == null) { //validators = validator.CreateDescriptor().GetMembersWithValidators().SelectMany(x => x); // validators = Enumerable.Empty<IPropertyValidator>(); // } // else { validators = validator.CreateDescriptor().GetValidatorsForMember(name); // } var attributes = validators.OfType<IAttributeMetadataValidator>() .Select(x => x.ToAttribute()) .Concat(SpecialCaseValidatorConversions(validators)); return attributes.ToList(); } IEnumerable<Attribute> SpecialCaseValidatorConversions(IEnumerable<IPropertyValidator> validators) { //Email Validator should be convertible to DataType EmailAddress. var emailValidators = validators .OfType<IEmailValidator>() .Select(x => new DataTypeAttribute(DataType.EmailAddress)) .Cast<Attribute>(); var requiredValidators = validators.OfType<INotNullValidator>().Cast<IPropertyValidator>() .Concat(validators.OfType<INotEmptyValidator>().Cast<IPropertyValidator>()) .Select(x => new RequiredAttribute()) .Cast<Attribute>(); return requiredValidators.Concat(emailValidators); } /*IEnumerable<Attribute> ConvertFVMetaDataToAttributes(Type type) { return ConvertFVMetaDataToAttributes(type, null); }*/ /*public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType) { var attributes = ConvertFVMetaDataToAttributes(modelType); return CreateMetadata(attributes, null /* containerType ?1?, modelAccessor, modelType, null /* propertyName ?1?); }*/ } /// <summary>Interface for attribute metadata validator.</summary> public interface IAttributeMetadataValidator : IPropertyValidator { /// <summary>Converts this object to an attribute.</summary> /// /// <returns>This object as an Attribute.</returns> Attribute ToAttribute(); } internal class AttributeMetadataValidator : IAttributeMetadataValidator { readonly Attribute attribute; /// <summary>Initializes a new instance of the FluentValidation.Mvc.AttributeMetadataValidator class.</summary> /// /// <param name="attributeConverter">The attribute converter.</param> public AttributeMetadataValidator(Attribute attributeConverter) { attribute = attributeConverter; } /// <summary>Gets or sets the error message source.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <value>The error message source.</value> public IStringSource ErrorMessageSource { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary>Gets or sets the error code.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <value>The error code.</value> public string ErrorCode { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary>Enumerates validate in this collection.</summary> /// /// <param name="context">The context.</param> /// /// <returns>An enumerator that allows foreach to be used to process validate in this collection.</returns> public IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) { return Enumerable.Empty<ValidationFailure>(); } /// <summary>Gets or sets the error message template.</summary> /// /// <value>The error message template.</value> public string ErrorMessageTemplate { get { return null; } set { } } /// <summary>Gets the custom message format arguments.</summary> /// /// <value>The custom message format arguments.</value> public ICollection<Func<object, object>> CustomMessageFormatArguments { get { return null; } } /// <summary>Gets a value indicating whether the supports standalone validation.</summary> /// /// <value>true if supports standalone validation, false if not.</value> public bool SupportsStandaloneValidation { get { return false; } } /// <summary>Gets or sets the custom state provider.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <value>The custom state provider.</value> public Func<object, object> CustomStateProvider { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary>Converts this object to an attribute.</summary> /// /// <returns>This object as an Attribute.</returns> public Attribute ToAttribute() { return attribute; } } } namespace FluentValidation.Mvc.MetadataExtensions { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; /// <summary>A metadata extensions.</summary> public static class MetadataExtensions { /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that hidden input.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder">The ruleBuilder to act on.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> HiddenInput<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new HiddenInputAttribute())); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that hidden input.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder"> The ruleBuilder to act on.</param> /// <param name="displayValue">true to display value.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> HiddenInput<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool displayValue) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new HiddenInputAttribute { DisplayValue = displayValue })); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that user interface hints.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder">The ruleBuilder to act on.</param> /// <param name="hint"> The hint.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> UIHint<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string hint) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new UIHintAttribute(hint))); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that user interface hints.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder"> The ruleBuilder to act on.</param> /// <param name="hint"> The hint.</param> /// <param name="presentationLayer">The presentation layer.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> UIHint<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string hint, string presentationLayer) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new UIHintAttribute(hint, presentationLayer))); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that scaffolds.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder">The ruleBuilder to act on.</param> /// <param name="scaffold"> true to scaffold.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> Scaffold<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool scaffold) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new ScaffoldColumnAttribute(scaffold))); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that data type.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder">The ruleBuilder to act on.</param> /// <param name="dataType"> Type of the data.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> DataType<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, DataType dataType) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DataTypeAttribute(dataType))); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that data type.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder"> The ruleBuilder to act on.</param> /// <param name="customDataType">Type of the custom data.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> DataType<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string customDataType) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DataTypeAttribute(customDataType))); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that displays a name.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder">The ruleBuilder to act on.</param> /// <param name="name"> The name.</param> /// /// <returns>An IRuleBuilder&lt;T,TProperty&gt;</returns> public static IRuleBuilder<T, TProperty> DisplayName<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string name) { #if NET4 return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DisplayAttribute { Name = name })); #else return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DisplayNameAttribute(name))); #endif } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that displays a format described by ruleBuilder.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder">The ruleBuilder to act on.</param> /// /// <returns>An IDisplayFormatBuilder&lt;T,TProperty&gt;</returns> public static IDisplayFormatBuilder<T, TProperty> DisplayFormat<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) { return new DisplayFormatBuilder<T, TProperty>(ruleBuilder); } /// <summary>An IRuleBuilder&lt;T,TProperty&gt; extension method that reads an only.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> /// <param name="ruleBuilder">The ruleBuilder to act on.</param> /// <param name="readOnly"> true to read only.</param> /// /// <returns>The only.</returns> public static IRuleBuilder<T, TProperty> ReadOnly<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool readOnly) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new ReadOnlyAttribute(readOnly))); } /// <summary>Interface for display format builder.</summary> /// /// <typeparam name="T"> Generic type parameter.</typeparam> /// <typeparam name="TProperty">Type of the property.</typeparam> public interface IDisplayFormatBuilder<T, TProperty> : IRuleBuilder<T, TProperty> { IDisplayFormatBuilder<T, TProperty> NullDisplayText(string text); IDisplayFormatBuilder<T, TProperty> DataFormatString(string text); IDisplayFormatBuilder<T, TProperty> ApplyFormatInEditMode(bool apply); IDisplayFormatBuilder<T, TProperty> ConvertEmptyStringToNull(bool convert); } private class DisplayFormatBuilder<T, TProperty> : IDisplayFormatBuilder<T, TProperty> { readonly IRuleBuilder<T, TProperty> builder; readonly DisplayFormatAttribute attribute = new DisplayFormatAttribute(); /// <summary>Initializes a new instance of the FluentValidation.Mvc.MetadataExtensions.MetadataExtensions.DisplayFormatBuilder&lt;T, TProperty&gt; class.</summary> /// /// <param name="builder">The builder.</param> public DisplayFormatBuilder(IRuleBuilder<T, TProperty> builder) { this.builder = builder; builder.SetValidator(new AttributeMetadataValidator(attribute)); } /// <summary>Sets a validator.</summary> /// /// <param name="validator">The validator.</param> /// /// <returns>An IRuleBuilderOptions&lt;T,TProperty&gt;</returns> public IRuleBuilderOptions<T, TProperty> SetValidator(IPropertyValidator validator) { return builder.SetValidator(validator); } /// <summary>Sets a validator.</summary> /// /// <param name="validator">The validator.</param> /// /// <returns>An IRuleBuilderOptions&lt;T,TProperty&gt;</returns> [Obsolete] public IRuleBuilderOptions<T, TProperty> SetValidator(IValidator validator) { return builder.SetValidator(validator); } /// <summary>Sets a validator.</summary> /// /// <param name="validator">The validator.</param> /// /// <returns>An IRuleBuilderOptions&lt;T,TProperty&gt;</returns> public IRuleBuilderOptions<T, TProperty> SetValidator(IValidator<TProperty> validator) { return builder.SetValidator(validator); } /// <summary>Null display text.</summary> /// /// <param name="text">The text.</param> /// /// <returns>An IDisplayFormatBuilder&lt;T,TProperty&gt;</returns> public IDisplayFormatBuilder<T, TProperty> NullDisplayText(string text) { attribute.NullDisplayText = text; return this; } /// <summary>Data format string.</summary> /// /// <param name="text">The text.</param> /// /// <returns>An IDisplayFormatBuilder&lt;T,TProperty&gt;</returns> public IDisplayFormatBuilder<T, TProperty> DataFormatString(string text) { attribute.DataFormatString = text; return this; } /// <summary>Applies the format in edit mode described by apply.</summary> /// /// <param name="apply">true to apply.</param> /// /// <returns>An IDisplayFormatBuilder&lt;T,TProperty&gt;</returns> public IDisplayFormatBuilder<T, TProperty> ApplyFormatInEditMode(bool apply) { attribute.ApplyFormatInEditMode = apply; return this; } /// <summary>Convert empty string to null.</summary> /// /// <param name="convert">true to convert.</param> /// /// <returns>The empty converted string to null.</returns> public IDisplayFormatBuilder<T, TProperty> ConvertEmptyStringToNull(bool convert) { attribute.ConvertEmptyStringToNull = convert; return this; } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Assets /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class AR : EduHubEntity { #region Navigation Property Cache private AKC Cache_CATEGORY_AKC; private AKT Cache_ASSET_TYPE_AKT; private AKR Cache_RELEASE_TYPE_AKR; private AKCT Cache_TAX_CATEGORY_AKCT; private AKL Cache_LOCATION_AKL; private AKD Cache_DEPARTMENT_AKD; private AKB Cache_BRANCH_AKB; private CR Cache_ORIG_SUPPLIER_CR; private CR Cache_CURR_SUPPLIER_CR; private GL Cache_PTE_GLCODE_GL; private KADM Cache_AMETHOD_KADM; private KADM Cache_TMETHOD_KADM; private AR Cache_COMPONENT_OF_AR; private SCI Cache_CAMPUS_SCI; #endregion #region Foreign Navigation Properties private IReadOnlyList<AKK> Cache_ARKEY_AKK_CODE; private IReadOnlyList<AR> Cache_ARKEY_AR_COMPONENT_OF; private IReadOnlyList<ARF> Cache_ARKEY_ARF_CODE; private IReadOnlyList<CRF> Cache_ARKEY_CRF_ATKEY; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Prime Key /// [Uppercase Alphanumeric (10)] /// </summary> public string ARKEY { get; internal set; } /// <summary> /// Numeric SAMS number for DE&amp;T export /// </summary> public int ARNUMBER { get; internal set; } /// <summary> /// Title (Primary description) /// [Alphanumeric (40)] /// </summary> public string TITLE { get; internal set; } /// <summary> /// Extra description of the asset /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION01 { get; internal set; } /// <summary> /// Extra description of the asset /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION02 { get; internal set; } /// <summary> /// Asset category /// [Uppercase Alphanumeric (10)] /// </summary> public string CATEGORY { get; internal set; } /// <summary> /// Asset type /// [Uppercase Alphanumeric (2)] /// </summary> public string ASSET_TYPE { get; internal set; } /// <summary> /// Asset Release Type /// [Uppercase Alphanumeric (2)] /// </summary> public string RELEASE_TYPE { get; internal set; } /// <summary> /// Asset tax category /// [Uppercase Alphanumeric (10)] /// </summary> public string TAX_CATEGORY { get; internal set; } /// <summary> /// Asset locations /// [Uppercase Alphanumeric (10)] /// </summary> public string LOCATION { get; internal set; } /// <summary> /// Departments /// [Uppercase Alphanumeric (10)] /// </summary> public string DEPARTMENT { get; internal set; } /// <summary> /// Sub Category /// [Uppercase Alphanumeric (10)] /// </summary> public string BRANCH { get; internal set; } /// <summary> /// Lease start date /// </summary> public DateTime? LEASE_START_DATE { get; internal set; } /// <summary> /// Lease end date /// </summary> public DateTime? LEASE_END_DATE { get; internal set; } /// <summary> /// For leased items /// </summary> public decimal? LEASE_COST_MONTH { get; internal set; } /// <summary> /// Supplier /// [Uppercase Alphanumeric (10)] /// </summary> public string ORIG_SUPPLIER { get; internal set; } /// <summary> /// Default repairer /// [Uppercase Alphanumeric (10)] /// </summary> public string CURR_SUPPLIER { get; internal set; } /// <summary> /// Invoice number of original acquisition /// [Alphanumeric (10)] /// </summary> public string ORIG_INVOICE_NO { get; internal set; } /// <summary> /// Invoice number of most recent purchase/addition /// [Alphanumeric (10)] /// </summary> public string LAST_INVOICE_NO { get; internal set; } /// <summary> /// Initial Purchase date /// </summary> public DateTime? PURDATE { get; internal set; } /// <summary> /// Last addition date /// </summary> public DateTime? LAST_ADDN_DATE { get; internal set; } /// <summary> /// Disposal date /// </summary> public DateTime? LAST_DISP_DATE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? LAST_GST_RECLAIM { get; internal set; } /// <summary> /// Last revaluation date /// </summary> public DateTime? LAST_REVAL_DATE { get; internal set; } /// <summary> /// GL acct where pte use % of depn will be posted /// [Uppercase Alphanumeric (10)] /// </summary> public string PTE_GLCODE { get; internal set; } /// <summary> /// Percentage of private use for accounting /// </summary> public double? PTE_USE_RATE { get; internal set; } /// <summary> /// Actuals:Open Bal - Cost ex GST /// </summary> public decimal? AOB_COST { get; internal set; } /// <summary> /// Actuals:Open Bal - Revaluations /// </summary> public decimal? AOB_REVALS { get; internal set; } /// <summary> /// Actual Disposals:Open Bal - Reductions in /// Original Cost ex GST /// </summary> public decimal? AOB_DISP_COST { get; internal set; } /// <summary> /// Actual Disposals:Open Bal - Reductions in /// Revaluation Adjustments /// </summary> public decimal? AOB_DISP_REVALS { get; internal set; } /// <summary> /// This year's additions /// </summary> public decimal? ATY_COST { get; internal set; } /// <summary> /// Actuals:This Year - Revaluation Adjustments /// </summary> public decimal? ATY_REVALS { get; internal set; } /// <summary> /// Actual Disposals:This Year - Reductions in /// </summary> public decimal? ATY_DISP_REVALS { get; internal set; } /// <summary> /// This Year - Reductions in Original Cost ex GST /// </summary> public decimal? ATY_DISP_COST { get; internal set; } /// <summary> /// ADep:Open Bal - Accum Depreciation /// </summary> public decimal? AOB_DEPN { get; internal set; } /// <summary> /// Private % of depn charged in prior years /// </summary> public decimal? AOB_PTE_DEPN { get; internal set; } /// <summary> /// ADep Disposals:Open bal - /// - Reductions in Accum Depreciation /// </summary> public decimal? AOB_DISP_DEPN { get; internal set; } /// <summary> /// ADep Disposals:Open Bal /// - Profit or Loss on Disposals /// </summary> public decimal? AOB_DISP_PROF { get; internal set; } /// <summary> /// ADep:This Year - Accum /// </summary> public decimal? ATY_DEPN { get; internal set; } /// <summary> /// Private % of depn charged this year /// </summary> public decimal? ATY_PTE_DEPN { get; internal set; } /// <summary> /// ADep Disposals:This Year /// - Reductions in Accum /// </summary> public decimal? ATY_DISP_DEPN { get; internal set; } /// <summary> /// ADep Disposals:This Year /// - Profit or Loss on Disposals /// </summary> public decimal? ATY_DISP_PROF { get; internal set; } /// <summary> /// Account rate /// </summary> public double? ARATE { get; internal set; } /// <summary> /// method /// [Uppercase Alphanumeric (1)] /// </summary> public string AMETHOD { get; internal set; } /// <summary> /// Estimated Life in Units /// </summary> public int? AEST_LIFE_UNITS { get; internal set; } /// <summary> /// Description of type of units used /// [Alphanumeric (30)] /// </summary> public string AUNITS_DESC { get; internal set; } /// <summary> /// Units used to date /// </summary> public int? AUNITS_TO_DATE { get; internal set; } /// <summary> /// indicator /// [Uppercase Alphanumeric (1)] /// </summary> public string AFLAG { get; internal set; } /// <summary> /// Start date for /// </summary> public DateTime? ADEPN_START { get; internal set; } /// <summary> /// Date last depreciated for accounting /// </summary> public DateTime? ADEPN_LAST_DATE { get; internal set; } /// <summary> /// Open Bal - Original GST /// </summary> public decimal? AOB_ORIG_GST { get; internal set; } /// <summary> /// Open Bal - Unclaimed GST /// </summary> public decimal? AOB_UNCL_GST { get; internal set; } /// <summary> /// Disposals:Open Bal-Reductions in Unclaimed GST /// </summary> public decimal? AOB_DISP_UNCL_GST { get; internal set; } /// <summary> /// Disposals:Open Bal-Reductions in Original GST /// </summary> public decimal? AOB_DISP_ORIG_GST { get; internal set; } /// <summary> /// This Year - Original GST /// </summary> public decimal? ATY_ORIG_GST { get; internal set; } /// <summary> /// This Year - Unclaimed GST /// </summary> public decimal? ATY_UNCL_GST { get; internal set; } /// <summary> /// Disposals:This Year Reductions in Unclaimed GST /// </summary> public decimal? ATY_DISP_UNCL_GST { get; internal set; } /// <summary> /// Disposals:This Year Reductions in Original GST /// </summary> public decimal? ATY_DISP_ORIG_GST { get; internal set; } /// <summary> /// TDep: Open Bal - Cost ex GST /// </summary> public decimal? TOB_COST { get; internal set; } /// <summary> /// TDep: Open Bal - Accum /// </summary> public decimal? TOB_DEPN { get; internal set; } /// <summary> /// Private % of tax depn charged in prior years /// </summary> public decimal? TOB_PTE_DEPN { get; internal set; } /// <summary> /// TDep: Open Bal - Reductions in Original Cost ex GST /// </summary> public decimal? TOB_DISP_COST { get; internal set; } /// <summary> /// TDep: Open Bal - Reductions in Accum /// </summary> public decimal? TOB_DISP_DEPN { get; internal set; } /// <summary> /// TDep: Open Bal - Profit/Loss on Disposals /// </summary> public decimal? TOB_DISP_PROF { get; internal set; } /// <summary> /// TDep: Open Bal - Gain on Disposals /// </summary> public decimal? TOB_DISP_GAIN { get; internal set; } /// <summary> /// TDep: This Year - Cost ex GST /// </summary> public decimal? TTY_COST { get; internal set; } /// <summary> /// TDep: This Year - Accum /// </summary> public decimal? TTY_DEPN { get; internal set; } /// <summary> /// Private % of depn charged this year /// </summary> public decimal? TTY_PTE_DEPN { get; internal set; } /// <summary> /// TDep: This Year - Reductions in Original Cost ex GST /// </summary> public decimal? TTY_DISP_COST { get; internal set; } /// <summary> /// TDep: This Year-Reductions in Accum /// </summary> public decimal? TTY_DISP_DEPN { get; internal set; } /// <summary> /// TDep: This Year - Profit/Loss on Disposals /// </summary> public decimal? TTY_DISP_PROF { get; internal set; } /// <summary> /// TDep: This Year - Gain on Disposals /// </summary> public decimal? TTY_DISP_GAIN { get; internal set; } /// <summary> /// Tax rate /// </summary> public double? TRATE { get; internal set; } /// <summary> /// Depreciation method /// [Uppercase Alphanumeric (1)] /// </summary> public string TMETHOD { get; internal set; } /// <summary> /// Depreciation indicator /// [Uppercase Alphanumeric (1)] /// </summary> public string TFLAG { get; internal set; } /// <summary> /// Start date for depreciation /// </summary> public DateTime? TDEPN_START { get; internal set; } /// <summary> /// Date last depreciated for tax /// </summary> public DateTime? TDEPN_LAST_DATE { get; internal set; } /// <summary> /// Open Bal - Original GST /// </summary> public decimal? TOB_ORIG_GST { get; internal set; } /// <summary> /// Open Bal - Unclaimed GST /// </summary> public decimal? TOB_UNCL_GST { get; internal set; } /// <summary> /// Disposals:Open Bal-Reductions in Unclaimed GST /// </summary> public decimal? TOB_DISP_UNCL_GST { get; internal set; } /// <summary> /// Disposals:Open Bal-Reductions in Original GST /// </summary> public decimal? TOB_DISP_ORIG_GST { get; internal set; } /// <summary> /// This Year - Original GST /// </summary> public decimal? TTY_ORIG_GST { get; internal set; } /// <summary> /// This Year - Unclaimed GST /// </summary> public decimal? TTY_UNCL_GST { get; internal set; } /// <summary> /// Disposals:This Year Reductions in Unclaimed GST /// </summary> public decimal? TTY_DISP_UNCL_GST { get; internal set; } /// <summary> /// Disposals:This Year Reductions in Original GST /// </summary> public decimal? TTY_DISP_ORIG_GST { get; internal set; } /// <summary> /// Actuals:Open Bal - Quantity /// </summary> public short? OB_QTY { get; internal set; } /// <summary> /// Actual Disposals:Open Bal - Quantity /// </summary> public short? OB_DISP_QTY { get; internal set; } /// <summary> /// Actuals:This Year - Quantity /// </summary> public short? TY_QTY { get; internal set; } /// <summary> /// Actual Disposals:This Year - Quantity /// </summary> public short? TY_DISP_QTY { get; internal set; } /// <summary> /// Actuals:Open Bal - Proceeds on Disposal /// </summary> public decimal? OB_DISP_PROC { get; internal set; } /// <summary> /// Disposal price /// </summary> public decimal? TY_DISP_PROC { get; internal set; } /// <summary> /// Last stocktake date /// </summary> public DateTime? LAST_ST_DATE { get; internal set; } /// <summary> /// Last Date this asset was serviced /// </summary> public DateTime? LAST_SVC_DATE { get; internal set; } /// <summary> /// Date for next service /// </summary> public DateTime? NEXT_SVC_DATE { get; internal set; } /// <summary> /// Comments from last service /// [Memo] /// </summary> public string LAST_SVC_DETAILS { get; internal set; } /// <summary> /// Owner /// [Alphanumeric (30)] /// </summary> public string OWNER { get; internal set; } /// <summary> /// Expected life /// </summary> public short? EXPECTED_LIFE { get; internal set; } /// <summary> /// Warranty in months /// </summary> public short? WARRANTY { get; internal set; } /// <summary> /// Expiry date of warranty /// </summary> public DateTime? WARRANTYEXP { get; internal set; } /// <summary> /// Serial number/Reg. number /// [Alphanumeric (20)] /// </summary> public string SERIAL { get; internal set; } /// <summary> /// Cleaning memo /// [Memo] /// </summary> public string CLEANING { get; internal set; } /// <summary> /// Hazard memo /// [Memo] /// </summary> public string HAZARD { get; internal set; } /// <summary> /// Site reference /// [Alphanumeric (20)] /// </summary> public string SITE_REFERENCE { get; internal set; } /// <summary> /// Extra details /// [Memo] /// </summary> public string EXTRA_DETAILS { get; internal set; } /// <summary> /// Asset that this is a component of, or related to /// [Uppercase Alphanumeric (10)] /// </summary> public string COMPONENT_OF { get; internal set; } /// <summary> /// Picture of asset /// </summary> public byte[] ASSET_PIC { get; internal set; } /// <summary> /// Campus number /// </summary> public int? CAMPUS { get; internal set; } /// <summary> /// Fair market value for donated assets /// </summary> public decimal? FAIR_MARKET { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// AKC (Assets - Categories) related entity by [AR.CATEGORY]-&gt;[AKC.CATEGORY] /// Asset category /// </summary> public AKC CATEGORY_AKC { get { if (CATEGORY == null) { return null; } if (Cache_CATEGORY_AKC == null) { Cache_CATEGORY_AKC = Context.AKC.FindByCATEGORY(CATEGORY); } return Cache_CATEGORY_AKC; } } /// <summary> /// AKT (Asset Types) related entity by [AR.ASSET_TYPE]-&gt;[AKT.AKTKEY] /// Asset type /// </summary> public AKT ASSET_TYPE_AKT { get { if (ASSET_TYPE == null) { return null; } if (Cache_ASSET_TYPE_AKT == null) { Cache_ASSET_TYPE_AKT = Context.AKT.FindByAKTKEY(ASSET_TYPE); } return Cache_ASSET_TYPE_AKT; } } /// <summary> /// AKR (Asset Release Types) related entity by [AR.RELEASE_TYPE]-&gt;[AKR.AKRKEY] /// Asset Release Type /// </summary> public AKR RELEASE_TYPE_AKR { get { if (RELEASE_TYPE == null) { return null; } if (Cache_RELEASE_TYPE_AKR == null) { Cache_RELEASE_TYPE_AKR = Context.AKR.FindByAKRKEY(RELEASE_TYPE); } return Cache_RELEASE_TYPE_AKR; } } /// <summary> /// AKCT (Assets - Categories Tax) related entity by [AR.TAX_CATEGORY]-&gt;[AKCT.CATEGORY] /// Asset tax category /// </summary> public AKCT TAX_CATEGORY_AKCT { get { if (TAX_CATEGORY == null) { return null; } if (Cache_TAX_CATEGORY_AKCT == null) { Cache_TAX_CATEGORY_AKCT = Context.AKCT.FindByCATEGORY(TAX_CATEGORY); } return Cache_TAX_CATEGORY_AKCT; } } /// <summary> /// AKL (Assets - Locations) related entity by [AR.LOCATION]-&gt;[AKL.LOCATION] /// Asset locations /// </summary> public AKL LOCATION_AKL { get { if (LOCATION == null) { return null; } if (Cache_LOCATION_AKL == null) { Cache_LOCATION_AKL = Context.AKL.FindByLOCATION(LOCATION); } return Cache_LOCATION_AKL; } } /// <summary> /// AKD (Assets - Departments) related entity by [AR.DEPARTMENT]-&gt;[AKD.DEPARTMENT] /// Departments /// </summary> public AKD DEPARTMENT_AKD { get { if (DEPARTMENT == null) { return null; } if (Cache_DEPARTMENT_AKD == null) { Cache_DEPARTMENT_AKD = Context.AKD.FindByDEPARTMENT(DEPARTMENT); } return Cache_DEPARTMENT_AKD; } } /// <summary> /// AKB (Assets - Sub-Category) related entity by [AR.BRANCH]-&gt;[AKB.BRANCH] /// Sub Category /// </summary> public AKB BRANCH_AKB { get { if (BRANCH == null) { return null; } if (Cache_BRANCH_AKB == null) { Cache_BRANCH_AKB = Context.AKB.FindByBRANCH(BRANCH); } return Cache_BRANCH_AKB; } } /// <summary> /// CR (Accounts Payable) related entity by [AR.ORIG_SUPPLIER]-&gt;[CR.CRKEY] /// Supplier /// </summary> public CR ORIG_SUPPLIER_CR { get { if (ORIG_SUPPLIER == null) { return null; } if (Cache_ORIG_SUPPLIER_CR == null) { Cache_ORIG_SUPPLIER_CR = Context.CR.FindByCRKEY(ORIG_SUPPLIER); } return Cache_ORIG_SUPPLIER_CR; } } /// <summary> /// CR (Accounts Payable) related entity by [AR.CURR_SUPPLIER]-&gt;[CR.CRKEY] /// Default repairer /// </summary> public CR CURR_SUPPLIER_CR { get { if (CURR_SUPPLIER == null) { return null; } if (Cache_CURR_SUPPLIER_CR == null) { Cache_CURR_SUPPLIER_CR = Context.CR.FindByCRKEY(CURR_SUPPLIER); } return Cache_CURR_SUPPLIER_CR; } } /// <summary> /// GL (General Ledger) related entity by [AR.PTE_GLCODE]-&gt;[GL.CODE] /// GL acct where pte use % of depn will be posted /// </summary> public GL PTE_GLCODE_GL { get { if (PTE_GLCODE == null) { return null; } if (Cache_PTE_GLCODE_GL == null) { Cache_PTE_GLCODE_GL = Context.GL.FindByCODE(PTE_GLCODE); } return Cache_PTE_GLCODE_GL; } } /// <summary> /// KADM (Asset Depreciation Methods) related entity by [AR.AMETHOD]-&gt;[KADM.KADMKEY] /// method /// </summary> public KADM AMETHOD_KADM { get { if (AMETHOD == null) { return null; } if (Cache_AMETHOD_KADM == null) { Cache_AMETHOD_KADM = Context.KADM.FindByKADMKEY(AMETHOD); } return Cache_AMETHOD_KADM; } } /// <summary> /// KADM (Asset Depreciation Methods) related entity by [AR.TMETHOD]-&gt;[KADM.KADMKEY] /// Depreciation method /// </summary> public KADM TMETHOD_KADM { get { if (TMETHOD == null) { return null; } if (Cache_TMETHOD_KADM == null) { Cache_TMETHOD_KADM = Context.KADM.FindByKADMKEY(TMETHOD); } return Cache_TMETHOD_KADM; } } /// <summary> /// AR (Assets) related entity by [AR.COMPONENT_OF]-&gt;[AR.ARKEY] /// Asset that this is a component of, or related to /// </summary> public AR COMPONENT_OF_AR { get { if (COMPONENT_OF == null) { return null; } if (Cache_COMPONENT_OF_AR == null) { Cache_COMPONENT_OF_AR = Context.AR.FindByARKEY(COMPONENT_OF); } return Cache_COMPONENT_OF_AR; } } /// <summary> /// SCI (School Information) related entity by [AR.CAMPUS]-&gt;[SCI.SCIKEY] /// Campus number /// </summary> public SCI CAMPUS_SCI { get { if (CAMPUS == null) { return null; } if (Cache_CAMPUS_SCI == null) { Cache_CAMPUS_SCI = Context.SCI.FindBySCIKEY(CAMPUS.Value); } return Cache_CAMPUS_SCI; } } #endregion #region Foreign Navigation Properties /// <summary> /// AKK (Asset Key Holders) related entities by [AR.ARKEY]-&gt;[AKK.CODE] /// Prime Key /// </summary> public IReadOnlyList<AKK> ARKEY_AKK_CODE { get { if (Cache_ARKEY_AKK_CODE == null && !Context.AKK.TryFindByCODE(ARKEY, out Cache_ARKEY_AKK_CODE)) { Cache_ARKEY_AKK_CODE = new List<AKK>().AsReadOnly(); } return Cache_ARKEY_AKK_CODE; } } /// <summary> /// AR (Assets) related entities by [AR.ARKEY]-&gt;[AR.COMPONENT_OF] /// Prime Key /// </summary> public IReadOnlyList<AR> ARKEY_AR_COMPONENT_OF { get { if (Cache_ARKEY_AR_COMPONENT_OF == null && !Context.AR.TryFindByCOMPONENT_OF(ARKEY, out Cache_ARKEY_AR_COMPONENT_OF)) { Cache_ARKEY_AR_COMPONENT_OF = new List<AR>().AsReadOnly(); } return Cache_ARKEY_AR_COMPONENT_OF; } } /// <summary> /// ARF (Asset Financial Transactions) related entities by [AR.ARKEY]-&gt;[ARF.CODE] /// Prime Key /// </summary> public IReadOnlyList<ARF> ARKEY_ARF_CODE { get { if (Cache_ARKEY_ARF_CODE == null && !Context.ARF.TryFindByCODE(ARKEY, out Cache_ARKEY_ARF_CODE)) { Cache_ARKEY_ARF_CODE = new List<ARF>().AsReadOnly(); } return Cache_ARKEY_ARF_CODE; } } /// <summary> /// CRF (Creditor Financial Transaction) related entities by [AR.ARKEY]-&gt;[CRF.ATKEY] /// Prime Key /// </summary> public IReadOnlyList<CRF> ARKEY_CRF_ATKEY { get { if (Cache_ARKEY_CRF_ATKEY == null && !Context.CRF.TryFindByATKEY(ARKEY, out Cache_ARKEY_CRF_ATKEY)) { Cache_ARKEY_CRF_ATKEY = new List<CRF>().AsReadOnly(); } return Cache_ARKEY_CRF_ATKEY; } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Timers; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Encapsulate the asynchronous requests for the assets required for an archive operation /// </summary> class AssetsRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); enum RequestState { Initial, Running, Completed, Aborted }; /// <value> /// Timeout threshold if we still need assets or missing asset notifications but have stopped receiving them /// from the asset service /// </value> protected const int TIMEOUT = 60 * 1000; /// <value> /// If a timeout does occur, limit the amount of UUID information put to the console. /// </value> protected const int MAX_UUID_DISPLAY_ON_TIMEOUT = 3; protected System.Timers.Timer m_requestCallbackTimer; /// <value> /// State of this request /// </value> private RequestState m_requestState = RequestState.Initial; /// <value> /// uuids to request /// </value> protected ICollection<UUID> m_uuids; /// <value> /// Callback used when all the assets requested have been received. /// </value> protected AssetsRequestCallback m_assetsRequestCallback; /// <value> /// List of assets that were found. This will be passed back to the requester. /// </value> protected List<UUID> m_foundAssetUuids = new List<UUID>(); /// <value> /// Maintain a list of assets that could not be found. This will be passed back to the requester. /// </value> protected List<UUID> m_notFoundAssetUuids = new List<UUID>(); /// <value> /// Record the number of asset replies required so we know when we've finished /// </value> private int m_repliesRequired; /// <value> /// Asset service used to request the assets /// </value> protected IAssetService m_assetService; protected AssetsArchiver m_assetsArchiver; protected internal AssetsRequest( AssetsArchiver assetsArchiver, ICollection<UUID> uuids, IAssetService assetService, AssetsRequestCallback assetsRequestCallback) { m_assetsArchiver = assetsArchiver; m_uuids = uuids; m_assetsRequestCallback = assetsRequestCallback; m_assetService = assetService; m_repliesRequired = uuids.Count; m_requestCallbackTimer = new System.Timers.Timer(TIMEOUT); m_requestCallbackTimer.AutoReset = false; m_requestCallbackTimer.Elapsed += new ElapsedEventHandler(OnRequestCallbackTimeout); } protected internal void Execute() { m_requestState = RequestState.Running; m_log.DebugFormat("[ARCHIVER]: AssetsRequest executed looking for {0} assets", m_repliesRequired); // We can stop here if there are no assets to fetch if (m_repliesRequired == 0) { m_requestState = RequestState.Completed; PerformAssetsRequestCallback(); return; } foreach (UUID uuid in m_uuids) { m_assetService.Get(uuid.ToString(), this, AssetRequestCallback); } m_requestCallbackTimer.Enabled = true; } protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args) { try { lock (this) { // Take care of the possibilty that this thread started but was paused just outside the lock before // the final request came in (assuming that such a thing is possible) if (m_requestState == RequestState.Completed) return; m_requestState = RequestState.Aborted; } // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure // case anyway. List<UUID> uuids = new List<UUID>(); foreach (UUID uuid in m_uuids) { uuids.Add(uuid); } foreach (UUID uuid in m_foundAssetUuids) { uuids.Remove(uuid); } foreach (UUID uuid in m_notFoundAssetUuids) { uuids.Remove(uuid); } m_log.ErrorFormat( "[ARCHIVER]: Asset service failed to return information about {0} requested assets", uuids.Count); int i = 0; foreach (UUID uuid in uuids) { m_log.ErrorFormat("[ARCHIVER]: No information about asset {0} received", uuid); if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT) break; } if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT) m_log.ErrorFormat( "[ARCHIVER]: (... {0} more not shown)", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT); m_log.Error("[ARCHIVER]: OAR save aborted."); } catch (Exception e) { m_log.ErrorFormat("[ARCHIVER]: Timeout handler exception {0}", e); } finally { m_assetsArchiver.ForceClose(); } } /// <summary> /// Called back by the asset cache when it has the asset /// </summary> /// <param name="assetID"></param> /// <param name="asset"></param> public void AssetRequestCallback(string id, object sender, AssetBase asset) { try { lock (this) { //m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id); m_requestCallbackTimer.Stop(); if (m_requestState == RequestState.Aborted) { m_log.WarnFormat( "[ARCHIVER]: Received information about asset {0} after archive save abortion. Ignoring.", id); return; } if (asset != null) { // m_log.DebugFormat("[ARCHIVER]: Recording asset {0} as found", id); m_foundAssetUuids.Add(asset.FullID); m_assetsArchiver.WriteAsset(asset); } else { // m_log.DebugFormat("[ARCHIVER]: Recording asset {0} as not found", id); m_notFoundAssetUuids.Add(new UUID(id)); } if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count == m_repliesRequired) { m_requestState = RequestState.Completed; m_log.DebugFormat( "[ARCHIVER]: Successfully added {0} assets ({1} assets notified missing)", m_foundAssetUuids.Count, m_notFoundAssetUuids.Count); // We want to stop using the asset cache thread asap // as we now need to do the work of producing the rest of the archive Thread newThread = new Thread(PerformAssetsRequestCallback); newThread.Name = "OpenSimulator archiving thread post assets receipt"; newThread.Start(); } else { m_requestCallbackTimer.Start(); } } } catch (Exception e) { m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e); } } /// <summary> /// Perform the callback on the original requester of the assets /// </summary> protected void PerformAssetsRequestCallback() { try { m_assetsRequestCallback(m_foundAssetUuids, m_notFoundAssetUuids); } catch (Exception e) { m_log.ErrorFormat( "[ARCHIVER]: Terminating archive creation since asset requster callback failed with {0}", e); } } } }