context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using Microsoft.Xrm.Sdk; namespace PowerShellLibrary.Crm.CmdletProviders { [GeneratedCode("CrmSvcUtil", "7.1.0001.3108")] [DataContract] [Microsoft.Xrm.Sdk.Client.EntityLogicalName("plugintype")] public partial class PluginType : Entity, INotifyPropertyChanging, INotifyPropertyChanged { public const string EntityLogicalName = "plugintype"; public const int EntityTypeCode = 4602; [AttributeLogicalName("assemblyname")] public string AssemblyName { get { return this.GetAttributeValue<string>("assemblyname"); } } [AttributeLogicalName("componentstate")] public OptionSetValue ComponentState { get { return this.GetAttributeValue<OptionSetValue>("componentstate"); } } [AttributeLogicalName("createdby")] public EntityReference CreatedBy { get { return this.GetAttributeValue<EntityReference>("createdby"); } } [AttributeLogicalName("createdon")] public DateTime? CreatedOn { get { return this.GetAttributeValue<DateTime?>("createdon"); } } [AttributeLogicalName("createdonbehalfby")] public EntityReference CreatedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("createdonbehalfby"); } } [AttributeLogicalName("culture")] public string Culture { get { return this.GetAttributeValue<string>("culture"); } } [AttributeLogicalName("customizationlevel")] public int? CustomizationLevel { get { return this.GetAttributeValue<int?>("customizationlevel"); } } [AttributeLogicalName("customworkflowactivityinfo")] public string CustomWorkflowActivityInfo { get { return this.GetAttributeValue<string>("customworkflowactivityinfo"); } } [AttributeLogicalName("description")] public string Description { get { return this.GetAttributeValue<string>("description"); } set { this.OnPropertyChanging("Description"); this.SetAttributeValue("description", (object) value); this.OnPropertyChanged("Description"); } } [AttributeLogicalName("friendlyname")] public string FriendlyName { get { return this.GetAttributeValue<string>("friendlyname"); } set { this.OnPropertyChanging("FriendlyName"); this.SetAttributeValue("friendlyname", (object) value); this.OnPropertyChanged("FriendlyName"); } } [AttributeLogicalName("ismanaged")] public bool? IsManaged { get { return this.GetAttributeValue<bool?>("ismanaged"); } } [AttributeLogicalName("isworkflowactivity")] public bool? IsWorkflowActivity { get { return this.GetAttributeValue<bool?>("isworkflowactivity"); } } [AttributeLogicalName("major")] public int? Major { get { return this.GetAttributeValue<int?>("major"); } } [AttributeLogicalName("minor")] public int? Minor { get { return this.GetAttributeValue<int?>("minor"); } } [AttributeLogicalName("modifiedby")] public EntityReference ModifiedBy { get { return this.GetAttributeValue<EntityReference>("modifiedby"); } } [AttributeLogicalName("modifiedon")] public DateTime? ModifiedOn { get { return this.GetAttributeValue<DateTime?>("modifiedon"); } } [AttributeLogicalName("modifiedonbehalfby")] public EntityReference ModifiedOnBehalfBy { get { return this.GetAttributeValue<EntityReference>("modifiedonbehalfby"); } } [AttributeLogicalName("name")] public string Name { get { return this.GetAttributeValue<string>("name"); } set { this.OnPropertyChanging("Name"); this.SetAttributeValue("name", (object) value); this.OnPropertyChanged("Name"); } } [AttributeLogicalName("organizationid")] public EntityReference OrganizationId { get { return this.GetAttributeValue<EntityReference>("organizationid"); } } [AttributeLogicalName("overwritetime")] public DateTime? OverwriteTime { get { return this.GetAttributeValue<DateTime?>("overwritetime"); } } [AttributeLogicalName("pluginassemblyid")] public EntityReference PluginAssemblyId { get { return this.GetAttributeValue<EntityReference>("pluginassemblyid"); } set { this.OnPropertyChanging("PluginAssemblyId"); this.SetAttributeValue("pluginassemblyid", (object) value); this.OnPropertyChanged("PluginAssemblyId"); } } [AttributeLogicalName("plugintypeid")] public Guid? PluginTypeId { get { return this.GetAttributeValue<Guid?>("plugintypeid"); } set { this.OnPropertyChanging("PluginTypeId"); this.SetAttributeValue("plugintypeid", (object) value); if (value.HasValue) base.Id = value.Value; else base.Id = Guid.Empty; this.OnPropertyChanged("PluginTypeId"); } } [AttributeLogicalName("plugintypeid")] public override Guid Id { get { return base.Id; } set { this.PluginTypeId = new Guid?(value); } } [AttributeLogicalName("plugintypeidunique")] public Guid? PluginTypeIdUnique { get { return this.GetAttributeValue<Guid?>("plugintypeidunique"); } } [AttributeLogicalName("publickeytoken")] public string PublicKeyToken { get { return this.GetAttributeValue<string>("publickeytoken"); } } [AttributeLogicalName("solutionid")] public Guid? SolutionId { get { return this.GetAttributeValue<Guid?>("solutionid"); } } [AttributeLogicalName("typename")] public string TypeName { get { return this.GetAttributeValue<string>("typename"); } set { this.OnPropertyChanging("TypeName"); this.SetAttributeValue("typename", (object) value); this.OnPropertyChanged("TypeName"); } } [AttributeLogicalName("version")] public string Version { get { return this.GetAttributeValue<string>("version"); } } [AttributeLogicalName("versionnumber")] public long? VersionNumber { get { return this.GetAttributeValue<long?>("versionnumber"); } } [AttributeLogicalName("workflowactivitygroupname")] public string WorkflowActivityGroupName { get { return this.GetAttributeValue<string>("workflowactivitygroupname"); } set { this.OnPropertyChanging("WorkflowActivityGroupName"); this.SetAttributeValue("workflowactivitygroupname", (object) value); this.OnPropertyChanged("WorkflowActivityGroupName"); } } [RelationshipSchemaName("plugintype_plugintypestatistic")] public IEnumerable<PluginTypeStatistic> plugintype_plugintypestatistic { get { return this.GetRelatedEntities<PluginTypeStatistic>("plugintype_plugintypestatistic", new EntityRole?()); } set { this.OnPropertyChanging("plugintype_plugintypestatistic"); this.SetRelatedEntities<PluginTypeStatistic>("plugintype_plugintypestatistic", new EntityRole?(), value); this.OnPropertyChanged("plugintype_plugintypestatistic"); } } [RelationshipSchemaName("plugintype_sdkmessageprocessingstep")] public IEnumerable<SdkMessageProcessingStep> plugintype_sdkmessageprocessingstep { get { return this.GetRelatedEntities<SdkMessageProcessingStep>("plugintype_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("plugintype_sdkmessageprocessingstep"); this.SetRelatedEntities<SdkMessageProcessingStep>("plugintype_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("plugintype_sdkmessageprocessingstep"); } } [RelationshipSchemaName("plugintypeid_sdkmessageprocessingstep")] public IEnumerable<SdkMessageProcessingStep> plugintypeid_sdkmessageprocessingstep { get { return this.GetRelatedEntities<SdkMessageProcessingStep>("plugintypeid_sdkmessageprocessingstep", new EntityRole?()); } set { this.OnPropertyChanging("plugintypeid_sdkmessageprocessingstep"); this.SetRelatedEntities<SdkMessageProcessingStep>("plugintypeid_sdkmessageprocessingstep", new EntityRole?(), value); this.OnPropertyChanged("plugintypeid_sdkmessageprocessingstep"); } } [AttributeLogicalName("createdby")] [RelationshipSchemaName("createdby_plugintype")] public SystemUser createdby_plugintype { get { return this.GetRelatedEntity<SystemUser>("createdby_plugintype", new EntityRole?()); } } [RelationshipSchemaName("lk_plugintype_createdonbehalfby")] [AttributeLogicalName("createdonbehalfby")] public SystemUser lk_plugintype_createdonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_plugintype_createdonbehalfby", new EntityRole?()); } } [AttributeLogicalName("modifiedonbehalfby")] [RelationshipSchemaName("lk_plugintype_modifiedonbehalfby")] public SystemUser lk_plugintype_modifiedonbehalfby { get { return this.GetRelatedEntity<SystemUser>("lk_plugintype_modifiedonbehalfby", new EntityRole?()); } } [RelationshipSchemaName("modifiedby_plugintype")] [AttributeLogicalName("modifiedby")] public SystemUser modifiedby_plugintype { get { return this.GetRelatedEntity<SystemUser>("modifiedby_plugintype", new EntityRole?()); } } [AttributeLogicalName("pluginassemblyid")] [RelationshipSchemaName("pluginassembly_plugintype")] public PluginAssembly pluginassembly_plugintype { get { return this.GetRelatedEntity<PluginAssembly>("pluginassembly_plugintype", new EntityRole?()); } set { this.OnPropertyChanging("pluginassembly_plugintype"); this.SetRelatedEntity<PluginAssembly>("pluginassembly_plugintype", new EntityRole?(), value); this.OnPropertyChanged("pluginassembly_plugintype"); } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; public PluginType() : base("plugintype") { } private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged == null) return; this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName)); } private void OnPropertyChanging(string propertyName) { if (this.PropertyChanging == null) return; this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName)); } } }
// ------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All Rights Reserved. // ------------------------------------------------------------------- //From \\authoring\Sparkle\Source\1.0.1083.0\Common\Source\Framework\Properties namespace System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Framework.PropertyInspector { using System.Runtime; using System.ComponentModel; using System.Diagnostics; using System.Collections.Generic; using System.Collections.ObjectModel; using System; using System.Activities.Presentation.PropertyEditing; using System.Collections; using System.Windows.Media; using System.Windows; using System.Globalization; using System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Framework.Data; using System.Diagnostics.CodeAnalysis; [SuppressMessage(FxCop.Category.Naming, "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "Code imported from Cider; keeping changes to a minimum as it impacts xaml files as well")] internal abstract class CategoryBase : CategoryEntry, IEnumerable<PropertyEntry> { private static AlphabeticalCategoryEditorComparer alphabeticalCategoryEditorComparer = new AlphabeticalCategoryEditorComparer(); private bool basicPropertyMatchesFilter = true; private bool advancedPropertyMatchesFilter = true; private ObservableCollectionWorkaround<CategoryEditor> categoryEditors = new ObservableCollectionWorkaround<CategoryEditor>(); // Track the category editor that is currently providing the icon: private CategoryEditor iconProvider = null; private ImageSource categoryIcon = null; [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] protected CategoryBase(string name) : base(name) { this.categoryEditors.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(categoryEditors_CollectionChanged); this.InitializeIcons(); } public override IEnumerable<PropertyEntry> Properties { get { return this; } } public abstract ObservableCollection<PropertyEntry> BasicProperties { get; } public abstract ObservableCollection<PropertyEntry> AdvancedProperties { get; } public bool BasicPropertyMatchesFilter { get { return this.basicPropertyMatchesFilter; } set { if (this.basicPropertyMatchesFilter != value) { this.basicPropertyMatchesFilter = value; this.OnPropertyChanged("BasicPropertyMatchesFilter"); } } } public bool AdvancedPropertyMatchesFilter { get { return this.advancedPropertyMatchesFilter; } set { if (this.advancedPropertyMatchesFilter != value) { this.advancedPropertyMatchesFilter = value; this.OnPropertyChanged("AdvancedPropertyMatchesFilter"); } } } public virtual IComparable SortOrdering { get { return this.CategoryName; } } public ObservableCollection<CategoryEditor> CategoryEditors { get { return categoryEditors; } } public ImageSource CategoryIcon { get { return this.categoryIcon; } protected set { this.categoryIcon = value; this.OnPropertyChanged("CategoryIcon"); } } // IPropertyFilterTarget Members public override PropertyEntry this[string propertyName] { get { foreach (PropertyEntry property in this.Properties) { if (property.PropertyName == propertyName) { return property; } } return null; } } private void categoryEditors_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { this.InitializeIcons(); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Propagating the error might cause VS to crash")] [SuppressMessage("Reliability", "Reliability108", Justification = "Propagating the error might cause VS to crash")] private void InitializeIcons() { if (this.iconProvider == null || !this.categoryEditors.Contains(this.iconProvider)) { foreach (CategoryEditor editor in this.categoryEditors) { ImageSource icon = null; // CategoryEditor.GetImage is user code and could throw: try { // 24,24 is the desired default size for category icons; it may or may not be respected // by the implementation of GetImage icon = editor.GetImage(new Size(24, 24)) as ImageSource; } catch (Exception exception) { this.ReportCategoryException(string.Format(CultureInfo.CurrentCulture, ExceptionStringTable.CategoryIconLoadFailed, this.CategoryName, exception.Message)); continue; } if (icon != null) { if (icon is ISupportInitialize) { // Attempt to access some property on the image to ensure it has been initialized properly. Display the error now, instead of later in the artboard. try { double dummyHeight = icon.Height; } catch (InvalidOperationException exception) { this.ReportCategoryException(string.Format(CultureInfo.CurrentCulture, ExceptionStringTable.CategoryIconLoadFailed, this.CategoryName, exception.Message)); continue; } } this.CategoryIcon = icon; this.iconProvider = editor; return; } } this.CategoryIcon = null; this.iconProvider = null; } } public virtual void ReportCategoryException(string message) { } IEnumerator<PropertyEntry> IEnumerable<PropertyEntry>.GetEnumerator() { return new PropertyEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new PropertyEnumerator(this); } public void AddCategoryEditor(CategoryEditor categoryEditor) { int insertionIndex = this.categoryEditors.BinarySearch(categoryEditor, CategoryBase.alphabeticalCategoryEditorComparer); if (insertionIndex < 0) { insertionIndex = ~insertionIndex; } this.categoryEditors.Insert(insertionIndex, categoryEditor); } public void RemoveCategoryEditor(Type categoryEditor) { for (int i = 0; i < this.CategoryEditors.Count; i++) { if (this.CategoryEditors[i].GetType() == categoryEditor) { this.CategoryEditors.RemoveAt(i); return; } } } public override void ApplyFilter(PropertyFilter filter) { this.MatchesFilter = filter.Match(this); // Now Match all the properties in this category bool newBasicPropertyMatchesFilter = false; bool newAdvancedPropertyMatchesFilter = false; foreach (PropertyEntry property in this.BasicProperties) { if (this.DoesPropertyMatchFilter(filter, property)) { newBasicPropertyMatchesFilter = true; } } foreach (PropertyEntry property in this.AdvancedProperties) { if (this.DoesPropertyMatchFilter(filter, property)) { newAdvancedPropertyMatchesFilter = true; } } this.BasicPropertyMatchesFilter = newBasicPropertyMatchesFilter; this.AdvancedPropertyMatchesFilter = newAdvancedPropertyMatchesFilter; this.OnFilterApplied(filter); } public override bool MatchesPredicate(PropertyFilterPredicate predicate) { return predicate.Match(this.CategoryName); } protected virtual bool DoesPropertyMatchFilter(PropertyFilter filter, PropertyEntry property) { property.ApplyFilter(filter); return property.MatchesFilter; } private struct PropertyEnumerator : IEnumerator<PropertyEntry> { private CategoryBase category; private IEnumerator<PropertyEntry> current; private bool enumeratingBasic; public PropertyEnumerator(CategoryBase category) { this.category = category; this.current = null; this.enumeratingBasic = false; this.Reset(); } public PropertyEntry Current { get { return this.current.Current; } } object IEnumerator.Current { get { return this.Current; } } public bool MoveNext() { if (this.current.MoveNext()) { return true; } else { if (this.enumeratingBasic) { this.enumeratingBasic = false; this.current = this.category.AdvancedProperties.GetEnumerator(); return this.MoveNext(); } else { return false; } } } public void Reset() { this.current = category.BasicProperties.GetEnumerator(); this.enumeratingBasic = true; } void IDisposable.Dispose() { } } private class AlphabeticalCategoryEditorComparer : Comparer<CategoryEditor> { public override int Compare(CategoryEditor x, CategoryEditor y) { //return x.GetType().ToString().CompareTo(y.GetType().ToString()); //CompareTo uses currentCulture for string comparison return string.Compare(x.GetType().ToString(), y.GetType().ToString(), StringComparison.CurrentCulture); } } } }
// 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. // The RegexReplacement class represents a substitution string for // use when using regexes to search/replace, etc. It's logically // a sequence intermixed (1) constant strings and (2) group numbers. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace Flatbox.RegularExpressions { internal sealed class RegexReplacement { // Constants for special insertion patterns internal const int Specials = 4; internal const int LeftPortion = -1; internal const int RightPortion = -2; internal const int LastGroup = -3; internal const int WholeString = -4; private readonly string _rep; private readonly List<string> _strings; // table of string constants private readonly List<int> _rules; // negative -> group #, positive -> string # /// <summary> /// Since RegexReplacement shares the same parser as Regex, /// the constructor takes a RegexNode which is a concatenation /// of constant strings and backreferences. /// </summary> internal RegexReplacement(string rep, RegexNode concat, Hashtable _caps) { if (concat.Type() != RegexNode.Concatenate) throw new ArgumentException(""); StringBuilder sb = StringBuilderCache.Acquire(); List<string> strings = new List<string>(); List<int> rules = new List<int>(); for (int i = 0; i < concat.ChildCount(); i++) { RegexNode child = concat.Child(i); switch (child.Type()) { case RegexNode.Multi: sb.Append(child._str); break; case RegexNode.One: sb.Append(child._ch); break; case RegexNode.Ref: if (sb.Length > 0) { rules.Add(strings.Count); strings.Add(sb.ToString()); sb.Length = 0; } int slot = child._m; if (_caps != null && slot >= 0) slot = (int)_caps[slot]; rules.Add(-Specials - 1 - slot); break; default: throw new ArgumentException(""); } } if (sb.Length > 0) { rules.Add(strings.Count); strings.Add(sb.ToString()); } StringBuilderCache.Release(sb); _rep = rep; _strings = strings; _rules = rules; } /// <summary> /// Given a Match, emits into the StringBuilder the evaluated /// substitution pattern. /// </summary> private void ReplacementImpl(StringBuilder sb, Match match) { for (int i = 0; i < _rules.Count; i++) { int r = _rules[i]; if (r >= 0) // string lookup sb.Append(_strings[r]); else if (r < -Specials) // group lookup sb.Append(match.GroupToStringImpl(-Specials - 1 - r)); else { switch (-Specials - 1 - r) { // special insertion patterns case LeftPortion: sb.Append(match.GetLeftSubstring()); break; case RightPortion: sb.Append(match.GetRightSubstring()); break; case LastGroup: sb.Append(match.LastGroupToStringImpl()); break; case WholeString: sb.Append(match.GetOriginalString()); break; } } } } /// <summary> /// Given a Match, emits into the List<string> the evaluated /// Right-to-Left substitution pattern. /// </summary> private void ReplacementImplRTL(List<string> al, Match match) { for (int i = _rules.Count - 1; i >= 0; i--) { int r = _rules[i]; if (r >= 0) // string lookup al.Add(_strings[r]); else if (r < -Specials) // group lookup al.Add(match.GroupToStringImpl(-Specials - 1 - r)); else { switch (-Specials - 1 - r) { // special insertion patterns case LeftPortion: al.Add(match.GetLeftSubstring()); break; case RightPortion: al.Add(match.GetRightSubstring()); break; case LastGroup: al.Add(match.LastGroupToStringImpl()); break; case WholeString: al.Add(match.GetOriginalString()); break; } } } } /// <summary> /// The original pattern string /// </summary> internal string Pattern { get { return _rep; } } /// <summary> /// Returns the replacement result for a single match /// </summary> internal string Replacement(Match match) { StringBuilder sb = StringBuilderCache.Acquire(); ReplacementImpl(sb, match); return StringBuilderCache.GetStringAndRelease(sb); } // Three very similar algorithms appear below: replace (pattern), // replace (evaluator), and split. /// <summary> /// Replaces all occurrences of the regex in the string with the /// replacement pattern. /// /// Note that the special case of no matches is handled on its own: /// with no matches, the input string is returned unchanged. /// The right-to-left case is split out because StringBuilder /// doesn't handle right-to-left string building directly very well. /// </summary> internal string Replace(Regex regex, string input, int count, int startat) { if (count < -1) throw new ArgumentOutOfRangeException(nameof(count), ""); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), ""); if (count == 0) return input; Match match = regex.Match(input, startat); if (!match.Success) { return input; } else { StringBuilder sb = StringBuilderCache.Acquire(); if (!regex.RightToLeft) { int prevat = 0; do { if (match.Index != prevat) sb.Append(input, prevat, match.Index - prevat); prevat = match.Index + match.Length; ReplacementImpl(sb, match); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) sb.Append(input, prevat, input.Length - prevat); } else { List<string> al = new List<string>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; ReplacementImplRTL(al, match); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat > 0) sb.Append(input, 0, prevat); for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return StringBuilderCache.GetStringAndRelease(sb); } } /// <summary> /// Replaces all occurrences of the regex in the string with the /// replacement evaluator. /// /// Note that the special case of no matches is handled on its own: /// with no matches, the input string is returned unchanged. /// The right-to-left case is split out because StringBuilder /// doesn't handle right-to-left string building directly very well. /// </summary> internal static string Replace(MatchEvaluator evaluator, Regex regex, string input, int count, int startat) { if (evaluator == null) throw new ArgumentNullException(nameof(evaluator)); if (count < -1) throw new ArgumentOutOfRangeException(nameof(count), ""); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), ""); if (count == 0) return input; Match match = regex.Match(input, startat); if (!match.Success) { return input; } else { StringBuilder sb = StringBuilderCache.Acquire(); if (!regex.RightToLeft) { int prevat = 0; do { if (match.Index != prevat) sb.Append(input, prevat, match.Index - prevat); prevat = match.Index + match.Length; sb.Append(evaluator(match)); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) sb.Append(input, prevat, input.Length - prevat); } else { List<string> al = new List<string>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; al.Add(evaluator(match)); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat > 0) sb.Append(input, 0, prevat); for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return StringBuilderCache.GetStringAndRelease(sb); } } /// <summary> /// Does a split. In the right-to-left case we reorder the /// array to be forwards. /// </summary> internal static string[] Split(Regex regex, string input, int count, int startat) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), ""); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), ""); string[] result; if (count == 1) { result = new string[1]; result[0] = input; return result; } count -= 1; Match match = regex.Match(input, startat); if (!match.Success) { result = new string[1]; result[0] = input; return result; } else { List<string> al = new List<string>(); if (!regex.RightToLeft) { int prevat = 0; for (; ;) { al.Add(input.Substring(prevat, match.Index - prevat)); prevat = match.Index + match.Length; // add all matched capture groups to the list. for (int i = 1; i < match.Groups.Count; i++) { if (match.IsMatched(i)) al.Add(match.Groups[i].ToString()); } if (--count == 0) break; match = match.NextMatch(); if (!match.Success) break; } al.Add(input.Substring(prevat, input.Length - prevat)); } else { int prevat = input.Length; for (; ;) { al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; // add all matched capture groups to the list. for (int i = 1; i < match.Groups.Count; i++) { if (match.IsMatched(i)) al.Add(match.Groups[i].ToString()); } if (--count == 0) break; match = match.NextMatch(); if (!match.Success) break; } al.Add(input.Substring(0, prevat)); al.Reverse(0, al.Count); } return al.ToArray(); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: TextReader ** ** ** Purpose: Abstract base class for all Text-only Readers. ** Subclasses will include StreamReader & StringReader. ** ** ===========================================================*/ using System; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using System.Security.Permissions; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. [Serializable()] public abstract class TextReader : MarshalByRefObject, IDisposable { public static readonly TextReader Null = new NullTextReader(); protected TextReader() { } // Closes this TextReader and releases any system resources associated with the // TextReader. Following a call to Close, any operations on the TextReader // may raise exceptions. // // This default method is empty, but descendant classes can override the // method to provide the appropriate functionality. public virtual void Close() { Dispose( true ); GC.SuppressFinalize( this ); } public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } protected virtual void Dispose( bool disposing ) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // public virtual int Peek() { return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read( [In, Out] char[] buffer, int index, int count ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int n = 0; do { int ch = Read(); if(ch == -1) break; buffer[index + n++] = (char)ch; } while(n < count); return n; } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual String ReadToEnd() { char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder( 4096 ); while((len = Read( chars, 0, chars.Length )) != 0) { sb.Append( chars, 0, len ); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock( [In, Out] char[] buffer, int index, int count ) { int i, n = 0; do { n += (i = Read( buffer, index + n, count - n )); } while(i > 0 && n < count); return n; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual String ReadLine() { StringBuilder sb = new StringBuilder(); while(true) { int ch = Read(); if(ch == -1) break; if(ch == '\r' || ch == '\n') { if(ch == '\r' && Peek() == '\n') Read(); return sb.ToString(); } sb.Append( (char)ch ); } if(sb.Length > 0) return sb.ToString(); return null; } [HostProtection( Synchronization = true )] public static TextReader Synchronized( TextReader reader ) { if(reader == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "reader" ); #else throw new ArgumentNullException(); #endif } if(reader is SyncTextReader) { return reader; } return new SyncTextReader( reader ); } [Serializable()] private sealed class NullTextReader : TextReader { public override int Read( char[] buffer, int index, int count ) { return 0; } public override String ReadLine() { return null; } } [Serializable()] internal sealed class SyncTextReader : TextReader { internal TextReader _in; internal SyncTextReader( TextReader t ) { _in = t; } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override void Close() { // So that any overriden Close() gets run _in.Close(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] protected override void Dispose( bool disposing ) { // Explicitly pick up a potentially methodimpl'ed Dispose if(disposing) { ((IDisposable)_in).Dispose(); } } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int Peek() { return _in.Peek(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int Read() { return _in.Read(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int Read( [In, Out] char[] buffer, int index, int count ) { return _in.Read( buffer, index, count ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override int ReadBlock( [In, Out] char[] buffer, int index, int count ) { return _in.ReadBlock( buffer, index, count ); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override String ReadLine() { return _in.ReadLine(); } [MethodImplAttribute( MethodImplOptions.Synchronized )] public override String ReadToEnd() { return _in.ReadToEnd(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter; using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Threading; namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite { public partial class AppInstanceIdExtendedTest : SMB2TestBase { /// <summary> /// Boolean flag indicating whether LeaseBreak is received /// </summary> private bool isLeaseBreakReceived = false; #region Test Case [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.CombinedFeature)] [TestCategory(TestCategories.Positive)] [Description("Operate file with lease before client failover and expect no lease state is maintained after client failover.")] public void AppInstanceId_FileLeasing_NoLeaseInReOpen() { #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb30); TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_LEASING | NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES); TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_APP_INSTANCE_ID, CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2, CreateContextTypeValue.SMB2_CREATE_REQUEST_LEASE); #endregion AppInstanceIdTestWithLeasing( false, LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING | LeaseStateValues.SMB2_LEASE_WRITE_CACHING, AccessMask.GENERIC_READ | AccessMask.GENERIC_WRITE, AccessMask.GENERIC_WRITE); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.CombinedFeature)] [TestCategory(TestCategories.Positive)] [Description("Operate file with lease before client failover and expect no lease state is maintained after client failover.")] public void AppInstanceId_DirectoryLeasing_NoLeaseInReOpen() { #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb30); TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING | NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES); TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_APP_INSTANCE_ID, CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2, CreateContextTypeValue.SMB2_CREATE_REQUEST_LEASE_V2); #endregion AppInstanceIdTestWithLeasing( true, LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING, AccessMask.GENERIC_READ, AccessMask.DELETE); } #endregion #region Common Method /// <summary> /// Test AppInstanceId with leasing /// </summary> /// <param name="isDirectory">Set true if test lease on directory, otherwise set false</param> /// <param name="requestedLeaseState">Lease state that client will request</param> /// <param name="accessMask">Access mask that client is used to access file/directory</param> /// <param name="accessMaskToTriggerBreak">Access mask that a separate client is used to access file/directory to trigger LeaseBreak</param> private void AppInstanceIdTestWithLeasing(bool isDirectory, LeaseStateValues requestedLeaseState, AccessMask accessMask, AccessMask accessMaskToTriggerBreak) { testDirectory = CreateTestDirectory(uncSharePath); #region InitialOpen: Connect to server via Nic1 and create an open with AppInstanceId and leasing BaseTestSite.Log.Add( LogEntryKind.TestStep, "InitialOpen: Connect to share via Nic1."); FILEID fileIdForInitialOpen; uint treeIdForInitialOpen; ConnectShare(TestConfig.SutIPAddress, TestConfig.ClientNic1IPAddress, clientForInitialOpen, out treeIdForInitialOpen); #region Create an open with AppInstanceId and leasing BaseTestSite.Log.Add(LogEntryKind.TestStep, "InitialOpen: Create an open with AppInstanceId and leasing."); appInstanceId = Guid.NewGuid(); Smb2CreateContextResponse[] serverCreateContexts; status = clientForInitialOpen.Create( treeIdForInitialOpen, isDirectory ? testDirectory : fileName, isDirectory ? CreateOptions_Values.FILE_DIRECTORY_FILE : CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileIdForInitialOpen, out serverCreateContexts, RequestedOplockLevel_Values.OPLOCK_LEVEL_LEASE, new Smb2CreateContextRequest[] { new Smb2CreateDurableHandleRequestV2 { CreateGuid = Guid.NewGuid(), }, new Smb2CreateRequestLeaseV2 { LeaseKey = Guid.NewGuid(), LeaseState = requestedLeaseState, }, new Smb2CreateAppInstanceId { AppInstanceId = appInstanceId } }, accessMask: accessMask, shareAccess: ShareAccess_Values.FILE_SHARE_READ | ShareAccess_Values.FILE_SHARE_WRITE); #endregion if (!isDirectory) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "InitialOpen: Write contents to file."); status = clientForInitialOpen.Write(treeIdForInitialOpen, fileIdForInitialOpen, contentWrite); } #endregion #region ReOpen: Connect to server via Nic2 and create an open with same AppInstanceId but without leasing BaseTestSite.Log.Add( LogEntryKind.TestStep, "ReOpen: Connect to same share via Nic2."); FILEID fileIdForReOpen; uint treeIdForReOpen; clientForReOpen.Smb2Client.LeaseBreakNotificationReceived += new Action<Packet_Header, LEASE_BREAK_Notification_Packet>(this.OnLeaseBreakNotificationReceived); ConnectShare(TestConfig.SutIPAddress, TestConfig.ClientNic2IPAddress, clientForReOpen, out treeIdForReOpen); #region Create an open with AppInstanceId but without leasing BaseTestSite.Log.Add(LogEntryKind.TestStep, "ReOpen: Create an open with AppInstanceId but without leasing."); status = clientForReOpen.Create( treeIdForReOpen, isDirectory ? testDirectory : fileName, isDirectory ? CreateOptions_Values.FILE_DIRECTORY_FILE : CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileIdForReOpen, out serverCreateContexts, RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE, new Smb2CreateContextRequest[] { new Smb2CreateDurableHandleRequestV2 { CreateGuid = Guid.NewGuid(), }, new Smb2CreateAppInstanceId { // Use the same application instance id to force the server close all files // And will clear previous lease AppInstanceId = appInstanceId } }, accessMask: AccessMask.GENERIC_READ); #endregion if (!isDirectory) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "ReOpen: Read the contents written by InitialOpen."); status = clientForReOpen.Read(treeIdForReOpen, fileIdForReOpen, 0, (uint)contentWrite.Length, out contentRead); BaseTestSite.Assert.IsTrue( contentRead.Equals(contentWrite), "The written content should equal to read content."); } #endregion #region ReOpen: Access same file/directory from a separate client and expect SUCCESS if (!isDirectory) { Smb2FunctionalClient separateClient = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client3: Connect to same server."); separateClient.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress, TestConfig.ClientNic2IPAddress); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client3: Trigger a Lease Break."); TriggerBreakFromClient(separateClient, TestConfig.RequestDialects, isDirectory, LeaseStateValues.SMB2_LEASE_NONE, accessMaskToTriggerBreak); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client3: Disconnect from the server."); separateClient.Disconnect(); } else { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client3: Attempt to create an empty file to trigger lease break."); sutProtocolController.CreateFile(Path.Combine(Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare), testDirectory), CurrentTestCaseName, string.Empty); } Thread.Sleep(500); BaseTestSite.Assert.AreNotEqual( true, isLeaseBreakReceived, "No LeaseBreak is expected to be received"); #endregion #region Client tear down BaseTestSite.Log.Add(LogEntryKind.TestStep, "ReOpen: Close file."); status = clientForReOpen.Close(treeIdForReOpen, fileIdForReOpen); BaseTestSite.Log.Add(LogEntryKind.TestStep, "ReOpen: Disconnect from the share."); status = clientForReOpen.TreeDisconnect(treeIdForReOpen); BaseTestSite.Log.Add(LogEntryKind.TestStep, "ReOpen: Log Off."); status = clientForReOpen.LogOff(); #endregion } /// <summary> /// Trigger LeaseBreak from a separate client /// </summary> /// <param name="client">Smb2FunctionalClient object that attempt to access file/directory to trigger lease break</param> /// <param name="requestDialect">Dialect in request</param> /// <param name="isDirectory">Set true if access a directory, otherwise set false</param> /// <param name="requestedLeaseState">Lease state that client will request</param> /// <param name="accessMask">Access mask that client is used to access file/directory</param> private void TriggerBreakFromClient( Smb2FunctionalClient client, DialectRevision[] requestDialect, bool isDirectory, LeaseStateValues requestedLeaseState, AccessMask accessMask) { BaseTestSite.Log.Add( LogEntryKind.Debug, "Below steps will trigger a lease break by accessing same file/directory from a separate client with LeaseState {0} and AccessMask {1}", requestedLeaseState, accessMask); #region Negotiate status = client.Negotiate( requestDialect, TestConfig.IsSMB1NegotiateEnabled, capabilityValue: Capabilities_Values.GLOBAL_CAP_DFS | Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING | Capabilities_Values.GLOBAL_CAP_LARGE_MTU | Capabilities_Values.GLOBAL_CAP_LEASING | Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL | Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES); #endregion #region SESSION_SETUP status = client.SessionSetup( TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, TestConfig.UseServerGssToken); #endregion #region TREE_CONNECT to share uint treeId; status = client.TreeConnect(uncSharePath, out treeId); #endregion #region CREATE FILEID fileId; Smb2CreateContextResponse[] serverCreateContexts; status = client.Create( treeId, isDirectory ? testDirectory : fileName, isDirectory ? CreateOptions_Values.FILE_DIRECTORY_FILE : CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out serverCreateContexts, RequestedOplockLevel_Values.OPLOCK_LEVEL_LEASE, new Smb2CreateContextRequest[] { new Smb2CreateRequestLeaseV2 { LeaseKey = Guid.NewGuid(), LeaseState = requestedLeaseState } }, accessMask: accessMask); #endregion status = client.Close(treeId, fileId); BaseTestSite.Log.Add( LogEntryKind.Debug, "Finish triggering lease break."); } protected override void OnLeaseBreakNotificationReceived(Packet_Header respHeader, LEASE_BREAK_Notification_Packet leaseBreakNotify) { BaseTestSite.Log.Add(LogEntryKind.Debug, "LeaseBreakNotification was received from server"); isLeaseBreakReceived = true; } #endregion } }
using System; using System.Xml; namespace nexposesharp { public class NexposeManager11 : IDisposable { private NexposeSession _session; public NexposeManager11 (NexposeSession session) { if (!session.IsAuthenticated) throw new Exception("Trying to create manager from unauthenticated session. Please authenticate."); _session = session; } public void Dispose() { _session.Logout(); } public XmlDocument GetSiteListing() { string cmd = "<SiteListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetSiteConfig(string siteID) { string cmd = "<SiteConfigRequest session-id=\"" + _session.SessionID + "\" site-id=\"" + siteID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument SaveOrUpdateSite(XmlNode site) { string cmd = "<SiteSaveRequest session-id=\"" + _session.SessionID + "\" >"; cmd = cmd + site.OuterXml; cmd = cmd + "</SiteSaveRequest>"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument DeleteSite(string siteID) { string cmd = "<SiteDeleteRequest session-id=\"" + _session.SessionID + "\" site-id=\"" + siteID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument ScanSite(string siteID) { string cmd = "<SiteScanRequest session-id=\"" + _session.SessionID + "\" site-id=\"" + siteID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetSiteScanHistory(string siteID) { string cmd = "<SiteScanHistoryRequest session-id=\"" + _session.SessionID + "\" site-id=\"" + siteID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetSiteDeviceListing(string siteID) { string cmd = "<SiteDeviceListingRequest session-id=\"" + _session.SessionID + "\" site-id=\"" + siteID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } // public XmlDocument ScanSiteDevices(XmlNode devices) // { //// string response = new XmlDocument(); //// //// XmlDocument doc = new XmlDocument(); //// doc.LoadXml(response); //// //// return doc; // } public XmlDocument DeleteDevice(string deviceID) { string cmd = "<DeviceDeleteRequest session-id=\"" + _session.SessionID + "\" device-id=\"" + deviceID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetAssetGroupListing() { string cmd = "<AssetGroupListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetAssetGroupConfig(string assetGroupID) { string cmd = "<AssetGroupConfigRequest session-id=\"" + _session.SessionID + "\" group-id=\"" + assetGroupID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument SaveOrUpdateAssetGroup(XmlNode assetGroup) { string cmd = "<AssetGroupSaveRequest session-id=\"" +_session.SessionID + "\">"; cmd = cmd + assetGroup.OuterXml; cmd = cmd + "</AssetGroupSaveRequest>"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument DeleteAssetGroup(string groupID) { string cmd = "<AssetGroupDeleteRequest session-id=\"" + _session.SessionID + "\" group-id=\"" + groupID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetScanEngineListing() { string cmd = "<EngineListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetScanEngineActivity(string engineID) { string cmd = "<EngineActivityRequest session-id=\"" + _session.SessionID + "\" engine-id=\"" + engineID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetAllScanActivities() { string cmd = "<ScanActivityRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument PauseScan(string scanID) { string cmd = "<ScanPauseRequest session-id=\"" + _session.SessionID + "\" scan-id=\"" + scanID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument ResumeScan(string scanID) { string cmd = "<ScanResumeRequest session-id=\"" + _session.SessionID + "\" scan-id=\"" + scanID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument StopScan(string scanID) { string cmd = "<ScanStopRequest session-id=\"" + _session.SessionID + "\" scan-id=\"" + scanID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetScanStatus(string scanID) { string cmd = "<ScanStatusRequest session-id=\"" + _session.SessionID + "\" scan-id=\"" + scanID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetScanStatistics(string scanID) { string cmd = "<ScanStatisticsRequest session-id=\"" + _session.SessionID + "\" scan-id=\"" + scanID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetVulnerabilityListing() { string cmd = "<VulnerabilityListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetVulnerabilityDetails(string vulnerabilityID) { string cmd = "<VulnerabilityDetailsRequest session-id=\"" + _session.SessionID + "\" vuln-id=\"" + vulnerabilityID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetReportTemplateListing() { string cmd = "<ReportListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetReportTemplateConfig(string reportTemplateID) { string cmd = "<ReportTemplateConfigRequest session-id=\"" + _session.SessionID + "\" template-id=\"" + reportTemplateID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument SaveOrUpdateReportTemplate(XmlNode reportTemplate) { string cmd = "<ReportTemplateSaveRequest session-id=\"" + _session.SessionID + "\">"; cmd = cmd + reportTemplate.OuterXml; cmd = cmd + "</ReportTemplateSaveRequest>"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetReportListing() { string cmd = "<ReportListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetReportHistory(string reportConfigID) { string cmd = "<ReportHistoryRequest session-id=\"" + _session.SessionID + "\" report-id=\"" + reportConfigID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetReportConfig(string reportConfigID) { string cmd = "<ReportConfigRequest session-id=\"" + _session.SessionID + "\" reportcfg-id=\"" + reportConfigID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument SaveOrUpdateReport(XmlNode report, bool generateNow) { string cmd = "<ReportSaveRequest session-id=\"" + _session.SessionID + "\" generate-now=\"" + (generateNow ? "1" : "0") + "\" >"; cmd = cmd + report.OuterXml; cmd = cmd + "</ReportSaveRequest>"; return _session.ExecuteCommand(cmd) as XmlDocument; } public byte[] GenerateReport(string reportID) { string cmd = "<ReportGenerateRequest session-id=\"" + _session.SessionID + "\" report-id=\"" + reportID + "\" />"; return _session.ExecuteCommand(cmd) as byte[]; } public XmlDocument DeleteReport(string reportID) { string cmd = "<DeleteReportRequest session-id=\"" + _session.SessionID + "\" report-id=\"" + reportID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public byte[] GenerateAdHocReport(XmlNode adHocReportConfig) { string cmd = "<ReportAdhocGenerateRequest session-id=\"" + _session.SessionID + "\" >"; cmd = cmd + adHocReportConfig.OuterXml; cmd = cmd + "</ReportAdhocGenerateRequest>"; byte[] response = _session.ExecuteCommand(cmd) as byte[]; return response; } public XmlDocument GetUserListing() { string cmd = "<UserListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetUserAuthenticatorListing() { string cmd = "<UserAuthenticatorListingRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetUserConfig(string userID) { string cmd = "<UserConfigRequest session-id=\"" + _session.SessionID + "\" id=\"" + userID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument SaveOrUpdateUser(XmlNode user) { string cmd = "<UserSaveRequest session-id=\"" + _session.SessionID + "\" >"; cmd = cmd + user.OuterXml; cmd = cmd + "</UserSaveRequest>"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument DeleteUser(string userID) { string cmd = "<UserDeleteRequest session-id=\"" + _session.SessionID + "\" id=\"" + userID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument ExecuteConsoleCommand(XmlNode command) { string cmd = "<ConsoleCommandRequest session-id=\"" + _session.SessionID + "\" >"; cmd = cmd + command.OuterXml; cmd = "</ConsoleCommandRequest>"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument GetSystemInformation() { string cmd = "<SystemInformationRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument StartUpdate() { string cmd = "<StartUpdateRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument Restart() { string cmd = "<RestartRequest session-id=\"" + _session.SessionID + "\" />"; return _session.ExecuteCommand(cmd) as XmlDocument; } public XmlDocument SendLog(XmlNode transport) { string cmd = "<SendLogRequest session-id=\"" + _session.SessionID + "\" >"; cmd = cmd + transport.OuterXml; cmd = cmd + "</SendLogRequest>"; return _session.ExecuteCommand(cmd) as XmlDocument; } } }
/* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * 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 org.javarosa.xpath.expr; using System; using System.Collections; namespace org.javarosa.xpath.parser { public class Lexer { public const int LEX_CONTEXT_VAL = 1; public const int LEX_CONTEXT_OP = 2; public static ArrayList lex(String expr) { ArrayList tokens = new ArrayList(); int i = 0; int context = LEX_CONTEXT_VAL; while (i < expr.Length) { int c = expr[i]; int d = getChar(expr, i + 1); Token token = null; int skip = 1; /*if (" \n\t\f\r".IndexOf(c) >= 0) { /* whitespace; do nothing } else */ if (c == '=') { token = new Token(Token.EQ); } else if (c == '!' && d == '=') { token = new Token(Token.NEQ); skip = 2; } else if (c == '<') { if (d == '=') { token = new Token(Token.LTE); skip = 2; } else { token = new Token(Token.LT); } } else if (c == '>') { if (d == '=') { token = new Token(Token.GTE); skip = 2; } else { token = new Token(Token.GT); } } else if (c == '+') { token = new Token(Token.PLUS); } else if (c == '-') { token = new Token(context == LEX_CONTEXT_VAL ? Token.UMINUS : Token.MINUS); //not sure this is entirely correct } else if (c == '*') { token = new Token(context == LEX_CONTEXT_VAL ? Token.WILDCARD : Token.MULT); } else if (c == '|') { token = new Token(Token.UNION); } else if (c == '/') { if (d == '/') { token = new Token(Token.DBL_SLASH); skip = 2; } else { token = new Token(Token.SLASH); } } else if (c == '[') { token = new Token(Token.LBRACK); } else if (c == ']') { token = new Token(Token.RBRACK); } else if (c == '(') { token = new Token(Token.LPAREN); } else if (c == ')') { token = new Token(Token.RPAREN); } else if (c == '.') { if (d == '.') { token = new Token(Token.DBL_DOT); skip = 2; } else if (isDigit(d)) { skip = matchNumeric(expr, i); token = new Token(Token.NUM, Convert.ToDouble(expr.Substring(i, i + skip))); } else { token = new Token(Token.DOT); } } else if (c == '@') { token = new Token(Token.AT); } else if (c == ',') { token = new Token(Token.COMMA); } else if (c == ':' && d == ':') { token = new Token(Token.DBL_COLON); skip = 2; } else if (context == LEX_CONTEXT_OP && i + 3 <= expr.Length && "and".Equals(expr.Substring(i, i + 3))) { token = new Token(Token.AND); skip = 3; } else if (context == LEX_CONTEXT_OP && i + 2 <= expr.Length && "or".Equals(expr.Substring(i, i + 2))) { token = new Token(Token.OR); skip = 2; } else if (context == LEX_CONTEXT_OP && i + 3 <= expr.Length && "div".Equals(expr.Substring(i, i + 3))) { token = new Token(Token.DIV); skip = 3; } else if (context == LEX_CONTEXT_OP && i + 3 <= expr.Length && "mod".Equals(expr.Substring(i, i + 3))) { token = new Token(Token.MOD); skip = 3; } else if (c == '$') { int len = matchQName(expr, i + 1); if (len == 0) { throw new XPathSyntaxException(); } else { token = new Token(Token.VAR, new XPathQName(expr.Substring(i + 1, i + len + 1))); skip = len + 1; } } else if (c == '\'' || c == '\"') { int end = expr.IndexOf(c.ToString(), i + 1); if (end == -1) { throw new XPathSyntaxException(); } else { token = new Token(Token.STR, expr.Substring(i + 1, end)); skip = (end - i) + 1; } } else if (isDigit(c)) { skip = matchNumeric(expr, i); token = new Token(Token.NUM, Convert.ToDouble(expr.Substring(i, i + skip))); } else if (context == LEX_CONTEXT_VAL && (isAlpha(c) || c == '_')) { int len = matchQName(expr, i); String name = expr.Substring(i, i + len); if (name.IndexOf(':') == -1 && getChar(expr, i + len) == ':' && getChar(expr, i + len + 1) == '*') { token = new Token(Token.NSWILDCARD, name); skip = len + 2; } else { token = new Token(Token.QNAME, new XPathQName(name)); skip = len; } } else { throw new XPathSyntaxException(); } if (token != null) { if (token.type == Token.WILDCARD || token.type == Token.NSWILDCARD || token.type == Token.QNAME || token.type == Token.VAR || token.type == Token.NUM || token.type == Token.STR || token.type == Token.RBRACK || token.type == Token.RPAREN || token.type == Token.DOT || token.type == Token.DBL_DOT) { context = LEX_CONTEXT_OP; } else { context = LEX_CONTEXT_VAL; } tokens.Add(token); } i += skip; } return tokens; } private static int matchNumeric(String expr, int i) { Boolean seenDecimalPoint = false; int start = i; int c; for (; i < expr.Length; i++) { c = expr[i]; if (!(isDigit(c) || (!seenDecimalPoint && c == '.'))) break; if (c == '.') seenDecimalPoint = true; } return i - start; } private static int matchQName(String expr, int i) { int len = matchNCName(expr, i); if (len > 0 && getChar(expr, i + len) == ':') { int len2 = matchNCName(expr, i + len + 1); if (len2 > 0) len += len2 + 1; } return len; } private static int matchNCName(String expr, int i) { int start = i; int c; for (; i < expr.Length; i++) { c = expr[i]; if (!(isAlpha(c) || c == '_' || (i > start && (isDigit(c) || c == '.' || c == '-')))) break; } return i - start; } //get char from string, return -1 for EOF private static int getChar(String expr, int i) { return (i < expr.Length ? expr[i] : -1); } private static Boolean isDigit(int c) { return (c < 0 ? false : Char.IsDigit((char)c)); } private static Boolean isAlpha(int c) { return (c < 0 ? false : Char.IsLower((char)c) || Char.IsUpper((char)c)); } } }
#region Apache License // // 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; using System.IO; using System.Text; using System.Threading; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { #if !NETCF /// <summary> /// Appends logging events to a file. /// </summary> /// <remarks> /// <para> /// Logging events are sent to the file specified by /// the <see cref="File"/> property. /// </para> /// <para> /// The file can be opened in either append or overwrite mode /// by specifying the <see cref="AppendToFile"/> property. /// If the file path is relative it is taken as relative from /// the application base directory. The file encoding can be /// specified by setting the <see cref="Encoding"/> property. /// </para> /// <para> /// The layout's <see cref="ILayout.Header"/> and <see cref="ILayout.Footer"/> /// values will be written each time the file is opened and closed /// respectively. If the <see cref="AppendToFile"/> property is <see langword="true"/> /// then the file may contain multiple copies of the header and footer. /// </para> /// <para> /// This appender will first try to open the file for writing when <see cref="ActivateOptions"/> /// is called. This will typically be during configuration. /// If the file cannot be opened for writing the appender will attempt /// to open the file again each time a message is logged to the appender. /// If the file cannot be opened for writing when a message is logged then /// the message will be discarded by this appender. /// </para> /// <para> /// The <see cref="FileAppender"/> supports pluggable file locking models via /// the <see cref="LockingModel"/> property. /// The default behavior, implemented by <see cref="FileAppender.ExclusiveLock"/> /// is to obtain an exclusive write lock on the file until this appender is closed. /// The alternative models only hold a /// write lock while the appender is writing a logging event (<see cref="FileAppender.MinimalLock"/>) /// or synchronize by using a named system wide Mutex (<see cref="FileAppender.InterProcessLock"/>). /// </para> /// <para> /// All locking strategies have issues and you should seriously consider using a different strategy that /// avoids having multiple processes logging to the same file. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Rodrigo B. de Oliveira</author> /// <author>Douglas de la Torre</author> /// <author>Niall Daley</author> #else /// <summary> /// Appends logging events to a file. /// </summary> /// <remarks> /// <para> /// Logging events are sent to the file specified by /// the <see cref="File"/> property. /// </para> /// <para> /// The file can be opened in either append or overwrite mode /// by specifying the <see cref="AppendToFile"/> property. /// If the file path is relative it is taken as relative from /// the application base directory. The file encoding can be /// specified by setting the <see cref="Encoding"/> property. /// </para> /// <para> /// The layout's <see cref="ILayout.Header"/> and <see cref="ILayout.Footer"/> /// values will be written each time the file is opened and closed /// respectively. If the <see cref="AppendToFile"/> property is <see langword="true"/> /// then the file may contain multiple copies of the header and footer. /// </para> /// <para> /// This appender will first try to open the file for writing when <see cref="ActivateOptions"/> /// is called. This will typically be during configuration. /// If the file cannot be opened for writing the appender will attempt /// to open the file again each time a message is logged to the appender. /// If the file cannot be opened for writing when a message is logged then /// the message will be discarded by this appender. /// </para> /// <para> /// The <see cref="FileAppender"/> supports pluggable file locking models via /// the <see cref="LockingModel"/> property. /// The default behavior, implemented by <see cref="FileAppender.ExclusiveLock"/> /// is to obtain an exclusive write lock on the file until this appender is closed. /// The alternative model only holds a /// write lock while the appender is writing a logging event (<see cref="FileAppender.MinimalLock"/>). /// </para> /// <para> /// All locking strategies have issues and you should seriously consider using a different strategy that /// avoids having multiple processes logging to the same file. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Rodrigo B. de Oliveira</author> /// <author>Douglas de la Torre</author> /// <author>Niall Daley</author> #endif public class FileAppender : TextWriterAppender { #region LockingStream Inner Class /// <summary> /// Write only <see cref="Stream"/> that uses the <see cref="LockingModelBase"/> /// to manage access to an underlying resource. /// </summary> private sealed class LockingStream : Stream, IDisposable { public sealed class LockStateException : LogException { public LockStateException(string message): base(message) { } } private Stream m_realStream=null; private LockingModelBase m_lockingModel=null; private int m_readTotal=-1; private int m_lockLevel=0; public LockingStream(LockingModelBase locking) : base() { if (locking==null) { throw new ArgumentException("Locking model may not be null","locking"); } m_lockingModel=locking; } #region Override Implementation of Stream // Methods public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { AssertLocked(); IAsyncResult ret=m_realStream.BeginRead(buffer,offset,count,callback,state); m_readTotal=EndRead(ret); return ret; } /// <summary> /// True asynchronous writes are not supported, the implementation forces a synchronous write. /// </summary> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { AssertLocked(); IAsyncResult ret=m_realStream.BeginWrite(buffer,offset,count,callback,state); EndWrite(ret); return ret; } public override void Close() { m_lockingModel.CloseFile(); } public override int EndRead(IAsyncResult asyncResult) { AssertLocked(); return m_readTotal; } public override void EndWrite(IAsyncResult asyncResult) { //No-op, it has already been handled } public override void Flush() { AssertLocked(); m_realStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { return m_realStream.Read(buffer,offset,count); } public override int ReadByte() { return m_realStream.ReadByte(); } public override long Seek(long offset, SeekOrigin origin) { AssertLocked(); return m_realStream.Seek(offset,origin); } public override void SetLength(long value) { AssertLocked(); m_realStream.SetLength(value); } void IDisposable.Dispose() { Close(); } public override void Write(byte[] buffer, int offset, int count) { AssertLocked(); m_realStream.Write(buffer,offset,count); } public override void WriteByte(byte value) { AssertLocked(); m_realStream.WriteByte(value); } // Properties public override bool CanRead { get { return false; } } public override bool CanSeek { get { AssertLocked(); return m_realStream.CanSeek; } } public override bool CanWrite { get { AssertLocked(); return m_realStream.CanWrite; } } public override long Length { get { AssertLocked(); return m_realStream.Length; } } public override long Position { get { AssertLocked(); return m_realStream.Position; } set { AssertLocked(); m_realStream.Position=value; } } #endregion Override Implementation of Stream #region Locking Methods private void AssertLocked() { if (m_realStream == null) { throw new LockStateException("The file is not currently locked"); } } public bool AcquireLock() { bool ret=false; lock(this) { if (m_lockLevel==0) { // If lock is already acquired, nop m_realStream=m_lockingModel.AcquireLock(); } if (m_realStream!=null) { m_lockLevel++; ret=true; } } return ret; } public void ReleaseLock() { lock(this) { m_lockLevel--; if (m_lockLevel==0) { // If already unlocked, nop m_lockingModel.ReleaseLock(); m_realStream=null; } } } #endregion Locking Methods } #endregion LockingStream Inner Class #region Locking Models /// <summary> /// Locking model base class /// </summary> /// <remarks> /// <para> /// Base class for the locking models available to the <see cref="FileAppender"/> derived loggers. /// </para> /// </remarks> public abstract class LockingModelBase { private FileAppender m_appender=null; /// <summary> /// Open the output file /// </summary> /// <param name="filename">The filename to use</param> /// <param name="append">Whether to append to the file, or overwrite</param> /// <param name="encoding">The encoding to use</param> /// <remarks> /// <para> /// Open the file specified and prepare for logging. /// No writes will be made until <see cref="AcquireLock"/> is called. /// Must be called before any calls to <see cref="AcquireLock"/>, /// <see cref="ReleaseLock"/> and <see cref="CloseFile"/>. /// </para> /// </remarks> public abstract void OpenFile(string filename, bool append,Encoding encoding); /// <summary> /// Close the file /// </summary> /// <remarks> /// <para> /// Close the file. No further writes will be made. /// </para> /// </remarks> public abstract void CloseFile(); /// <summary> /// Acquire the lock on the file /// </summary> /// <returns>A stream that is ready to be written to.</returns> /// <remarks> /// <para> /// Acquire the lock on the file in preparation for writing to it. /// Return a stream pointing to the file. <see cref="ReleaseLock"/> /// must be called to release the lock on the output file. /// </para> /// </remarks> public abstract Stream AcquireLock(); /// <summary> /// Release the lock on the file /// </summary> /// <remarks> /// <para> /// Release the lock on the file. No further writes will be made to the /// stream until <see cref="AcquireLock"/> is called again. /// </para> /// </remarks> public abstract void ReleaseLock(); /// <summary> /// Gets or sets the <see cref="FileAppender"/> for this LockingModel /// </summary> /// <value> /// The <see cref="FileAppender"/> for this LockingModel /// </value> /// <remarks> /// <para> /// The file appender this locking model is attached to and working on /// behalf of. /// </para> /// <para> /// The file appender is used to locate the security context and the error handler to use. /// </para> /// <para> /// The value of this property will be set before <see cref="OpenFile"/> is /// called. /// </para> /// </remarks> public FileAppender CurrentAppender { get { return m_appender; } set { m_appender = value; } } /// <summary> /// Helper method that creates a FileStream under CurrentAppender's SecurityContext. /// </summary> /// <remarks> /// <para> /// Typically called during OpenFile or AcquireLock. /// </para> /// <para> /// If the directory portion of the <paramref name="filename"/> does not exist, it is created /// via Directory.CreateDirecctory. /// </para> /// </remarks> /// <param name="filename"></param> /// <param name="append"></param> /// <param name="fileShare"></param> /// <returns></returns> protected Stream CreateStream(string filename, bool append, FileShare fileShare) { using (CurrentAppender.SecurityContext.Impersonate(this)) { // Ensure that the directory structure exists string directoryFullName = Path.GetDirectoryName(filename); // Only create the directory if it does not exist // doing this check here resolves some permissions failures if (!Directory.Exists(directoryFullName)) { Directory.CreateDirectory(directoryFullName); } FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create; return new FileStream(filename, fileOpenMode, FileAccess.Write, fileShare); } } /// <summary> /// Helper method to close <paramref name="stream"/> under CurrentAppender's SecurityContext. /// </summary> /// <remarks> /// Does not set <paramref name="stream"/> to null. /// </remarks> /// <param name="stream"></param> protected void CloseStream(Stream stream) { using (CurrentAppender.SecurityContext.Impersonate(this)) { stream.Close(); } } } /// <summary> /// Hold an exclusive lock on the output file /// </summary> /// <remarks> /// <para> /// Open the file once for writing and hold it open until <see cref="CloseFile"/> is called. /// Maintains an exclusive lock on the file during this time. /// </para> /// </remarks> public class ExclusiveLock : LockingModelBase { private Stream m_stream = null; /// <summary> /// Open the file specified and prepare for logging. /// </summary> /// <param name="filename">The filename to use</param> /// <param name="append">Whether to append to the file, or overwrite</param> /// <param name="encoding">The encoding to use</param> /// <remarks> /// <para> /// Open the file specified and prepare for logging. /// No writes will be made until <see cref="AcquireLock"/> is called. /// Must be called before any calls to <see cref="AcquireLock"/>, /// <see cref="ReleaseLock"/> and <see cref="CloseFile"/>. /// </para> /// </remarks> public override void OpenFile(string filename, bool append,Encoding encoding) { try { m_stream = CreateStream(filename, append, FileShare.Read); } catch (Exception e1) { CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file "+filename+". "+e1.Message); } } /// <summary> /// Close the file /// </summary> /// <remarks> /// <para> /// Close the file. No further writes will be made. /// </para> /// </remarks> public override void CloseFile() { CloseStream(m_stream); m_stream = null; } /// <summary> /// Acquire the lock on the file /// </summary> /// <returns>A stream that is ready to be written to.</returns> /// <remarks> /// <para> /// Does nothing. The lock is already taken /// </para> /// </remarks> public override Stream AcquireLock() { return m_stream; } /// <summary> /// Release the lock on the file /// </summary> /// <remarks> /// <para> /// Does nothing. The lock will be released when the file is closed. /// </para> /// </remarks> public override void ReleaseLock() { //NOP } } /// <summary> /// Acquires the file lock for each write /// </summary> /// <remarks> /// <para> /// Opens the file once for each <see cref="AcquireLock"/>/<see cref="ReleaseLock"/> cycle, /// thus holding the lock for the minimal amount of time. This method of locking /// is considerably slower than <see cref="FileAppender.ExclusiveLock"/> but allows /// other processes to move/delete the log file whilst logging continues. /// </para> /// </remarks> public class MinimalLock : LockingModelBase { private string m_filename; private bool m_append; private Stream m_stream=null; /// <summary> /// Prepares to open the file when the first message is logged. /// </summary> /// <param name="filename">The filename to use</param> /// <param name="append">Whether to append to the file, or overwrite</param> /// <param name="encoding">The encoding to use</param> /// <remarks> /// <para> /// Open the file specified and prepare for logging. /// No writes will be made until <see cref="AcquireLock"/> is called. /// Must be called before any calls to <see cref="AcquireLock"/>, /// <see cref="ReleaseLock"/> and <see cref="CloseFile"/>. /// </para> /// </remarks> public override void OpenFile(string filename, bool append, Encoding encoding) { m_filename=filename; m_append=append; } /// <summary> /// Close the file /// </summary> /// <remarks> /// <para> /// Close the file. No further writes will be made. /// </para> /// </remarks> public override void CloseFile() { // NOP } /// <summary> /// Acquire the lock on the file /// </summary> /// <returns>A stream that is ready to be written to.</returns> /// <remarks> /// <para> /// Acquire the lock on the file in preparation for writing to it. /// Return a stream pointing to the file. <see cref="ReleaseLock"/> /// must be called to release the lock on the output file. /// </para> /// </remarks> public override Stream AcquireLock() { if (m_stream==null) { try { m_stream = CreateStream(m_filename, m_append, FileShare.Read); m_append = true; } catch (Exception e1) { CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file "+m_filename+". "+e1.Message); } } return m_stream; } /// <summary> /// Release the lock on the file /// </summary> /// <remarks> /// <para> /// Release the lock on the file. No further writes will be made to the /// stream until <see cref="AcquireLock"/> is called again. /// </para> /// </remarks> public override void ReleaseLock() { CloseStream(m_stream); m_stream = null; } } #if !NETCF /// <summary> /// Provides cross-process file locking. /// </summary> /// <author>Ron Grabowski</author> /// <author>Steve Wranovsky</author> public class InterProcessLock : LockingModelBase { private Mutex m_mutex = null; private bool m_mutexClosed = false; private Stream m_stream = null; /// <summary> /// Open the file specified and prepare for logging. /// </summary> /// <param name="filename">The filename to use</param> /// <param name="append">Whether to append to the file, or overwrite</param> /// <param name="encoding">The encoding to use</param> /// <remarks> /// <para> /// Open the file specified and prepare for logging. /// No writes will be made until <see cref="AcquireLock"/> is called. /// Must be called before any calls to <see cref="AcquireLock"/>, /// -<see cref="ReleaseLock"/> and <see cref="CloseFile"/>. /// </para> /// </remarks> #if FRAMEWORK_4_0_OR_ABOVE [System.Security.SecuritySafeCritical] #endif public override void OpenFile(string filename, bool append, Encoding encoding) { try { m_stream = CreateStream(filename, append, FileShare.ReadWrite); string mutextFriendlyFilename = filename .Replace("\\", "_") .Replace(":", "_") .Replace("/", "_"); m_mutex = new Mutex(false, mutextFriendlyFilename); m_mutexClosed = false; } catch (Exception e1) { CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); } } /// <summary> /// Close the file /// </summary> /// <remarks> /// <para> /// Close the file. No further writes will be made. /// </para> /// </remarks> public override void CloseFile() { try { CloseStream(m_stream); m_stream = null; } finally { m_mutex.ReleaseMutex(); m_mutex.Close(); m_mutexClosed = true; } } /// <summary> /// Acquire the lock on the file /// </summary> /// <returns>A stream that is ready to be written to.</returns> /// <remarks> /// <para> /// Does nothing. The lock is already taken /// </para> /// </remarks> public override Stream AcquireLock() { if (m_mutex != null) { // TODO: add timeout? m_mutex.WaitOne(); // should always be true (and fast) for FileStream if (m_stream.CanSeek) { m_stream.Seek(0, SeekOrigin.End); } } return m_stream; } /// <summary> /// /// </summary> public override void ReleaseLock() { if (m_mutexClosed == false && m_mutex != null) { m_mutex.ReleaseMutex(); } } } #endif #endregion Locking Models #region Public Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public FileAppender() { } /// <summary> /// Construct a new appender using the layout, file and append mode. /// </summary> /// <param name="layout">the layout to use with this appender</param> /// <param name="filename">the full path to the file to write to</param> /// <param name="append">flag to indicate if the file should be appended to</param> /// <remarks> /// <para> /// Obsolete constructor. /// </para> /// </remarks> [Obsolete("Instead use the default constructor and set the Layout, File & AppendToFile properties")] public FileAppender(ILayout layout, string filename, bool append) { Layout = layout; File = filename; AppendToFile = append; ActivateOptions(); } /// <summary> /// Construct a new appender using the layout and file specified. /// The file will be appended to. /// </summary> /// <param name="layout">the layout to use with this appender</param> /// <param name="filename">the full path to the file to write to</param> /// <remarks> /// <para> /// Obsolete constructor. /// </para> /// </remarks> [Obsolete("Instead use the default constructor and set the Layout & File properties")] public FileAppender(ILayout layout, string filename) : this(layout, filename, true) { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the path to the file that logging will be written to. /// </summary> /// <value> /// The path to the file that logging will be written to. /// </value> /// <remarks> /// <para> /// If the path is relative it is taken as relative from /// the application base directory. /// </para> /// </remarks> virtual public string File { get { return m_fileName; } set { m_fileName = value; } } /// <summary> /// Gets or sets a flag that indicates whether the file should be /// appended to or overwritten. /// </summary> /// <value> /// Indicates whether the file should be appended to or overwritten. /// </value> /// <remarks> /// <para> /// If the value is set to false then the file will be overwritten, if /// it is set to true then the file will be appended to. /// </para> /// The default value is true. /// </remarks> public bool AppendToFile { get { return m_appendToFile; } set { m_appendToFile = value; } } /// <summary> /// Gets or sets <see cref="Encoding"/> used to write to the file. /// </summary> /// <value> /// The <see cref="Encoding"/> used to write to the file. /// </value> /// <remarks> /// <para> /// The default encoding set is <see cref="System.Text.Encoding.Default"/> /// which is the encoding for the system's current ANSI code page. /// </para> /// </remarks> public Encoding Encoding { get { return m_encoding; } set { m_encoding = value; } } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to write to the file. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to write to the file. /// </value> /// <remarks> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } #if NETCF /// <summary> /// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file. /// </summary> /// <value> /// The <see cref="FileAppender.LockingModel"/> used to lock the file. /// </value> /// <remarks> /// <para> /// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file. /// </para> /// <para> /// There are two built in locking models, <see cref="FileAppender.ExclusiveLock"/> and <see cref="FileAppender.MinimalLock"/>. /// The first locks the file from the start of logging to the end, the /// second locks only for the minimal amount of time when logging each message /// and the last synchronizes processes using a named system wide Mutex. /// </para> /// <para> /// The default locking model is the <see cref="FileAppender.ExclusiveLock"/>. /// </para> /// </remarks> #else /// <summary> /// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file. /// </summary> /// <value> /// The <see cref="FileAppender.LockingModel"/> used to lock the file. /// </value> /// <remarks> /// <para> /// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file. /// </para> /// <para> /// There are three built in locking models, <see cref="FileAppender.ExclusiveLock"/>, <see cref="FileAppender.MinimalLock"/> and <see cref="FileAppender.InterProcessLock"/> . /// The first locks the file from the start of logging to the end, the /// second locks only for the minimal amount of time when logging each message /// and the last synchronizes processes using a named system wide Mutex. /// </para> /// <para> /// The default locking model is the <see cref="FileAppender.ExclusiveLock"/>. /// </para> /// </remarks> #endif public FileAppender.LockingModelBase LockingModel { get { return m_lockingModel; } set { m_lockingModel = value; } } #endregion Public Instance Properties #region Override implementation of AppenderSkeleton /// <summary> /// Activate the options on the file appender. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// This will cause the file to be opened. /// </para> /// </remarks> override public void ActivateOptions() { base.ActivateOptions(); if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } if (m_lockingModel == null) { m_lockingModel = new FileAppender.ExclusiveLock(); } m_lockingModel.CurrentAppender=this; if (m_fileName != null) { using(SecurityContext.Impersonate(this)) { m_fileName = ConvertToFullPath(m_fileName.Trim()); } SafeOpenFile(m_fileName, m_appendToFile); } else { LogLog.Warn(declaringType, "FileAppender: File option not set for appender ["+Name+"]."); LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?"); } } #endregion Override implementation of AppenderSkeleton #region Override implementation of TextWriterAppender /// <summary> /// Closes any previously opened file and calls the parent's <see cref="TextWriterAppender.Reset"/>. /// </summary> /// <remarks> /// <para> /// Resets the filename and the file stream. /// </para> /// </remarks> override protected void Reset() { base.Reset(); m_fileName = null; } /// <summary> /// Called to initialize the file writer /// </summary> /// <remarks> /// <para> /// Will be called for each logged message until the file is /// successfully opened. /// </para> /// </remarks> override protected void PrepareWriter() { SafeOpenFile(m_fileName, m_appendToFile); } /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes a log statement to the output stream if the output stream exists /// and is writable. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { if (m_stream.AcquireLock()) { try { base.Append(loggingEvent); } finally { m_stream.ReleaseLock(); } } } /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent[])"/> /// method. /// </summary> /// <param name="loggingEvents">The array of events to log.</param> /// <remarks> /// <para> /// Acquires the output file locks once before writing all the events to /// the stream. /// </para> /// </remarks> override protected void Append(LoggingEvent[] loggingEvents) { if (m_stream.AcquireLock()) { try { base.Append(loggingEvents); } finally { m_stream.ReleaseLock(); } } } /// <summary> /// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property. /// </summary> /// <remarks> /// <para> /// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property. /// </para> /// </remarks> protected override void WriteFooter() { if (m_stream!=null) { //WriteFooter can be called even before a file is opened m_stream.AcquireLock(); try { base.WriteFooter(); } finally { m_stream.ReleaseLock(); } } } /// <summary> /// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property. /// </summary> /// <remarks> /// <para> /// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property. /// </para> /// </remarks> protected override void WriteHeader() { if (m_stream!=null) { if (m_stream.AcquireLock()) { try { base.WriteHeader(); } finally { m_stream.ReleaseLock(); } } } } /// <summary> /// Closes the underlying <see cref="TextWriter"/>. /// </summary> /// <remarks> /// <para> /// Closes the underlying <see cref="TextWriter"/>. /// </para> /// </remarks> protected override void CloseWriter() { if (m_stream!=null) { m_stream.AcquireLock(); try { base.CloseWriter(); } finally { m_stream.ReleaseLock(); } } } #endregion Override implementation of TextWriterAppender #region Public Instance Methods /// <summary> /// Closes the previously opened file. /// </summary> /// <remarks> /// <para> /// Writes the <see cref="ILayout.Footer"/> to the file and then /// closes the file. /// </para> /// </remarks> protected void CloseFile() { WriteFooterAndCloseWriter(); } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Sets and <i>opens</i> the file where the log output will go. The specified file must be writable. /// </summary> /// <param name="fileName">The path to the log file. Must be a fully qualified path.</param> /// <param name="append">If true will append to fileName. Otherwise will truncate fileName</param> /// <remarks> /// <para> /// Calls <see cref="OpenFile"/> but guarantees not to throw an exception. /// Errors are passed to the <see cref="TextWriterAppender.ErrorHandler"/>. /// </para> /// </remarks> virtual protected void SafeOpenFile(string fileName, bool append) { try { OpenFile(fileName, append); } catch(Exception e) { ErrorHandler.Error("OpenFile("+fileName+","+append+") call failed.", e, ErrorCode.FileOpenFailure); } } /// <summary> /// Sets and <i>opens</i> the file where the log output will go. The specified file must be writable. /// </summary> /// <param name="fileName">The path to the log file. Must be a fully qualified path.</param> /// <param name="append">If true will append to fileName. Otherwise will truncate fileName</param> /// <remarks> /// <para> /// If there was already an opened file, then the previous file /// is closed first. /// </para> /// <para> /// This method will ensure that the directory structure /// for the <paramref name="fileName"/> specified exists. /// </para> /// </remarks> virtual protected void OpenFile(string fileName, bool append) { if (LogLog.IsErrorEnabled) { // Internal check that the fileName passed in is a rooted path bool isPathRooted = false; using(SecurityContext.Impersonate(this)) { isPathRooted = Path.IsPathRooted(fileName); } if (!isPathRooted) { LogLog.Error(declaringType, "INTERNAL ERROR. OpenFile("+fileName+"): File name is not fully qualified."); } } lock(this) { Reset(); LogLog.Debug(declaringType, "Opening file for writing ["+fileName+"] append ["+append+"]"); // Save these for later, allowing retries if file open fails m_fileName = fileName; m_appendToFile = append; LockingModel.CurrentAppender=this; LockingModel.OpenFile(fileName,append,m_encoding); m_stream=new LockingStream(LockingModel); if (m_stream != null) { m_stream.AcquireLock(); try { SetQWForFiles(new StreamWriter(m_stream, m_encoding)); } finally { m_stream.ReleaseLock(); } } WriteHeader(); } } /// <summary> /// Sets the quiet writer used for file output /// </summary> /// <param name="fileStream">the file stream that has been opened for writing</param> /// <remarks> /// <para> /// This implementation of <see cref="M:SetQWForFiles(Stream)"/> creates a <see cref="StreamWriter"/> /// over the <paramref name="fileStream"/> and passes it to the /// <see cref="M:SetQWForFiles(TextWriter)"/> method. /// </para> /// <para> /// This method can be overridden by sub classes that want to wrap the /// <see cref="Stream"/> in some way, for example to encrypt the output /// data using a <c>System.Security.Cryptography.CryptoStream</c>. /// </para> /// </remarks> virtual protected void SetQWForFiles(Stream fileStream) { SetQWForFiles(new StreamWriter(fileStream, m_encoding)); } /// <summary> /// Sets the quiet writer being used. /// </summary> /// <param name="writer">the writer over the file stream that has been opened for writing</param> /// <remarks> /// <para> /// This method can be overridden by sub classes that want to /// wrap the <see cref="TextWriter"/> in some way. /// </para> /// </remarks> virtual protected void SetQWForFiles(TextWriter writer) { QuietWriter = new QuietTextWriter(writer, ErrorHandler); } #endregion Protected Instance Methods #region Protected Static Methods /// <summary> /// Convert a path into a fully qualified path. /// </summary> /// <param name="path">The path to convert.</param> /// <returns>The fully qualified path.</returns> /// <remarks> /// <para> /// Converts the path specified to a fully /// qualified path. If the path is relative it is /// taken as relative from the application base /// directory. /// </para> /// </remarks> protected static string ConvertToFullPath(string path) { return SystemInfo.ConvertToFullPath(path); } #endregion Protected Static Methods #region Private Instance Fields /// <summary> /// Flag to indicate if we should append to the file /// or overwrite the file. The default is to append. /// </summary> private bool m_appendToFile = true; /// <summary> /// The name of the log file. /// </summary> private string m_fileName = null; /// <summary> /// The encoding to use for the file stream. /// </summary> private Encoding m_encoding = Encoding.Default; /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; /// <summary> /// The stream to log to. Has added locking semantics /// </summary> private FileAppender.LockingStream m_stream = null; /// <summary> /// The locking model to use /// </summary> private FileAppender.LockingModelBase m_lockingModel = new FileAppender.ExclusiveLock(); #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the FileAppender class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(FileAppender); #endregion Private Static Fields } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using Fluent.Extensions; using Fluent.Internal; /// <summary> /// Dismiss popup mode. /// </summary> public enum DismissPopupMode { /// <summary> /// Always dismiss popup. /// </summary> Always, /// <summary> /// Dismiss only if mouse is not over popup. /// </summary> MouseNotOver } /// <summary> /// Reason for dismiss popup event. /// </summary> public enum DismissPopupReason { /// <summary> /// No reason given. /// </summary> Undefined, /// <summary> /// Application lost focus. /// </summary> ApplicationLostFocus, /// <summary> /// Showing key tips. /// </summary> ShowingKeyTips } /// <summary> /// Dismiss popup arguments. /// </summary> public class DismissPopupEventArgs : RoutedEventArgs { /// <summary> /// Standard constructor. /// </summary> public DismissPopupEventArgs() : this(DismissPopupMode.Always) { } /// <summary> /// Constructor. /// </summary> /// <param name="dismissMode">Dismiss mode.</param> public DismissPopupEventArgs(DismissPopupMode dismissMode) : this(dismissMode, DismissPopupReason.Undefined) { } /// <summary> /// Constructor. /// </summary> /// <param name="dismissMode">Dismiss mode.</param> /// <param name="reason">Dismiss reason.</param> public DismissPopupEventArgs(DismissPopupMode dismissMode, DismissPopupReason reason) { this.RoutedEvent = PopupService.DismissPopupEvent; this.DismissMode = dismissMode; this.DismissReason = reason; } /// <summary> /// Popup dismiss mode. /// </summary> public DismissPopupMode DismissMode { get; } /// <summary> /// Popup dismiss reason. /// </summary> public DismissPopupReason DismissReason { get; set; } /// <inheritdoc /> protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget) { var handler = (EventHandler<DismissPopupEventArgs>)genericHandler; handler(genericTarget, this); } } /// <summary> /// Represent additional popup functionality /// </summary> public static class PopupService { #region DismissPopup /// <summary> /// Occurs then popup is dismissed /// </summary> public static readonly RoutedEvent DismissPopupEvent = EventManager.RegisterRoutedEvent("DismissPopup", RoutingStrategy.Bubble, typeof(EventHandler<DismissPopupEventArgs>), typeof(PopupService)); /// <summary> /// Raises DismissPopup event (Async) /// </summary> public static void RaiseDismissPopupEventAsync(object sender, DismissPopupMode mode, DismissPopupReason reason = DismissPopupReason.Undefined) { var element = sender as UIElement; if (element is null) { return; } WriteDebug($"Dismissing Popup async (Mode = {mode}, Sender = {sender})"); element.RunInDispatcherAsync(() => RaiseDismissPopupEvent(sender, mode, reason)); } /// <summary> /// Raises DismissPopup event /// </summary> public static void RaiseDismissPopupEvent(object sender, DismissPopupMode mode, DismissPopupReason reason = DismissPopupReason.Undefined) { var element = sender as UIElement; if (element is null) { return; } WriteDebug($"Dismissing Popup (Mode = {mode}, Sender = {sender})"); element.RaiseEvent(new DismissPopupEventArgs(mode, reason)); } #endregion /// <summary> /// Set needed parameters to control /// </summary> /// <param name="classType">Control type</param> public static void Attach(Type classType) { EventManager.RegisterClassHandler(classType, Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler(OnClickThroughThunk)); EventManager.RegisterClassHandler(classType, DismissPopupEvent, new EventHandler<DismissPopupEventArgs>(OnDismissPopup)); EventManager.RegisterClassHandler(classType, FrameworkElement.ContextMenuOpeningEvent, new ContextMenuEventHandler(OnContextMenuOpening), true); EventManager.RegisterClassHandler(classType, FrameworkElement.ContextMenuClosingEvent, new ContextMenuEventHandler(OnContextMenuClosing), true); EventManager.RegisterClassHandler(classType, UIElement.LostMouseCaptureEvent, new MouseEventHandler(OnLostMouseCapture)); } /// <summary> /// Handles PreviewMouseDownOutsideCapturedElementEvent event /// </summary> public static void OnClickThroughThunk(object sender, MouseButtonEventArgs e) { WriteDebug(nameof(OnClickThroughThunk)); WriteDebug($"Sender - {sender}"); WriteDebug($"OriginalSource - {e.OriginalSource}"); WriteDebug($"Mouse.Captured - {Mouse.Captured}"); if (e.ChangedButton == MouseButton.Left || e.ChangedButton == MouseButton.Right) { if (Mouse.Captured == sender // Special handling for unknown Popups (for example datepickers used in the ribbon) || (sender is IDropDownControl && IsPopupRoot(Mouse.Captured))) { if (sender is RibbonTabControl ribbonTabControl && ribbonTabControl.IsMinimized // this is true if, for example, a DatePicker popup is open and we click outside of the ribbon popup // this should then only close the DatePicker popup but not the ribbon popup && IsPopupRoot(e.OriginalSource) == false) { // Don't close the ribbon popup if the mouse is over the ribbon popup if (IsMousePhysicallyOver(ribbonTabControl.SelectedContentPresenter) == false) { // Force dismissing the Ribbon-Popup. // Always is needed because of eager-closing-prevention. RaiseDismissPopupEvent(sender, DismissPopupMode.Always); } } else { RaiseDismissPopupEvent(sender, DismissPopupMode.MouseNotOver); } } } } /// <summary> /// Handles lost mouse capture event /// </summary> public static void OnLostMouseCapture(object sender, MouseEventArgs e) { WriteDebug(nameof(OnLostMouseCapture)); WriteDebug($"Sender - {sender}"); WriteDebug($"OriginalSource - {e.OriginalSource}"); WriteDebug($"Mouse.Captured - {Mouse.Captured}"); var control = sender as IDropDownControl; if (control is null) { return; } if (Mouse.Captured == sender || control.IsDropDownOpen == false || control.IsContextMenuOpened) { WriteDebug($"OnLostMouseCapture => Taking no action"); return; } var popup = control.DropDownPopup; if (popup?.Child is null) { RaiseDismissPopupEvent(sender, DismissPopupMode.MouseNotOver); return; } if (e.OriginalSource == sender) { // If Ribbon loses capture because something outside popup is clicked - close the popup if (popup.PlacementTarget is RibbonTabItem) { if (Mouse.Captured is null || IsAncestorOf(popup, Mouse.Captured as DependencyObject) == false) { RaiseDismissPopupEvent(sender, DismissPopupMode.Always); } } return; } if (IsAncestorOf(popup, sender as DependencyObject) == false && IsAncestorOf(sender as DependencyObject, popup) == false && IsAncestorOf(popup, e.OriginalSource as DependencyObject) == false) { RaiseDismissPopupEvent(sender, DismissPopupMode.MouseNotOver); return; } // This code is needed to keep some popus open. // One of these is the ribbon popup when it's minimized. if (e.OriginalSource != null && Mouse.Captured is null && (IsPopupRoot(e.OriginalSource) || IsAncestorOf(popup.Child, e.OriginalSource as DependencyObject))) { WriteDebug($"Setting mouse capture to: {sender}"); Mouse.Capture(sender as IInputElement, CaptureMode.SubTree); e.Handled = true; // Only raise a popup dismiss event if the source is MenuBase. // this is because MenuBase "steals" the mouse focus in a way we have to work around here. if (e.OriginalSource is MenuBase) { RaiseDismissPopupEvent(sender, DismissPopupMode.MouseNotOver); } } } /// <summary> /// Returns true whether parent is ancestor of element /// </summary> /// <param name="parent">Parent</param> /// <param name="element">Element</param> /// <returns>Returns true whether parent is ancestor of element</returns> public static bool IsAncestorOf(DependencyObject parent, DependencyObject element) { if (parent is null) { return false; } while (element != null) { if (ReferenceEquals(element, parent)) { return true; } element = UIHelper.GetVisualOrLogicalParent(element); } return false; } /// <summary> /// Handles dismiss popup event /// </summary> public static void OnDismissPopup(object sender, DismissPopupEventArgs e) { var control = sender as IDropDownControl; if (control is null) { return; } switch (e.DismissMode) { case DismissPopupMode.Always: DismisPopupForAlways(control, e); break; case DismissPopupMode.MouseNotOver: DismisPopupForMouseNotOver(control, e); break; default: throw new ArgumentOutOfRangeException(nameof(e.DismissMode), e.DismissMode, "Unknown DismissMode."); } } private static void DismisPopupForAlways(IDropDownControl control, DismissPopupEventArgs e) { control.IsDropDownOpen = false; } private static void DismisPopupForMouseNotOver(IDropDownControl control, DismissPopupEventArgs e) { if (control.IsDropDownOpen == false) { return; } // Prevent eager closing of the Ribbon-Popup and forward mouse focus to the ribbon popup instead. if (control is RibbonTabControl ribbonTabControl && ribbonTabControl.IsMinimized && IsAncestorOf(control as DependencyObject, e.OriginalSource as DependencyObject)) { // Don't prevent closing if the new target is an ApplicationMenu (#581) if (Mouse.Captured is ApplicationMenu) { control.IsDropDownOpen = false; return; } Mouse.Capture(control as IInputElement, CaptureMode.SubTree); return; } if (IsMousePhysicallyOver(control.DropDownPopup) == false) { control.IsDropDownOpen = false; } else { if (Mouse.Captured != control) { Mouse.Capture(control as IInputElement, CaptureMode.SubTree); } e.Handled = true; } } /// <summary> /// Returns true whether mouse is physically over the popup /// </summary> /// <param name="popup">Element</param> /// <returns>Returns true whether mouse is physically over the popup</returns> public static bool IsMousePhysicallyOver(Popup popup) { if (popup?.Child is null) { return false; } return IsMousePhysicallyOver(popup.Child); } /// <summary> /// Returns true whether mouse is physically over the element /// </summary> /// <param name="element">Element</param> /// <returns>Returns true whether mouse is physically over the element</returns> public static bool IsMousePhysicallyOver(UIElement element) { if (element is null) { return false; } var position = Mouse.GetPosition(element); return position.X >= 0.0 && position.Y >= 0.0 && position.X <= element.RenderSize.Width && position.Y <= element.RenderSize.Height; } /// <summary> /// Handles context menu opening event /// </summary> public static void OnContextMenuOpening(object sender, ContextMenuEventArgs e) { if (sender is IDropDownControl control) { control.IsContextMenuOpened = true; WriteDebug("Context menu opening"); } } /// <summary> /// Handles context menu closing event /// </summary> public static void OnContextMenuClosing(object sender, ContextMenuEventArgs e) { if (sender is IDropDownControl control) { WriteDebug("Context menu closing"); control.IsContextMenuOpened = false; if (Mouse.Captured is System.Windows.Controls.ContextMenu == false) { RaiseDismissPopupEvent(e.OriginalSource, DismissPopupMode.MouseNotOver); } } } private static bool IsPopupRoot(object obj) { if (obj is null) { return false; } var type = obj.GetType(); return type.FullName == "System.Windows.Controls.Primitives.PopupRoot" || type.Name == "PopupRoot"; } private static void WriteDebug(string message) { //Debug.WriteLine(message); } } }
// // StreamPositionLabel.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Unix; using Gtk; namespace Banshee.Widgets { public enum StreamLabelState { Idle, Contacting, Loading, Buffering, Playing } public class StreamPositionLabel : Alignment { private double buffering_progress; private bool is_live; private SeekSlider seekRange; private string format_string = "<small>{0}</small>"; private Pango.Layout layout; private StreamLabelState state; public StreamPositionLabel (SeekSlider seekRange) : base (0.0f, 0.0f, 1.0f, 1.0f) { AppPaintable = true; this.seekRange = seekRange; this.seekRange.ValueChanged += OnSliderUpdated; } protected StreamPositionLabel (IntPtr raw) : base (raw) { } protected override void OnRealized () { base.OnRealized (); BuildLayouts (); UpdateLabel (); } private void BuildLayouts () { if (layout != null) { layout.Dispose (); } layout = new Pango.Layout (PangoContext); layout.FontDescription = PangoContext.FontDescription; layout.Ellipsize = Pango.EllipsizeMode.None; } private bool first_style_set = false; protected override void OnStyleUpdated () { base.OnStyleUpdated (); if (first_style_set) { BuildLayouts (); UpdateLabel (); } first_style_set = true; } protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height) { minimum_height = natural_height = 0; if (!IsRealized || layout == null) { return; } int width, height; layout.GetPixelSize (out width, out height); minimum_height = natural_height = height; } protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width) { minimum_width = natural_width = 0; if (!IsRealized || layout == null) { return; } int width, height; layout.GetPixelSize (out width, out height); minimum_width = natural_width = width; } protected override bool OnDrawn (Cairo.Context cr) { int bar_width = (int)((double)Allocation.Width * buffering_progress); bool render_bar = false; var border = StyleContext.GetBorder (StateFlags); if (bar_width > 0 && IsBuffering) { bar_width -= border.Left + border.Right; render_bar = true; StyleContext.Save (); StyleContext.AddClass ("trough"); StyleContext.RenderBackground (cr, 0, 0, Allocation.Width, Allocation.Height); StyleContext.RenderFrame (cr, 0, 0, Allocation.Width, Allocation.Height); StyleContext.Restore (); if (bar_width > 0) { StyleContext.Save (); StyleContext.AddClass ("progressbar"); StyleContext.RenderActivity (cr, border.Left, border.Top, bar_width, Allocation.Height - (border.Top + border.Bottom)); StyleContext.Restore (); } } int width, height; layout.GetPixelSize (out width, out height); int x = (Allocation.Width - width) / 2; int y = (Allocation.Height - height) / 2; Gdk.Rectangle rect = new Gdk.Rectangle (0, 0, Allocation.Width, Allocation.Height); if (render_bar) { // First render the text that is on the progressbar int full_bar_width = bar_width + border.Left; rect.Width = full_bar_width; cr.Save (); Gdk.CairoHelper.Rectangle (cr, rect); cr.Clip (); StyleContext.Save (); // The entry class is need so that the text get the "selected" color StyleContext.AddClass ("entry"); StyleContext.AddClass ("progressbar"); StyleContext.RenderLayout (cr, x, y, layout); StyleContext.Restore (); cr.Restore (); // Adjust the rectangle so that the rest of the text is rendered as expected rect.X += rect.Width; rect.Width = Allocation.Width - rect.Width; } cr.Save (); Gdk.CairoHelper.Rectangle (cr, rect); cr.Clip (); StyleContext.Save (); StyleContext.AddClass ("trough"); StyleContext.RenderLayout (cr, x, y, layout); StyleContext.Restore (); cr.Restore (); return true; } private static string idle = Catalog.GetString ("Idle"); private static string contacting = Catalog.GetString ("Contacting..."); private static string loading = Catalog.GetString ("Loading..."); private void UpdateLabel () { if (!IsRealized || layout == null) { return; } if (IsBuffering) { double progress = buffering_progress * 100.0; UpdateLabel (String.Format ("{0}: {1}%", Catalog.GetString("Buffering"), progress.ToString ("0.0"))); } else if (IsContacting) { UpdateLabel (contacting); } else if (IsLoading) { UpdateLabel (loading); } else if (IsIdle) { UpdateLabel (idle); } else if (seekRange.Duration == Int64.MaxValue) { UpdateLabel (FormatDuration ((long)seekRange.Value)); } else if (seekRange.Value == 0 && seekRange.Duration == 0) { // nop } else { UpdateLabel (String.Format (Catalog.GetString ("{0} of {1}"), FormatDuration ((long)seekRange.Value), FormatDuration ((long)seekRange.Adjustment.Upper))); } } private string last_text; private void UpdateLabel (string text) { if (!IsRealized || layout == null || text == last_text) { return; } last_text = text; layout.SetMarkup (String.Format (format_string, GLib.Markup.EscapeText (text))); QueueResize (); } private static string FormatDuration (long time) { time /= 1000; return (time > 3600 ? String.Format ("{0}:{1:00}:{2:00}", time / 3600, (time / 60) % 60, time % 60) : String.Format ("{0}:{1:00}", time / 60, time % 60)); } private void OnSliderUpdated (object o, EventArgs args) { UpdateLabel (); } public double BufferingProgress { get { return buffering_progress; } set { buffering_progress = Math.Max (0.0, Math.Min (1.0, value)); UpdateLabel (); } } public bool IsIdle { get { return StreamState == StreamLabelState.Idle; } } public bool IsBuffering { get { return StreamState == StreamLabelState.Buffering; } } public bool IsContacting { get { return StreamState == StreamLabelState.Contacting; } } public bool IsLoading { get { return StreamState == StreamLabelState.Loading; } } public StreamLabelState StreamState { get { return state; } set { if (state != value) { state = value; UpdateLabel (); } } } public bool IsLive { get { return is_live; } set { if (is_live != value) { is_live = value; UpdateLabel (); } } } public string FormatString { set { format_string = value; BuildLayouts (); UpdateLabel (); } } } }
// // SelectTool.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 Cairo; using Gtk; using Pinta.Core; using System.Linq; using Gdk; namespace Pinta.Tools { public abstract class SelectTool : SelectShapeTool { private PointD reset_origin; private PointD shape_end; private ToolControl [] controls = new ToolControl [8]; private int? active_control; private SelectionHistoryItem hist; public override Gdk.Key ShortcutKey { get { return Gdk.Key.S; } } protected override bool ShowAntialiasingButton { get { return false; } } private CursorType? active_cursor; private CombineMode combine_mode; public SelectTool () { CreateHandler (); } #region ToolBar // We don't want the ShapeTool's toolbar protected override void BuildToolBar (Toolbar tb) { PintaCore.Workspace.SelectionHandler.BuildToolbar (tb); } #endregion #region Mouse Handlers protected override void OnMouseDown (DrawingArea canvas, ButtonPressEventArgs args, Cairo.PointD point) { // Ignore extra button clicks while drawing if (is_drawing) return; Document doc = PintaCore.Workspace.ActiveDocument; hist = new SelectionHistoryItem(Icon, Name); hist.TakeSnapshot(); reset_origin = args.Event.GetPoint(); active_control = HandleResize (point); if (!active_control.HasValue) { combine_mode = PintaCore.Workspace.SelectionHandler.DetermineCombineMode(args); double x = Utility.Clamp(point.X, 0, doc.ImageSize.Width - 1); double y = Utility.Clamp(point.Y, 0, doc.ImageSize.Height - 1); shape_origin = new PointD(x, y); doc.PreviousSelection.Dispose (); doc.PreviousSelection = doc.Selection.Clone(); doc.Selection.SelectionPolygons.Clear(); // The bottom right corner should be selected. active_control = 3; } is_drawing = true; } protected override void OnMouseUp (DrawingArea canvas, ButtonReleaseEventArgs args, Cairo.PointD point) { Document doc = PintaCore.Workspace.ActiveDocument; // If the user didn't move the mouse, they want to deselect int tolerance = 0; if (Math.Abs (reset_origin.X - args.Event.X) <= tolerance && Math.Abs (reset_origin.Y - args.Event.Y) <= tolerance) { PintaCore.Actions.Edit.Deselect.Activate (); if (hist != null) { hist.Dispose(); hist = null; } doc.ToolLayer.Clear (); } else { ClearHandles (doc.ToolLayer); ReDraw(args.Event.State); if (doc.Selection != null) { SelectionModeHandler.PerformSelectionMode (combine_mode, doc.Selection.SelectionPolygons); doc.Selection.Origin = shape_origin; doc.Selection.End = shape_end; PintaCore.Workspace.Invalidate(); } if (hist != null) { doc.History.PushNewItem(hist); hist = null; } } is_drawing = false; active_control = null; // Update the mouse cursor. UpdateCursor (point); } protected override void OnDeactivated(BaseTool newTool) { base.OnDeactivated (newTool); if (PintaCore.Workspace.HasOpenDocuments) { Document doc = PintaCore.Workspace.ActiveDocument; doc.ToolLayer.Clear (); } } protected override void OnCommit () { base.OnCommit (); if (PintaCore.Workspace.HasOpenDocuments) { Document doc = PintaCore.Workspace.ActiveDocument; doc.ToolLayer.Clear (); } } protected override void OnMouseMove (object o, MotionNotifyEventArgs args, Cairo.PointD point) { Document doc = PintaCore.Workspace.ActiveDocument; if (!is_drawing) { UpdateCursor (point); return; } double x = Utility.Clamp(point.X, 0, doc.ImageSize.Width - 1); double y = Utility.Clamp(point.Y, 0, doc.ImageSize.Height - 1); controls[active_control.Value].HandleMouseMove (x, y, args.Event.State); ClearHandles (doc.ToolLayer); RefreshHandler (); ReDraw (args.Event.State); if (doc.Selection != null) { SelectionModeHandler.PerformSelectionMode (combine_mode, doc.Selection.SelectionPolygons); PintaCore.Workspace.Invalidate(); } } protected void RefreshHandler () { controls[0].Position = new PointD (shape_origin.X, shape_origin.Y); controls[1].Position = new PointD (shape_origin.X, shape_end.Y); controls[2].Position = new PointD (shape_end.X, shape_origin.Y); controls[3].Position = new PointD (shape_end.X, shape_end.Y); controls[4].Position = new PointD (shape_origin.X, (shape_origin.Y + shape_end.Y) / 2); controls[5].Position = new PointD ((shape_origin.X + shape_end.X) / 2, shape_origin.Y); controls[6].Position = new PointD (shape_end.X, (shape_origin.Y + shape_end.Y) / 2); controls[7].Position = new PointD ((shape_origin.X + shape_end.X) / 2, shape_end.Y); } public void ReDraw (Gdk.ModifierType state) { Document doc = PintaCore.Workspace.ActiveDocument; doc.ShowSelection = true; doc.ToolLayer.Hidden = false; bool constraint = (state & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask; if (constraint) { double dx = Math.Abs (shape_end.X - shape_origin.X); double dy = Math.Abs (shape_end.Y - shape_origin.Y); if (dx <= dy) if (shape_end.X >= shape_origin.X) shape_end.X = shape_origin.X + dy; else shape_end.X = shape_origin.X - dy; else if (shape_end.Y >= shape_origin.Y) shape_end.Y = shape_origin.Y + dx; else shape_end.Y = shape_origin.Y - dx; } Cairo.Rectangle rect = Utility.PointsToRectangle (shape_origin, shape_end, constraint); Cairo.Rectangle dirty = DrawShape (rect, doc.SelectionLayer); DrawHandler (doc.ToolLayer); last_dirty = dirty; } protected void CreateHandler () { controls[0] = new ToolControl (CursorType.TopLeftCorner, (x, y, s) => { shape_origin.X = x; shape_origin.Y = y; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { if (shape_end.X - shape_origin.X <= shape_end.Y - shape_origin.Y) shape_origin.X = shape_end.X - shape_end.Y + shape_origin.Y; else shape_origin.Y = shape_end.Y - shape_end.X + shape_origin.X; } }); controls[1] = new ToolControl (CursorType.BottomLeftCorner, (x, y, s) => { shape_origin.X = x; shape_end.Y = y; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { if (shape_end.X - shape_origin.X <= shape_end.Y - shape_origin.Y) shape_origin.X = shape_end.X - shape_end.Y + shape_origin.Y; else shape_end.Y = shape_origin.Y + shape_end.X - shape_origin.X; } }); controls[2] = new ToolControl (CursorType.TopRightCorner, (x, y, s) => { shape_end.X = x; shape_origin.Y = y; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { if (shape_end.X - shape_origin.X <= shape_end.Y - shape_origin.Y) shape_end.X = shape_origin.X + shape_end.Y - shape_origin.Y; else shape_origin.Y = shape_end.Y - shape_end.X + shape_origin.X; } }); controls[3] = new ToolControl (CursorType.BottomRightCorner, (x, y, s) => { shape_end.X = x; shape_end.Y = y; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { if (shape_end.X - shape_origin.X <= shape_end.Y - shape_origin.Y) shape_end.X = shape_origin.X + shape_end.Y - shape_origin.Y; else shape_end.Y = shape_origin.Y + shape_end.X - shape_origin.X; } }); controls[4] = new ToolControl (CursorType.LeftSide, (x, y, s) => { shape_origin.X = x; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { double d = shape_end.X - shape_origin.X; shape_origin.Y = (shape_origin.Y + shape_end.Y - d) / 2; shape_end.Y = (shape_origin.Y + shape_end.Y + d) / 2; } }); controls[5] = new ToolControl (CursorType.TopSide, (x, y, s) => { shape_origin.Y = y; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { double d = shape_end.Y - shape_origin.Y; shape_origin.X = (shape_origin.X + shape_end.X - d) / 2; shape_end.X = (shape_origin.X + shape_end.X + d) / 2; } }); controls[6] = new ToolControl (CursorType.RightSide, (x, y, s) => { shape_end.X = x; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { double d = shape_end.X - shape_origin.X; shape_origin.Y = (shape_origin.Y + shape_end.Y - d) / 2; shape_end.Y = (shape_origin.Y + shape_end.Y + d) / 2; } }); controls[7] = new ToolControl (CursorType.BottomSide, (x, y, s) => { shape_end.Y = y; if ((s & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask) { double d = shape_end.Y - shape_origin.Y; shape_origin.X = (shape_origin.X + shape_end.X - d) / 2; shape_end.X = (shape_origin.X + shape_end.X + d) / 2; } }); } public int? HandleResize (PointD point) { for (int i = 0; i < controls.Length; ++i) { if (controls[i].IsInside (point)) return i; } return null; } public void DrawHandler (Layer layer) { using (var g = new Context(layer.Surface)) { foreach (var tool_control in controls) tool_control.Render (g); } } public void UpdateCursor (PointD point) { foreach (ToolControl ct in controls.Where (ct => ct.IsInside (point))) { if (active_cursor != ct.Cursor) { SetCursor (new Cursor(ct.Cursor)); active_cursor = ct.Cursor; } return; } if (active_cursor.HasValue) { SetCursor (DefaultCursor); active_cursor = null; } } #endregion public override void AfterUndo() { base.AfterUndo(); Document doc = PintaCore.Workspace.ActiveDocument; if (PintaCore.Tools.CurrentTool == this) doc.ToolLayer.Hidden = false; shape_origin = doc.Selection.Origin; shape_end = doc.Selection.End; UpdateHandler(); } public override void AfterRedo() { base.AfterRedo(); Document doc = PintaCore.Workspace.ActiveDocument; if (PintaCore.Tools.CurrentTool == this) doc.ToolLayer.Hidden = false; shape_origin = doc.Selection.Origin; shape_end = doc.Selection.End; UpdateHandler(); } /// <summary> /// Update the selection handles' positions, and redraw them. /// </summary> private void UpdateHandler () { var doc = PintaCore.Workspace.ActiveDocument; ClearHandles (doc.ToolLayer); RefreshHandler(); DrawHandler (doc.ToolLayer); PintaCore.Workspace.Invalidate(); } /// <summary> /// Erase previously-drawn handles. /// </summary> private void ClearHandles (Layer layer) { using (var g = new Context (layer.Surface)) { foreach (var tool_control in controls) tool_control.Clear (g); } } } }
// // MetaMetadata.cs // s.im.pl serialization // // Generated by DotNetTranslator on 11/16/10. // Copyright 2010 Interface Ecology Lab. // using System; using System.Collections.Generic; using System.IO; using Ecologylab.BigSemantics.Actions; using Ecologylab.BigSemantics.MetadataNS; using Ecologylab.BigSemantics.PlatformSpecifics; using Simpl.Fundamental.Generic; using Simpl.Serialization.Attributes; using Simpl.Serialization; using Simpl.Serialization.Types.Element; using Ecologylab.BigSemantics.MetadataNS.Builtins; namespace Ecologylab.BigSemantics.MetaMetadataNS { [SimplInherit] [SimplDescriptorClasses(new[] { typeof(MetaMetadataClassDescriptor), typeof(MetaMetadataFieldDescriptor) })] public class MetaMetadata : MetaMetadataCompositeField, IMappable<String> { private const string ROOT_MMD_NAME = "metadata"; [SimplScalar] protected string ormInheritanceStrategy; [SimplNoWrap] [SimplCollection("selector")] private List<MetaMetadataSelector> selectors; [SimplScalar] private Boolean dontGenerateClass; [SimplCollection] [SimplScope(SemanticOperationTranslationScope.ScopeName)] private List<SemanticOperation> beforeSemanticActions; [SimplCollection] [SimplScope(SemanticOperationTranslationScope.ScopeName)] private List<SemanticOperation> semanticActions; [SimplCollection] [SimplScope(SemanticOperationTranslationScope.ScopeName)] private List<SemanticOperation> afterSemanticActions; [SimplScalar] [MmDontInherit] private Boolean builtIn; [SimplScalar] private RedirectHandling redirectHandling; [SimplCollection("mixins")] [SimplNoWrap] private List<String> mixins; [SimplScalar] private String collectionOf; [SimplCollection("url_generator")] [SimplNoWrap] private List<UrlGenerator> urlGenerators; [SimplMap("link_with")] [SimplNoWrap] private Dictionary<String, LinkWith> linkWiths; [SimplScalar] [SimplHints(new Hint[] { Hint.XmlAttribute })] private Visibility visibility; private Dictionary<String, MetaMetadataField> naturalIds = new Dictionary<String, MetaMetadataField>(); private object file; private SimplTypesScope localMetadataTranslationScope; public MetaMetadata() { } protected override string GetMetaMetadataTagToInheritFrom() { return ExtendsAttribute ?? base.GetMetaMetadataTagToInheritFrom(); } #region Properties public Boolean DontGenerateClass { get { return dontGenerateClass; } set { dontGenerateClass = value; } } public List<String> Mixins { get { return mixins; } set { mixins = value; } } public String CollectionOf { get { return collectionOf; } set { collectionOf = value; } } public List<MetaMetadataSelector> Selectors { get { return selectors; } set { selectors = value; } } public Visibility Visibility { get { return visibility; } set { visibility = value; } } // FileInfo changed to object to accommodate windows 8 public object File { get; set; } public Dictionary<string, MetaMetadataField> NaturalIds { get { return naturalIds; } set { naturalIds = value; } } public override bool IsBuiltIn { get { return builtIn; } } public RedirectHandling RedirectHandling { get { return redirectHandling; } set { redirectHandling = value; } } public List<SemanticOperation> BeforeSemanticActions { get { return beforeSemanticActions; } } public List<SemanticOperation> SemanticActions { get { return semanticActions; } } public List<SemanticOperation> AfterSemanticActions { get { return afterSemanticActions; } } #endregion String IMappable<String>.Key() { return Name; } public bool IsDerivedFrom(MetaMetadata baseMmd) { MetaMetadata mmd = this; while (mmd != null) { if (mmd == baseMmd) return true; mmd = mmd.SuperMmd; } return false; } protected override bool InheritMetaMetadataHelper(InheritanceHandler inheritanceHandler) { inheritanceHandler = new InheritanceHandler(this); // init each field's declaringMmd to this (some of them may change during inheritance) foreach (MetaMetadataField field in Kids.Values) field.DeclaringMmd = this; return base.InheritMetaMetadataHelper(inheritanceHandler); } protected override void InheritNonFieldElements(MetaMetadata inheritedMmd, InheritanceHandler inheritanceHandler) { base.InheritNonFieldElements(inheritedMmd, inheritanceHandler); InheritAttributes(inheritedMmd); if (this.genericTypeVars != null) this.genericTypeVars.InheritFrom(inheritedMmd.genericTypeVars, inheritanceHandler); //InheritSemanticActions(inheritedMmd); } protected override void InheritFrom(MetaMetadataRepository repository, MetaMetadataCompositeField inheritedStructure, InheritanceHandler inheritanceHandler) { base.InheritFrom(repository, inheritedStructure, inheritanceHandler); // for fields referring to this meta-metadata type // need to do inheritMetaMetadata() again after copying fields from this.getInheritedMmd() /* foreach (MetaMetadataField f in this.Kids.Values) { if (f.GetType() == typeof(MetaMetadataNestedField)) { MetaMetadataNestedField nested = (MetaMetadataNestedField) f; if (nested.InheritedMmd == this) { nested.ClearInheritFinishedOrInProgressFlag(); nested.InheritMetaMetadata(); } } } */ } public new MetadataClassDescriptor BindMetadataClassDescriptor(SimplTypesScope metadataTScope) { if (metadataClassDescriptor != null) return metadataClassDescriptor; // create a temporary local metadata translation scope SimplTypesScope localMetadataTScope = SimplTypesScope.Get("mmd_local_tscope:" + Name, metadataTScope ); // record the initial number of classes in the local translation scope int initialLocalTScopeSize = localMetadataTScope.EntriesByClassName.Count; // do actual stuff ... base.BindMetadataClassDescriptor(localMetadataTScope); // if tag overlaps, or there are fields using classes not in metadataTScope, use localTScope MetadataClassDescriptor thisCd = this.MetadataClassDescriptor; if (thisCd != null) { MetadataClassDescriptor thatCd = (MetadataClassDescriptor)metadataTScope.GetClassDescriptorByTag(thisCd.TagName); if (thisCd != thatCd) { localMetadataTScope.AddTranslation(thisCd); this.localMetadataTranslationScope = localMetadataTScope; } else if (localMetadataTScope.EntriesByClassName.Count > initialLocalTScopeSize) this.localMetadataTranslationScope = localMetadataTScope; else this.localMetadataTranslationScope = metadataTScope; } // return the bound metadata class descriptor return thisCd; } protected override MetaMetadata FindOrGenerateInheritedMetaMetadata(MetaMetadataRepository repository, InheritanceHandler inheritanceHandler) { if (MetaMetadata.IsRootMetaMetadata(this)) return null; MetaMetadata inheritedMmd = this.TypeMmd; if (inheritedMmd == null) { String inheritedMmdName = this.Type; if (inheritedMmdName == null) { inheritedMmdName = this.ExtendsAttribute; SetNewMetadataClass(true); } if (inheritedMmdName == null) throw new MetaMetadataException("no type/extends specified: " + this); inheritedMmd = (MetaMetadata) this.Scope[inheritedMmdName]; if (inheritedMmd == null) throw new MetaMetadataException("meta-metadata '" + inheritedMmdName + "' not found."); TypeMmd = inheritedMmd; } return inheritedMmd; } private static bool IsRootMetaMetadata(MetaMetadata mmd) { return mmd.Name.Equals(ROOT_MMD_NAME); } protected override String GetMetadataClassName() { return this.CSharpPackageName + "." + GetMetadataClassSimpleName(); } protected override string GetMetadataClassSimpleName() { if (IsBuiltIn || IsNewMetadataClass()) { // new definition return XmlTools.CamelCaseFromXMLElementName(Name, true);// ClassNameFromElementName(Name); } else { // re-using existing type // do not use this.type directly because we don't know if that is a definition or just re-using exsiting type MetaMetadata inheritedMmd = SuperMmd; // if (inheritedMmd == null) // InheritMetaMetadata(null);//edit // currently, this should never happend because we call this method after inheritance process. return inheritedMmd == null ? null : inheritedMmd.GetMetadataClassSimpleName(); } } public override bool IsNewMetadataClass() { return base.IsNewMetadataClass() && !IsBuiltIn; } public MetadataNS.Metadata ConstructMetadata(SimplTypesScope metadataTScope = null) { if (metadataTScope == null) metadataTScope = Repository.MetadataTScope; MetadataNS.Metadata result = null; Type metadataClass = GetMetadataClass(metadataTScope); if (metadataClass != null) { Type[] argClasses = new Type[] { typeof(MetaMetadataCompositeField) }; object[] argObjects = new object[] { this }; //result = metadataClass.GetConstructor(argClasses).Invoke(argObjects) as Metadata.Metadata; //result = SemanticsPlatformSpecifics.Get().InvokeInstance(metadataClass, argClasses, argObjects) as MetadataNS.Metadata; result = ReflectionTools.GetInstance<Metadata>(metadataClass, argObjects); // TODO handle mixins. } return result; } public MetaMetadata SuperMmd { get { return (MetaMetadata) SuperField; } set { SuperField = value; } } } public enum RedirectHandling { REDIRECT_USUAL, REDIRECT_FOLLOW_DONT_RESET_LOCATION, REDIRECT_FOLLOW_GET_NEW_MM, } public enum Visibility { GLOBAL, PACKAGE, } }
/* * 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.Drawing; using OpenMetaverse; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Physics.Manager; using log4net; namespace OpenSim.Region.OptionalModules.ContentManagement { public class MetaEntity { #region Constants public const float INVISIBLE = .95f; // Settings for transparency of metaentity public const float NONE = 0f; public const float TRANSLUCENT = .5f; #endregion Constants #region Static Fields //private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Static Fields #region Fields protected SceneObjectGroup m_Entity = null; // The scene object group that represents this meta entity. protected uint m_metaLocalid; #endregion Fields #region Constructors public MetaEntity() { } /// <summary> /// Makes a new meta entity by copying the given scene object group. /// The physics boolean is just a stub right now. /// </summary> public MetaEntity(SceneObjectGroup orig, bool physics) { m_Entity = orig.Copy(false); Initialize(physics); } /// <summary> /// Takes an XML description of a scene object group and converts it to a meta entity. /// </summary> public MetaEntity(string objectXML, Scene scene, bool physics) { m_Entity = SceneObjectSerializer.FromXml2Format(objectXML); m_Entity.SetScene(scene); Initialize(physics); } #endregion Constructors #region Public Properties public SceneObjectPart[] Parts { get { return m_Entity.Parts; } } public uint LocalId { get { return m_Entity.LocalId; } set { m_Entity.LocalId = value; } } public SceneObjectGroup ObjectGroup { get { return m_Entity; } } public int PrimCount { get { return m_Entity.PrimCount; } } public SceneObjectPart RootPart { get { return m_Entity.RootPart; } } public Scene Scene { get { return m_Entity.Scene; } } public UUID UUID { get { return m_Entity.UUID; } set { m_Entity.UUID = value; } } #endregion Public Properties #region Protected Methods // The metaentity objectgroup must have unique localids as well as unique uuids. // localids are used by the client to refer to parts. // uuids are sent to the client and back to the server to identify parts on the server side. /// <summary> /// Changes localids and uuids of m_Entity. /// </summary> protected void Initialize(bool physics) { //make new uuids Dictionary<UUID, SceneObjectPart> parts = new Dictionary<UUID, SceneObjectPart>(); foreach (SceneObjectPart part in m_Entity.Parts) { part.ResetIDs(part.LinkNum); parts.Add(part.UUID, part); } //finalize m_Entity.RootPart.PhysActor = null; foreach (SceneObjectPart part in parts.Values) m_Entity.AddPart(part); } #endregion Protected Methods #region Public Methods /// <summary> /// Hides the metaentity from a single client. /// </summary> public virtual void Hide(IClientAPI client) { //This deletes the group without removing from any databases. //This is important because we are not IN any database. //m_Entity.FakeDeleteGroup(); foreach (SceneObjectPart part in m_Entity.Parts) client.SendKillObject(m_Entity.RegionHandle, part.LocalId); } /// <summary> /// Sends a kill object message to all clients, effectively "hiding" the metaentity even though it's still on the server. /// </summary> public virtual void HideFromAll() { foreach (SceneObjectPart part in m_Entity.Parts) { m_Entity.Scene.ForEachClient( delegate(IClientAPI controller) { controller.SendKillObject(m_Entity.RegionHandle, part.LocalId); } ); } } public void SendFullUpdate(IClientAPI client) { // Not sure what clientFlags should be but 0 seems to work SendFullUpdate(client, 0); } public void SendFullUpdate(IClientAPI client, uint clientFlags) { m_Entity.SendFullUpdateToClient(client); } public void SendFullUpdateToAll() { m_Entity.Scene.ForEachClient( delegate(IClientAPI controller) { m_Entity.SendFullUpdateToClient(controller); } ); } /// <summary> /// Makes a single SceneObjectPart see through. /// </summary> /// <param name="part"> /// A <see cref="SceneObjectPart"/> /// The part to make see through /// </param> /// <param name="transparencyAmount"> /// A <see cref="System.Single"/> /// The degree of transparency to imbue the part with, 0f being solid and .95f being invisible. /// </param> public static void SetPartTransparency(SceneObjectPart part, float transparencyAmount) { Primitive.TextureEntry tex = null; Color4 texcolor; try { tex = part.Shape.Textures; texcolor = new Color4(); } catch(Exception) { //m_log.ErrorFormat("[Content Management]: Exception thrown while accessing textures of scene object: " + e); return; } for (uint i = 0; i < tex.FaceTextures.Length; i++) { try { if (tex.FaceTextures[i] != null) { texcolor = tex.FaceTextures[i].RGBA; texcolor.A = transparencyAmount; tex.FaceTextures[i].RGBA = texcolor; } } catch (Exception) { //m_log.ErrorFormat("[Content Management]: Exception thrown while accessing different face textures of object: " + e); continue; } } try { texcolor = tex.DefaultTexture.RGBA; texcolor.A = transparencyAmount; tex.DefaultTexture.RGBA = texcolor; part.Shape.TextureEntry = tex.GetBytes(); } catch (Exception) { //m_log.Info("[Content Management]: Exception thrown while accessing default face texture of object: " + e); } } #endregion Public Methods } }
using System.Diagnostics; using DWORD = System.Int32; using System.Threading; using System; namespace CleanSqlite { public partial class Sqlite3 { /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for win32 ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d ** ************************************************************************* */ //#include "sqliteInt.h" /* ** The code in this file is only used if we are compiling multithreaded ** on a win32 system. */ #if SQLITE_MUTEX_W32 /* ** Each recursive mutex is an instance of the following structure. */ public partial class sqlite3_mutex { public Object mutex; /* Mutex controlling the lock */ public int id; /* Mutex type */ public int nRef; /* Number of enterances */ public DWORD owner; /* Thread holding this mutex */ #if SQLITE_DEBUG public int trace; /* True to trace changes */ #endif public sqlite3_mutex() { mutex = new Object(); } public sqlite3_mutex( Mutex mutex, int id, int nRef, DWORD owner #if SQLITE_DEBUG , int trace #endif ) { this.mutex = mutex; this.id = id; this.nRef = nRef; this.owner = owner; #if SQLITE_DEBUG this.trace = 0; #endif } }; //#define SQLITE_W32_MUTEX_INITIALIZER { 0 } static Mutex SQLITE_W32_MUTEX_INITIALIZER = null; #if SQLITE_DEBUG //#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 } #else //#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0 } #endif /* ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, ** or WinCE. Return false (zero) for Win95, Win98, or WinME. ** ** Here is an interesting observation: Win95, Win98, and WinME lack ** the LockFileEx() API. But we can still statically link against that ** API as long as we don't call it win running Win95/98/ME. A call to ** this routine is used to determine if the host is Win95/98/ME or ** WinNT/2K/XP so that we will know whether or not we can safely call ** the LockFileEx() API. ** ** mutexIsNT() is only used for the TryEnterCriticalSection() API call, ** which is only available if your application was compiled with ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only ** call to TryEnterCriticalSection() is #ifdef'ed out, so #if ** this out as well. */ #if FALSE #if SQLITE_OS_WINCE //# define mutexIsNT() (1) #else static int mutexIsNT(void){ static int osType = 0; if( osType==0 ){ OSVERSIONINFO sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); GetVersionEx(&sInfo); osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1; } return osType==2; } #endif //* SQLITE_OS_WINCE */ #endif #if SQLITE_DEBUG /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside Debug.Assert() statements. */ static bool winMutexHeld( sqlite3_mutex p ) { return p.nRef != 0 && p.owner == GetCurrentThreadId(); } static bool winMutexNotheld2( sqlite3_mutex p, DWORD tid ) { return p.nRef == 0 || p.owner != tid; } static bool winMutexNotheld( sqlite3_mutex p ) { DWORD tid = GetCurrentThreadId(); return winMutexNotheld2( p, tid ); } #endif /* ** Initialize and deinitialize the mutex subsystem. */ //No MACROS under C#; Cannot use SQLITE3_MUTEX_INITIALIZER, static sqlite3_mutex[] winMutex_staticMutexes = new sqlite3_mutex[]{ new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0 #if SQLITE_DEBUG , 0 #endif ),// SQLITE3_MUTEX_INITIALIZER, new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0 #if SQLITE_DEBUG , 0 #endif ),// SQLITE3_MUTEX_INITIALIZER, new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0 #if SQLITE_DEBUG , 0 #endif ),// SQLITE3_MUTEX_INITIALIZER, new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0 #if SQLITE_DEBUG , 0 #endif ),// SQLITE3_MUTEX_INITIALIZER, new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0 #if SQLITE_DEBUG , 0 #endif ),// SQLITE3_MUTEX_INITIALIZER, new sqlite3_mutex( SQLITE_W32_MUTEX_INITIALIZER, 0, 0, (DWORD)0 #if SQLITE_DEBUG , 0 #endif ),// SQLITE3_MUTEX_INITIALIZER, }; static int winMutex_isInit = 0; /* As winMutexInit() and winMutexEnd() are called as part ** of the sqlite3_initialize and sqlite3_shutdown() ** processing, the "interlocked" magic is probably not ** strictly necessary. */ static long winMutex_lock = 0; private static System.Object lockThis = new System.Object(); static int winMutexInit() { /* The first to increment to 1 does actual initialization */ lock ( lockThis ) //if ( Interlocked.CompareExchange(ref winMutex_lock, 1, 0 ) == 0 ) { int i; for ( i = 0; i < ArraySize( winMutex_staticMutexes ); i++ ) { if (winMutex_staticMutexes[i].mutex== null) winMutex_staticMutexes[i].mutex = new Mutex(); //InitializeCriticalSection( winMutex_staticMutexes[i].mutex ); } winMutex_isInit = 1; } //else //{ // /* Someone else is in the process of initing the static mutexes */ // while ( 0 == winMutex_isInit ) // { // Thread.Sleep( 1 ); // } //} return SQLITE_OK; } static int winMutexEnd() { /* The first to decrement to 0 does actual shutdown ** (which should be the last to shutdown.) */ if ( Interlocked.CompareExchange( ref winMutex_lock, 0, 1 ) == 1 ) { if ( winMutex_isInit == 1 ) { int i; for ( i = 0; i < ArraySize( winMutex_staticMutexes ); i++ ) { DeleteCriticalSection( winMutex_staticMutexes[i].mutex ); } winMutex_isInit = 0; } } return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. SQLite ** will unwind its stack and return an error. The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_MEM2 ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU ** <li> SQLITE_MUTEX_STATIC_LRU2 ** </ul> ** ** The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. But SQLite will only request a recursive mutex in ** cases where it really needs one. If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ static sqlite3_mutex winMutexAlloc( int iType ) { sqlite3_mutex p; switch ( iType ) { case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { p = new sqlite3_mutex();//sqlite3MallocZero( sizeof(*p) ); if ( p != null ) { p.id = iType; InitializeCriticalSection( p.mutex ); } break; } default: { Debug.Assert( winMutex_isInit == 1 ); Debug.Assert( iType - 2 >= 0 ); Debug.Assert( iType - 2 < ArraySize( winMutex_staticMutexes ) ); p = winMutex_staticMutexes[iType - 2]; p.id = iType; break; } } return p; } /* ** This routine deallocates a previously ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ static void winMutexFree( sqlite3_mutex p ) { Debug.Assert( p != null ); Debug.Assert( p.nRef == 0 ); Debug.Assert( p.id == SQLITE_MUTEX_FAST || p.id == SQLITE_MUTEX_RECURSIVE ); DeleteCriticalSection( p.mutex ); p.owner = 0; //sqlite3_free( p ); } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void winMutexEnter( sqlite3_mutex p ) { DWORD tid = GetCurrentThreadId(); Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || winMutexNotheld2( p, tid ) ); EnterCriticalSection( p.mutex ); p.owner = tid; p.nRef++; #if SQLITE_DEBUG if ( p.trace != 0 ) { printf( "enter mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef ); } #endif } static int winMutexTry( sqlite3_mutex p ) { #if !NDEBUG DWORD tid = GetCurrentThreadId(); #endif int rc = SQLITE_BUSY; Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || winMutexNotheld2( p, tid ) ); /* ** The sqlite3_mutex_try() routine is very rarely used, and when it ** is used it is merely an optimization. So it is OK for it to always ** fail. ** ** The TryEnterCriticalSection() interface is only available on WinNT. ** And some windows compilers complain if you try to use it without ** first doing some #defines that prevent SQLite from building on Win98. ** For that reason, we will omit this optimization for now. See ** ticket #2685. */ #if FALSE if( mutexIsNT() && TryEnterCriticalSection(p.mutex) ){ p.owner = tid; p.nRef++; rc = SQLITE_OK; } #else UNUSED_PARAMETER( p ); #endif #if SQLITE_DEBUG if ( rc == SQLITE_OK && p.trace != 0 ) { printf( "try mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef ); } #endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void winMutexLeave( sqlite3_mutex p ) { #if !NDEBUG DWORD tid = GetCurrentThreadId(); #endif Debug.Assert( p.nRef > 0 ); Debug.Assert( p.owner == tid ); p.nRef--; Debug.Assert( p.nRef == 0 || p.id == SQLITE_MUTEX_RECURSIVE ); if (p.nRef == 0) LeaveCriticalSection( p.mutex ); #if SQLITE_DEBUG if ( p.trace != 0 ) { printf( "leave mutex {0} ({1}) with nRef={2}\n", p.GetHashCode(), p.owner, p.nRef ); } #endif } static sqlite3_mutex_methods sqlite3DefaultMutex() { sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods ( (dxMutexInit)winMutexInit, (dxMutexEnd)winMutexEnd, (dxMutexAlloc)winMutexAlloc, (dxMutexFree)winMutexFree, (dxMutexEnter)winMutexEnter, (dxMutexTry)winMutexTry, (dxMutexLeave)winMutexLeave, #if SQLITE_DEBUG (dxMutexHeld)winMutexHeld, (dxMutexNotheld)winMutexNotheld #else null, null #endif ); return sMutex; } #endif // * SQLITE_MUTEX_W32 */ } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cluster { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute; using Apache.Ignite.Core.Impl.Events; using Apache.Ignite.Core.Impl.Messaging; using Apache.Ignite.Core.Impl.Services; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Ignite projection implementation. /// </summary> internal class ClusterGroupImpl : PlatformTarget, IClusterGroup { /** Attribute: platform. */ private const string AttrPlatform = "org.apache.ignite.platform"; /** Platform. */ private const string Platform = "dotnet"; /** Initial topver; invalid from Java perspective, so update will be triggered when this value is met. */ private const int TopVerInit = 0; /** */ private const int OpForAttribute = 2; /** */ private const int OpForCache = 3; /** */ private const int OpForClient = 4; /** */ private const int OpForData = 5; /** */ private const int OpForHost = 6; /** */ private const int OpForNodeIds = 7; /** */ private const int OpMetrics = 9; /** */ private const int OpMetricsFiltered = 10; /** */ private const int OpNodeMetrics = 11; /** */ private const int OpNodes = 12; /** */ private const int OpPingNode = 13; /** */ private const int OpTopology = 14; /** */ private const int OpForRemotes = 17; /** */ private const int OpForDaemons = 18; /** */ private const int OpForRandom = 19; /** */ private const int OpForOldest = 20; /** */ private const int OpForYoungest = 21; /** */ private const int OpResetMetrics = 22; /** */ private const int OpForServers = 23; /** */ private const int OpCacheMetrics = 24; /** */ private const int OpResetLostPartitions = 25; /** */ private const int OpMemoryMetrics = 26; /** */ private const int OpMemoryMetricsByName = 27; /** Initial Ignite instance. */ private readonly Ignite _ignite; /** Predicate. */ private readonly Func<IClusterNode, bool> _pred; /** Topology version. */ private long _topVer = TopVerInit; /** Nodes for the given topology version. */ private volatile IList<IClusterNode> _nodes; /** Processor. */ private readonly IUnmanagedTarget _proc; /** Compute. */ private readonly Lazy<Compute> _comp; /** Messaging. */ private readonly Lazy<Messaging> _msg; /** Events. */ private readonly Lazy<Events> _events; /** Services. */ private readonly Lazy<IServices> _services; /// <summary> /// Constructor. /// </summary> /// <param name="proc">Processor.</param> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="ignite">Grid.</param> /// <param name="pred">Predicate.</param> [SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily")] public ClusterGroupImpl(IUnmanagedTarget proc, IUnmanagedTarget target, Marshaller marsh, Ignite ignite, Func<IClusterNode, bool> pred) : base(target, marsh) { _proc = proc; _ignite = ignite; _pred = pred; _comp = new Lazy<Compute>(() => new Compute(new ComputeImpl(UU.ProcessorCompute(proc, target), marsh, this, false))); _msg = new Lazy<Messaging>(() => new Messaging(UU.ProcessorMessage(proc, target), marsh, this)); _events = new Lazy<Events>(() => new Events(UU.ProcessorEvents(proc, target), marsh, this)); _services = new Lazy<IServices>(() => new Services(UU.ProcessorServices(proc, target), marsh, this, false, false)); } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite; } } /** <inheritDoc /> */ public ICompute GetCompute() { return _comp.Value; } /** <inheritDoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); return ForNodeIds0(nodes, node => node.Id); } /** <inheritDoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); return ForNodeIds0(nodes, node => node.Id); } /** <inheritDoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { IgniteArgumentCheck.NotNull(ids, "ids"); return ForNodeIds0(ids, null); } /** <inheritDoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { IgniteArgumentCheck.NotNull(ids, "ids"); return ForNodeIds0(ids, null); } /// <summary> /// Internal routine to get projection for specific node IDs. /// </summary> /// <param name="items">Items.</param> /// <param name="func">Function to transform item to Guid (optional).</param> /// <returns></returns> private IClusterGroup ForNodeIds0<T>(IEnumerable<T> items, Func<T, Guid> func) { Debug.Assert(items != null); IUnmanagedTarget prj = DoOutOpObject(OpForNodeIds, writer => { WriteEnumerable(writer, items, func); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { var newPred = _pred == null ? p : node => _pred(node) && p(node); return new ClusterGroupImpl(_proc, Target, Marshaller, _ignite, newPred); } /** <inheritDoc /> */ public IClusterGroup ForAttribute(string name, string val) { IgniteArgumentCheck.NotNull(name, "name"); Action<BinaryWriter> action = writer => { writer.WriteString(name); writer.WriteString(val); }; IUnmanagedTarget prj = DoOutOpObject(OpForAttribute, action); return GetClusterGroup(prj); } /// <summary> /// Creates projection with a specified op. /// </summary> /// <param name="name">Cache name to include into projection.</param> /// <param name="op">Operation id.</param> /// <returns> /// Projection over nodes that have specified cache running. /// </returns> private IClusterGroup ForCacheNodes(string name, int op) { IUnmanagedTarget prj = DoOutOpObject(op, writer => { writer.WriteString(name); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForCacheNodes(string name) { return ForCacheNodes(name, OpForCache); } /** <inheritDoc /> */ public IClusterGroup ForDataNodes(string name) { return ForCacheNodes(name, OpForData); } /** <inheritDoc /> */ public IClusterGroup ForClientNodes(string name) { return ForCacheNodes(name, OpForClient); } /** <inheritDoc /> */ public IClusterGroup ForRemotes() { return GetClusterGroup(DoOutOpObject(OpForRemotes)); } /** <inheritDoc /> */ public IClusterGroup ForDaemons() { return GetClusterGroup(DoOutOpObject(OpForDaemons)); } /** <inheritDoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); IUnmanagedTarget prj = DoOutOpObject(OpForHost, writer => { writer.WriteGuid(node.Id); }); return GetClusterGroup(prj); } /** <inheritDoc /> */ public IClusterGroup ForRandom() { return GetClusterGroup(DoOutOpObject(OpForRandom)); } /** <inheritDoc /> */ public IClusterGroup ForOldest() { return GetClusterGroup(DoOutOpObject(OpForOldest)); } /** <inheritDoc /> */ public IClusterGroup ForYoungest() { return GetClusterGroup(DoOutOpObject(OpForYoungest)); } /** <inheritDoc /> */ public IClusterGroup ForServers() { return GetClusterGroup(DoOutOpObject(OpForServers)); } /** <inheritDoc /> */ public IClusterGroup ForDotNet() { return ForAttribute(AttrPlatform, Platform); } /** <inheritDoc /> */ public ICollection<IClusterNode> GetNodes() { return RefreshNodes(); } /** <inheritDoc /> */ public IClusterNode GetNode(Guid id) { return GetNodes().FirstOrDefault(node => node.Id == id); } /** <inheritDoc /> */ public IClusterNode GetNode() { return GetNodes().FirstOrDefault(); } /** <inheritDoc /> */ public IClusterMetrics GetMetrics() { if (_pred == null) { return DoInOp(OpMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; }); } return DoOutInOp(OpMetricsFiltered, writer => { WriteEnumerable(writer, GetNodes().Select(node => node.Id)); }, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; }); } /** <inheritDoc /> */ public IMessaging GetMessaging() { return _msg.Value; } /** <inheritDoc /> */ public IEvents GetEvents() { return _events.Value; } /** <inheritDoc /> */ public IServices GetServices() { return _services.Value; } /// <summary> /// Pings a remote node. /// </summary> /// <param name="nodeId">ID of a node to ping.</param> /// <returns>True if node for a given ID is alive, false otherwise.</returns> internal bool PingNode(Guid nodeId) { return DoOutOp(OpPingNode, nodeId) == True; } /// <summary> /// Predicate (if any). /// </summary> public Func<IClusterNode, bool> Predicate { get { return _pred; } } /// <summary> /// Refresh cluster node metrics. /// </summary> /// <param name="nodeId">Node</param> /// <param name="lastUpdateTime"></param> /// <returns></returns> internal ClusterMetricsImpl RefreshClusterNodeMetrics(Guid nodeId, long lastUpdateTime) { return DoOutInOp(OpNodeMetrics, writer => { writer.WriteGuid(nodeId); writer.WriteLong(lastUpdateTime); }, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return reader.ReadBoolean() ? new ClusterMetricsImpl(reader) : null; } ); } /// <summary> /// Gets a topology by version. Returns null if topology history storage doesn't contain /// specified topology version (history currently keeps the last 1000 snapshots). /// </summary> /// <param name="version">Topology version.</param> /// <returns>Collection of Ignite nodes which represented by specified topology version, /// if it is present in history storage, {@code null} otherwise.</returns> /// <exception cref="IgniteException">If underlying SPI implementation does not support /// topology history. Currently only {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi} /// supports topology history.</exception> internal ICollection<IClusterNode> Topology(long version) { return DoOutInOp(OpTopology, writer => writer.WriteLong(version), input => IgniteUtils.ReadNodes(Marshaller.StartUnmarshal(input))); } /// <summary> /// Topology version. /// </summary> internal long TopologyVersion { get { RefreshNodes(); return Interlocked.Read(ref _topVer); } } /// <summary> /// Update topology. /// </summary> /// <param name="newTopVer">New topology version.</param> /// <param name="newNodes">New nodes.</param> internal void UpdateTopology(long newTopVer, List<IClusterNode> newNodes) { lock (this) { // If another thread already advanced topology version further, we still // can safely return currently received nodes, but we will not assign them. if (_topVer < newTopVer) { Interlocked.Exchange(ref _topVer, newTopVer); _nodes = newNodes.AsReadOnly(); } } } /// <summary> /// Get current nodes without refreshing the topology. /// </summary> /// <returns>Current nodes.</returns> internal IList<IClusterNode> NodesNoRefresh() { return _nodes; } /// <summary> /// Resets the metrics. /// </summary> public void ResetMetrics() { DoOutInOp(OpResetMetrics); } /// <summary> /// Resets the lost partitions. /// </summary> public void ResetLostPartitions(IEnumerable<string> cacheNames) { IgniteArgumentCheck.NotNull(cacheNames, "cacheNames"); DoOutOp(OpResetLostPartitions, w => { var pos = w.Stream.Position; var count = 0; w.WriteInt(count); // Reserve space. foreach (var cacheName in cacheNames) { w.WriteString(cacheName); count++; } w.Stream.WriteInt(pos, count); }); } /// <summary> /// Gets the cache metrics within this cluster group. /// </summary> /// <param name="cacheName">Name of the cache.</param> /// <returns>Metrics.</returns> public ICacheMetrics GetCacheMetrics(string cacheName) { return DoOutInOp(OpCacheMetrics, w => w.WriteString(cacheName), stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /// <summary> /// Gets the memory metrics. /// </summary> public ICollection<IMemoryMetrics> GetMemoryMetrics() { return DoInOp(OpMemoryMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); var cnt = reader.ReadInt(); var res = new List<IMemoryMetrics>(cnt); for (int i = 0; i < cnt; i++) { res.Add(new MemoryMetrics(reader)); } return res; }); } /// <summary> /// Gets the memory metrics. /// </summary> public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName) { return DoOutInOp(OpMemoryMetricsByName, w => w.WriteString(memoryPolicyName), stream => stream.ReadBool() ? new MemoryMetrics(Marshaller.StartUnmarshal(stream, false)) : null); } /// <summary> /// Creates new Cluster Group from given native projection. /// </summary> /// <param name="prj">Native projection.</param> /// <returns>New cluster group.</returns> private IClusterGroup GetClusterGroup(IUnmanagedTarget prj) { return new ClusterGroupImpl(_proc, prj, Marshaller, _ignite, _pred); } /// <summary> /// Refresh projection nodes. /// </summary> /// <returns>Nodes.</returns> private IList<IClusterNode> RefreshNodes() { long oldTopVer = Interlocked.Read(ref _topVer); List<IClusterNode> newNodes = null; DoOutInOp(OpNodes, writer => { writer.WriteLong(oldTopVer); }, input => { BinaryReader reader = Marshaller.StartUnmarshal(input); if (reader.ReadBoolean()) { // Topology has been updated. long newTopVer = reader.ReadLong(); newNodes = IgniteUtils.ReadNodes(reader, _pred); UpdateTopology(newTopVer, newNodes); } }); if (newNodes != null) return newNodes; // No topology changes. Debug.Assert(_nodes != null, "At least one topology update should have occurred."); return _nodes; } } }
// 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 Android.App; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Drawing; namespace ArcGISRuntime.Samples.SurfacePlacements { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Surface placement", category: "GraphicsOverlay", description: "Position graphics relative to a surface using different surface placement modes.", instructions: "The application loads a scene showing four points that use individual surface placement modes (Absolute, Relative, Relative to Scene, and either Draped Billboarded or Draped Flat). Use the toggle to change the draped mode and the slider to dynamically adjust the Z value of the graphics. Explore the scene by zooming in/out and by panning around to observe the effects of the surface placement rules.", tags: new[] { "3D", "absolute", "altitude", "draped", "elevation", "floating", "relative", "scenes", "sea level", "surface placement", "Featured" })] [Shared.Attributes.AndroidLayout("FindFeaturesUtilityNetwork.xml")] public class SurfacePlacements : Activity { // Hold references to UI elements. private SceneView _mySceneView; private RadioButton _billboardedButton; private RadioButton _flatButton; private SeekBar _zSlider; private TextView _zLabel; // Draped overlays. private GraphicsOverlay _drapedBillboardedOverlay; private GraphicsOverlay _drapedFlatOverlay; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Surface placement"; CreateLayout(); Initialize(); } private void Initialize() { // Create new Scene. Scene myScene = new Scene { // Set the Scene's basemap property. Basemap = new Basemap(BasemapStyle.ArcGISImageryStandard) }; // Create a camera with coordinates showing layer data. Camera camera = new Camera(48.389124348393182, -4.4595173327138591, 140, 322, 74, 0); // Assign the Scene to the SceneView. _mySceneView.Scene = myScene; // Create ElevationSource from elevation data Uri. ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource( new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")); // Create scene layer from the Brest, France scene server. var sceneLayer = new ArcGISSceneLayer(new Uri("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Buildings_Brest/SceneServer")); _mySceneView.Scene.OperationalLayers.Add(sceneLayer); // Add elevationSource to BaseSurface's ElevationSources. _mySceneView.Scene.BaseSurface.ElevationSources.Add(elevationSource); // Set view point of scene view using camera. _mySceneView.SetViewpointCameraAsync(camera); // Create overlays with elevation modes. _drapedBillboardedOverlay = new GraphicsOverlay(); _drapedBillboardedOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.DrapedBillboarded; _mySceneView.GraphicsOverlays.Add(_drapedBillboardedOverlay); _drapedFlatOverlay = new GraphicsOverlay(); _drapedFlatOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.DrapedFlat; GraphicsOverlay relativeToSceneOverlay = new GraphicsOverlay(); relativeToSceneOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.RelativeToScene; _mySceneView.GraphicsOverlays.Add(relativeToSceneOverlay); GraphicsOverlay relativeToSurfaceOverlay = new GraphicsOverlay(); relativeToSurfaceOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Relative; _mySceneView.GraphicsOverlays.Add(relativeToSurfaceOverlay); GraphicsOverlay absoluteOverlay = new GraphicsOverlay(); absoluteOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Absolute; _mySceneView.GraphicsOverlays.Add(absoluteOverlay); // Create point for graphic location. MapPoint sceneRelatedPoint = new MapPoint(-4.4610562, 48.3902727, 70, camera.Location.SpatialReference); MapPoint surfaceRelatedPoint = new MapPoint(-4.4609257, 48.3903965, 70, camera.Location.SpatialReference); // Create a red triangle symbol. var triangleSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Triangle, Color.FromArgb(255, 255, 0, 0), 10); // Create a text symbol for each elevation mode. TextSymbol drapedBillboardedText = new TextSymbol("DRAPED BILLBOARDED", Color.FromArgb(255, 0, 0, 255), 10, Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center, Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle); drapedBillboardedText.OffsetY += 20; TextSymbol drapedFlatText = new TextSymbol("DRAPED FLAT", Color.FromArgb(255, 0, 0, 255), 10, Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center, Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle); drapedFlatText.OffsetY += 20; TextSymbol relativeToSurfaceText = new TextSymbol("RELATIVE TO SURFACE", Color.FromArgb(255, 0, 0, 255), 10, Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center, Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle); relativeToSurfaceText.OffsetY += 20; TextSymbol relativeToSceneText = new TextSymbol("RELATIVE TO SCENE", Color.FromArgb(255, 0, 0, 255), 10, Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center, Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle); relativeToSceneText.OffsetY -= 20; TextSymbol absoluteText = new TextSymbol("ABSOLUTE", Color.FromArgb(255, 0, 0, 255), 10, Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center, Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle); absoluteText.OffsetY += 20; // Add the point graphic and text graphic to the corresponding graphics overlay. _drapedBillboardedOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol)); _drapedBillboardedOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, drapedBillboardedText)); _drapedFlatOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol)); _drapedFlatOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, drapedFlatText)); relativeToSceneOverlay.Graphics.Add(new Graphic(sceneRelatedPoint, triangleSymbol)); relativeToSceneOverlay.Graphics.Add(new Graphic(sceneRelatedPoint, relativeToSceneText)); relativeToSurfaceOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol)); relativeToSurfaceOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, relativeToSurfaceText)); absoluteOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol)); absoluteOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, absoluteText)); absoluteOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, absoluteText)); } private void SetBillboarded(object sender, EventArgs e) { _mySceneView.GraphicsOverlays.Remove(_drapedFlatOverlay); _mySceneView.GraphicsOverlays.Add(_drapedBillboardedOverlay); } private void SetFlat(object sender, EventArgs e) { _mySceneView.GraphicsOverlays.Remove(_drapedBillboardedOverlay); _mySceneView.GraphicsOverlays.Add(_drapedFlatOverlay); } private void ZValueChanged(object sender, SeekBar.ProgressChangedEventArgs e) { foreach (GraphicsOverlay overlay in _mySceneView.GraphicsOverlays) { foreach (Graphic graphic in overlay.Graphics) { graphic.Geometry = GeometryEngine.SetZ(graphic.Geometry, _zSlider.Progress); } } _zLabel.Text = $"{_zSlider.Progress} meters"; } private void CreateLayout() { // Create a new layout for the app. SetContentView(Resource.Layout.SurfacePlacements); _mySceneView = FindViewById<SceneView>(Resource.Id.SceneView); _billboardedButton = FindViewById<RadioButton>(Resource.Id.billboardedButton); _flatButton = FindViewById<RadioButton>(Resource.Id.flatButton); _zSlider = FindViewById<SeekBar>(Resource.Id.Slider); _zLabel = FindViewById<TextView>(Resource.Id.ValueLabel); _billboardedButton.Click += SetBillboarded; _flatButton.Click += SetFlat; _zSlider.ProgressChanged += ZValueChanged; } protected override void OnDestroy() { base.OnDestroy(); // Remove the sceneview (_mySceneView.Parent as ViewGroup).RemoveView(_mySceneView); _mySceneView.Dispose(); _mySceneView = null; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Contoso.Provisioning.OneDriveWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green ([email protected]) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using Redzen.Numerics.Distributions; using SharpNeat.Network; namespace SharpNeat.Genomes.Neat { /// <summary> /// Represents parameters specific to NEAT genomes. E.g. parameters that describe probabilities /// for the different types of mutation and the proportion of possible connections to instantiate /// between input and output neurons within the initial population. /// </summary> public class NeatGenomeParameters { #region Constants const double DefaultConnectionWeightRange = 5.0; const double DefaultInitialInterconnectionsProportion = 0.05; const double DefaultDisjointExcessGenesRecombineProbability = 0.1; // High level mutation probabilities const double DefaultConnectionWeightMutationProbability = 0.94; const double DefaultAddNodeMutationProbability = 0.01; const double DefaultAddConnectionMutationProbability = 0.025; const double DefaultNodeAuxStateMutationProbability = 0.00; const double DefaultDeleteConnectionMutationProbability = 0.025; #endregion #region Instance Fields bool _feedforwardOnly; IActivationFunction _activationFn; double _connectionWeightRange; double _initialInterconnectionsProportion; double _disjointExcessGenesRecombineProbability; // High level mutation probabilities. double _connectionWeightMutationProbability; double _addNodeMutationProbability; double _addConnectionMutationProbability; double _nodeAuxStateMutationProbability; double _deleteConnectionMutationProbability; // RouletteWheelLayout representing the above five mutation probabilities. DiscreteDistribution _rouletteWheelLayout; // Alternative RouletteWheelLayout used when we wish to avoid deletion mutations, e.g. when // mutating a genome with just one connection. DiscreteDistribution _rouletteWheelLayoutNonDestructive; /// <summary> /// A list of ConnectionMutationInfo objects that drives the types of connection mutation /// that occur. /// </summary> ConnectionMutationInfoList _connectionMutationInfoList; // The fitness history length to be used by genomes when recording their fitness int _fitnessHistoryLength; #endregion #region Constructors /// <summary> /// Construct with default set of parameters. /// </summary> public NeatGenomeParameters() { _activationFn = LogisticFunctionSteep.__DefaultInstance; _connectionWeightRange = DefaultConnectionWeightRange; _initialInterconnectionsProportion = DefaultInitialInterconnectionsProportion; _disjointExcessGenesRecombineProbability = DefaultDisjointExcessGenesRecombineProbability; _connectionWeightMutationProbability = DefaultConnectionWeightMutationProbability; _addNodeMutationProbability = DefaultAddNodeMutationProbability; _addConnectionMutationProbability = DefaultAddConnectionMutationProbability; _nodeAuxStateMutationProbability = DefaultNodeAuxStateMutationProbability; _deleteConnectionMutationProbability = DefaultDeleteConnectionMutationProbability; _rouletteWheelLayout = CreateRouletteWheelLayout(); _rouletteWheelLayoutNonDestructive = CreateRouletteWheelLayout_NonDestructive(); // Create a connection weight mutation scheme. _connectionMutationInfoList = CreateConnectionWeightMutationScheme_Default(); // No fitness history. _fitnessHistoryLength = 0; } /// <summary> /// Copy constructor. /// </summary> public NeatGenomeParameters(NeatGenomeParameters copyFrom) { _feedforwardOnly = copyFrom._feedforwardOnly; _activationFn = copyFrom._activationFn; _connectionWeightRange = copyFrom._connectionWeightRange; _initialInterconnectionsProportion = copyFrom._initialInterconnectionsProportion; _disjointExcessGenesRecombineProbability = copyFrom._disjointExcessGenesRecombineProbability; _connectionWeightMutationProbability = copyFrom._connectionWeightMutationProbability; _addNodeMutationProbability = copyFrom._addNodeMutationProbability; _addConnectionMutationProbability = copyFrom._addConnectionMutationProbability; _nodeAuxStateMutationProbability = copyFrom._nodeAuxStateMutationProbability; _deleteConnectionMutationProbability = copyFrom._deleteConnectionMutationProbability; _rouletteWheelLayout = new DiscreteDistribution((double[])copyFrom._rouletteWheelLayout.Probabilities.Clone()); _rouletteWheelLayoutNonDestructive = new DiscreteDistribution((double[])copyFrom._rouletteWheelLayoutNonDestructive.Probabilities.Clone()); _connectionMutationInfoList = new ConnectionMutationInfoList(copyFrom._connectionMutationInfoList); _connectionMutationInfoList.Initialize(); _fitnessHistoryLength = copyFrom._fitnessHistoryLength; } #endregion #region Properties // TODO: rename to AcyclicOnly? /// <summary> /// Gets or sets a boolean that indicates if NEAT should produce only feed-forward networks (no recurrent/cyclic connection paths). /// </summary> public bool FeedforwardOnly { get { return _feedforwardOnly; } set { _feedforwardOnly = value; } } /// <summary> /// Gets or sets the neuron activation function to use in evolved networks. NEAT uses the same activation /// function at each node. /// </summary> public IActivationFunction ActivationFn { get { return _activationFn; } set { _activationFn = value; } } /// <summary> /// Gets or sets the connection weight range to use in NEAT genomes. E.g. a value of 5 defines a weight range /// of -5 to 5. The weight range is strictly enforced - e.g. when creating new connections and mutating /// existing ones. /// </summary> public double ConnectionWeightRange { get { return _connectionWeightRange; } set { _connectionWeightRange = value; } } /// <summary> /// Gets or sets a proportion that specifies the number of interconnections to make between input and /// output neurons in an initial random population. This is a proportion of the total number of /// possible interconnections. /// </summary> public double InitialInterconnectionsProportion { get { return _initialInterconnectionsProportion; } set { _initialInterconnectionsProportion = value; } } /// <summary> /// Gets or sets the probability that all excess and disjoint genes are copied into an offspring genome /// during sexual reproduction. Currently the excess/disjoint genes are copied in an all or nothing strategy. /// </summary> public double DisjointExcessGenesRecombinedProbability { get { return _disjointExcessGenesRecombineProbability; } set { _disjointExcessGenesRecombineProbability = value; } } /// <summary> /// Gets or sets the probability that a genome mutation operates on genome connection weights. /// </summary> public double ConnectionWeightMutationProbability { get { return _connectionWeightMutationProbability; } set { _connectionWeightMutationProbability = value; _rouletteWheelLayout = CreateRouletteWheelLayout(); _rouletteWheelLayoutNonDestructive = CreateRouletteWheelLayout_NonDestructive(); } } /// <summary> /// Gets or sets the probability that a genome mutation is an 'add node' mutation. /// </summary> public double AddNodeMutationProbability { get { return _addNodeMutationProbability; } set { _addNodeMutationProbability = value; _rouletteWheelLayout = CreateRouletteWheelLayout(); _rouletteWheelLayoutNonDestructive = CreateRouletteWheelLayout_NonDestructive(); } } /// <summary> /// Gets or sets the probability that a genome mutation is an 'add connection' mutation. /// </summary> public double AddConnectionMutationProbability { get { return _addConnectionMutationProbability; } set { _addConnectionMutationProbability = value; _rouletteWheelLayout = CreateRouletteWheelLayout(); _rouletteWheelLayoutNonDestructive = CreateRouletteWheelLayout_NonDestructive(); } } /// <summary> /// Gets or sets the probability that a genome mutation is a 'node auxiliary state' mutation. /// </summary> public double NodeAuxStateMutationProbability { get { return _nodeAuxStateMutationProbability; } set { _nodeAuxStateMutationProbability = value; _rouletteWheelLayout = CreateRouletteWheelLayout(); _rouletteWheelLayoutNonDestructive = CreateRouletteWheelLayout_NonDestructive(); } } /// <summary> /// Gets or sets the probability that a genome mutation is a 'delete connection' mutation. /// </summary> public double DeleteConnectionMutationProbability { get { return _deleteConnectionMutationProbability; } set { _deleteConnectionMutationProbability = value; _rouletteWheelLayout = CreateRouletteWheelLayout(); _rouletteWheelLayoutNonDestructive = CreateRouletteWheelLayout_NonDestructive(); } } /// <summary> /// Gets a RouletteWheelLayout that represents the probabilities of each type of genome mutation. /// </summary> public DiscreteDistribution RouletteWheelLayout { get { return _rouletteWheelLayout; } } /// <summary> /// Gets an alternative RouletteWheelLayout for use when we wish to avoid deletion mutations, /// e.g. when mutating a genome with just one connection. /// </summary> public DiscreteDistribution RouletteWheelLayoutNonDestructive { get { return _rouletteWheelLayoutNonDestructive; } } /// <summary> /// Gets a list of ConnectionMutationInfo objects that drives the types of connection mutation /// that occur. /// </summary> public ConnectionMutationInfoList ConnectionMutationInfoList { get { return _connectionMutationInfoList; } } /// <summary> /// Gets or sets the fitness history length to be used by genomes when recording their fitness. /// </summary> public int FitnessHistoryLength { get { return _fitnessHistoryLength; } set { _fitnessHistoryLength = value; } } #endregion #region Private Methods private DiscreteDistribution CreateRouletteWheelLayout() { double[] probabilities = new double[] { _connectionWeightMutationProbability, _addNodeMutationProbability, _addConnectionMutationProbability, _nodeAuxStateMutationProbability, _deleteConnectionMutationProbability }; return new DiscreteDistribution(probabilities); } private DiscreteDistribution CreateRouletteWheelLayout_NonDestructive() { double[] probabilities = new double[] { _connectionWeightMutationProbability, _addNodeMutationProbability, _addConnectionMutationProbability, _nodeAuxStateMutationProbability }; return new DiscreteDistribution(probabilities); } /// <summary> /// Returns the default connection weight mutation scheme. /// </summary> private ConnectionMutationInfoList CreateConnectionWeightMutationScheme_Default() { ConnectionMutationInfoList list = new ConnectionMutationInfoList(6); // Gaussian jiggle with sigma=0.01 (most values between +-0.02) // Jiggle 1,2 and 3 connections respectively. list.Add(new ConnectionMutationInfo(0.5985, ConnectionPerturbanceType.JiggleGaussian, ConnectionSelectionType.FixedQuantity, 0.0, 1, 0.0, 0.01)); list.Add(new ConnectionMutationInfo(0.2985, ConnectionPerturbanceType.JiggleGaussian, ConnectionSelectionType.FixedQuantity, 0.0, 2, 0.0, 0.01)); list.Add(new ConnectionMutationInfo(0.0985, ConnectionPerturbanceType.JiggleGaussian, ConnectionSelectionType.FixedQuantity, 0.0, 3, 0.0, 0.01)); // Reset mutations. 1, 2 and 3 connections respectively. list.Add(new ConnectionMutationInfo(0.015, ConnectionPerturbanceType.Reset, ConnectionSelectionType.FixedQuantity, 0.0, 1, 0.0, 0)); list.Add(new ConnectionMutationInfo(0.015, ConnectionPerturbanceType.Reset, ConnectionSelectionType.FixedQuantity, 0.0, 2, 0.0, 0)); list.Add(new ConnectionMutationInfo(0.015, ConnectionPerturbanceType.Reset, ConnectionSelectionType.FixedQuantity, 0.0, 3, 0.0, 0)); list.Initialize(); return list; } /// <summary> /// Returns the connection weight mutation scheme from SharpNEAT version 1.x /// </summary> private ConnectionMutationInfoList CreateConnectionWeightMutationScheme_SharpNEAT1() { ConnectionMutationInfoList list = new ConnectionMutationInfoList(5); list.Add(new ConnectionMutationInfo(0.125, ConnectionPerturbanceType.JiggleUniform, ConnectionSelectionType.Proportional, 0.5, 0, 0.05, 0.0)); list.Add(new ConnectionMutationInfo(0.125, ConnectionPerturbanceType.JiggleUniform, ConnectionSelectionType.Proportional, 0.1, 0, 0.05, 0.0)); list.Add(new ConnectionMutationInfo(0.125, ConnectionPerturbanceType.JiggleUniform, ConnectionSelectionType.FixedQuantity, 0.0, 1, 0.05, 0.0)); list.Add(new ConnectionMutationInfo(0.5, ConnectionPerturbanceType.Reset, ConnectionSelectionType.Proportional, 0.1, 0, 0.0, 0.0)); list.Add(new ConnectionMutationInfo(0.125, ConnectionPerturbanceType.Reset, ConnectionSelectionType.FixedQuantity, 0.0, 1, 0.0, 0.0)); list.Initialize(); return list; } #endregion #region Static Factory Methods /// <summary> /// Creates parameters suitable for use during the simplifying mode of a NEAT search. Addition /// mutations are disabled, deletion and weight mutation rates are increased. /// </summary> public static NeatGenomeParameters CreateSimplifyingParameters(NeatGenomeParameters copyFrom) { NeatGenomeParameters newParams = new NeatGenomeParameters(copyFrom); newParams._connectionWeightMutationProbability = 0.6; newParams._addNodeMutationProbability = 0.0; newParams._addConnectionMutationProbability = 0.0; // TODO: better method for automatically generating simplifying parameters? newParams._nodeAuxStateMutationProbability = copyFrom._nodeAuxStateMutationProbability; newParams._deleteConnectionMutationProbability = 0.4; newParams._rouletteWheelLayout = newParams.CreateRouletteWheelLayout(); newParams._rouletteWheelLayoutNonDestructive = newParams.CreateRouletteWheelLayout_NonDestructive(); newParams._connectionMutationInfoList = new ConnectionMutationInfoList(copyFrom._connectionMutationInfoList); // SharpNEAT version 1.x used this scheme. // newParams._connectionMutationInfoList.Add(new ConnectionMutationInfo(0.333, ConnectionPerturbanceType.JiggleUniform, ConnectionSelectionType.Proportional, 0.3, 0, 0.05, 0.0)); // newParams._connectionMutationInfoList.Add(new ConnectionMutationInfo(0.333, ConnectionPerturbanceType.JiggleUniform, ConnectionSelectionType.Proportional, 0.1, 0, 0.05, 0.0)); // newParams._connectionMutationInfoList.Add(new ConnectionMutationInfo(0.333, ConnectionPerturbanceType.JiggleUniform, ConnectionSelectionType.Proportional, 0.01, 0, 0.05, 0.0)); newParams._connectionMutationInfoList.Initialize(); return newParams; } #endregion } }
namespace DecelerationLaserLock { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.parkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.lockToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.unlockToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.textBox1 = new System.Windows.Forms.TextBox(); this.controlVoltageNumericEditor = new NationalInstruments.UI.WindowsForms.NumericEdit(); this.label1 = new System.Windows.Forms.Label(); this.LockCheck = new System.Windows.Forms.CheckBox(); this.gainGroupBox = new System.Windows.Forms.GroupBox(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.speedSwitch = new NationalInstruments.UI.WindowsForms.Switch(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.dLabel = new System.Windows.Forms.Label(); this.iLabel = new System.Windows.Forms.Label(); this.pLabel = new System.Windows.Forms.Label(); this.slopeSwitch = new NationalInstruments.UI.WindowsForms.Switch(); this.dSlider = new NationalInstruments.UI.WindowsForms.Slide(); this.iSlider = new NationalInstruments.UI.WindowsForms.Slide(); this.pSlider = new NationalInstruments.UI.WindowsForms.Slide(); this.deviationGraph = new NationalInstruments.UI.WindowsForms.WaveformGraph(); this.waveformPlot1 = new NationalInstruments.UI.WaveformPlot(); this.xAxis1 = new NationalInstruments.UI.XAxis(); this.yAxis1 = new NationalInstruments.UI.YAxis(); this.label2 = new System.Windows.Forms.Label(); this.setpointNumericEdit = new NationalInstruments.UI.WindowsForms.NumericEdit(); this.scanNumberBox = new System.Windows.Forms.NumericUpDown(); this.label7 = new System.Windows.Forms.Label(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.controlVoltageNumericEditor)).BeginInit(); this.gainGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.speedSwitch)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.slopeSwitch)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dSlider)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.iSlider)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pSlider)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.deviationGraph)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.setpointNumericEdit)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.scanNumberBox)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem1}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(653, 24); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; // // toolStripMenuItem1 // this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.parkToolStripMenuItem, this.lockToolStripMenuItem, this.unlockToolStripMenuItem}); this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(54, 20); this.toolStripMenuItem1.Text = "Actions"; // // parkToolStripMenuItem // this.parkToolStripMenuItem.Name = "parkToolStripMenuItem"; this.parkToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.parkToolStripMenuItem.Text = "Park"; this.parkToolStripMenuItem.Click += new System.EventHandler(this.parkToolStripMenuItem_Click); // // lockToolStripMenuItem // this.lockToolStripMenuItem.Name = "lockToolStripMenuItem"; this.lockToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.lockToolStripMenuItem.Text = "Lock"; this.lockToolStripMenuItem.Click += new System.EventHandler(this.lockToolStripMenuItem_Click); // // unlockToolStripMenuItem // this.unlockToolStripMenuItem.Name = "unlockToolStripMenuItem"; this.unlockToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.unlockToolStripMenuItem.Text = "Unlock"; this.unlockToolStripMenuItem.Click += new System.EventHandler(this.unlockToolStripMenuItem_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(6, 227); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox1.Size = new System.Drawing.Size(640, 53); this.textBox1.TabIndex = 3; // // controlVoltageNumericEditor // this.controlVoltageNumericEditor.CoercionInterval = 0.005; this.controlVoltageNumericEditor.FormatMode = NationalInstruments.UI.NumericFormatMode.CreateSimpleDoubleMode(3); this.controlVoltageNumericEditor.Location = new System.Drawing.Point(91, 26); this.controlVoltageNumericEditor.Name = "controlVoltageNumericEditor"; this.controlVoltageNumericEditor.OutOfRangeMode = NationalInstruments.UI.NumericOutOfRangeMode.CoerceToRange; this.controlVoltageNumericEditor.Range = new NationalInstruments.UI.Range(-10, 10); this.controlVoltageNumericEditor.Size = new System.Drawing.Size(61, 20); this.controlVoltageNumericEditor.TabIndex = 4; this.controlVoltageNumericEditor.AfterChangeValue += new NationalInstruments.UI.AfterChangeNumericValueEventHandler(this.controlVoltageNumericEditor_AfterChangeValue); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(158, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(79, 13); this.label1.TabIndex = 5; this.label1.Text = "Control Voltage"; // // LockCheck // this.LockCheck.AutoSize = true; this.LockCheck.Location = new System.Drawing.Point(12, 29); this.LockCheck.Name = "LockCheck"; this.LockCheck.Size = new System.Drawing.Size(62, 17); this.LockCheck.TabIndex = 6; this.LockCheck.Text = "Locked"; this.LockCheck.UseVisualStyleBackColor = true; this.LockCheck.CheckedChanged += new System.EventHandler(this.lockCheck_CheckedChanged); // // gainGroupBox // this.gainGroupBox.Controls.Add(this.label6); this.gainGroupBox.Controls.Add(this.label5); this.gainGroupBox.Controls.Add(this.speedSwitch); this.gainGroupBox.Controls.Add(this.label3); this.gainGroupBox.Controls.Add(this.label4); this.gainGroupBox.Controls.Add(this.dLabel); this.gainGroupBox.Controls.Add(this.iLabel); this.gainGroupBox.Controls.Add(this.pLabel); this.gainGroupBox.Controls.Add(this.slopeSwitch); this.gainGroupBox.Controls.Add(this.dSlider); this.gainGroupBox.Controls.Add(this.iSlider); this.gainGroupBox.Controls.Add(this.pSlider); this.gainGroupBox.Location = new System.Drawing.Point(473, 27); this.gainGroupBox.Name = "gainGroupBox"; this.gainGroupBox.Size = new System.Drawing.Size(173, 193); this.gainGroupBox.TabIndex = 7; this.gainGroupBox.TabStop = false; this.gainGroupBox.Text = "Gain settings"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(9, 94); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(30, 13); this.label6.TabIndex = 14; this.label6.Text = "Slow"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(10, 38); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(27, 13); this.label5.TabIndex = 13; this.label5.Text = "Fast"; // // speedSwitch // this.speedSwitch.Location = new System.Drawing.Point(8, 49); this.speedSwitch.Name = "speedSwitch"; this.speedSwitch.OffColor = System.Drawing.SystemColors.InactiveCaption; this.speedSwitch.OnColor = System.Drawing.SystemColors.ActiveCaption; this.speedSwitch.Size = new System.Drawing.Size(26, 48); this.speedSwitch.SwitchStyle = NationalInstruments.UI.SwitchStyle.VerticalSlide; this.speedSwitch.TabIndex = 12; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 116); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(25, 13); this.label3.TabIndex = 10; this.label3.Text = "Pos"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(12, 173); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(27, 13); this.label4.TabIndex = 11; this.label4.Text = "Neg"; // // dLabel // this.dLabel.AutoSize = true; this.dLabel.Location = new System.Drawing.Point(146, 16); this.dLabel.Name = "dLabel"; this.dLabel.Size = new System.Drawing.Size(15, 13); this.dLabel.TabIndex = 5; this.dLabel.Text = "D"; // // iLabel // this.iLabel.AutoSize = true; this.iLabel.Location = new System.Drawing.Point(104, 16); this.iLabel.Name = "iLabel"; this.iLabel.Size = new System.Drawing.Size(10, 13); this.iLabel.TabIndex = 4; this.iLabel.Text = "I"; // // pLabel // this.pLabel.AutoSize = true; this.pLabel.Location = new System.Drawing.Point(57, 16); this.pLabel.Name = "pLabel"; this.pLabel.Size = new System.Drawing.Size(14, 13); this.pLabel.TabIndex = 3; this.pLabel.Text = "P"; // // slopeSwitch // this.slopeSwitch.Location = new System.Drawing.Point(9, 128); this.slopeSwitch.Name = "slopeSwitch"; this.slopeSwitch.OffColor = System.Drawing.SystemColors.GradientInactiveCaption; this.slopeSwitch.OnColor = System.Drawing.SystemColors.GradientActiveCaption; this.slopeSwitch.Size = new System.Drawing.Size(26, 48); this.slopeSwitch.SwitchStyle = NationalInstruments.UI.SwitchStyle.VerticalSlide; this.slopeSwitch.TabIndex = 8; // // dSlider // this.dSlider.CoercionInterval = 0.1; this.dSlider.InteractionMode = ((NationalInstruments.UI.LinearNumericPointerInteractionModes)(((NationalInstruments.UI.LinearNumericPointerInteractionModes.DragPointer | NationalInstruments.UI.LinearNumericPointerInteractionModes.SnapPointer) | NationalInstruments.UI.LinearNumericPointerInteractionModes.EditRange))); this.dSlider.Location = new System.Drawing.Point(121, 19); this.dSlider.Name = "dSlider"; this.dSlider.PointerColor = System.Drawing.SystemColors.HotTrack; this.dSlider.Size = new System.Drawing.Size(50, 175); this.dSlider.TabIndex = 2; // // iSlider // this.iSlider.CoercionInterval = 0.1; this.iSlider.InteractionMode = ((NationalInstruments.UI.LinearNumericPointerInteractionModes)(((NationalInstruments.UI.LinearNumericPointerInteractionModes.DragPointer | NationalInstruments.UI.LinearNumericPointerInteractionModes.SnapPointer) | NationalInstruments.UI.LinearNumericPointerInteractionModes.EditRange))); this.iSlider.Location = new System.Drawing.Point(78, 19); this.iSlider.Name = "iSlider"; this.iSlider.PointerColor = System.Drawing.SystemColors.HotTrack; this.iSlider.Size = new System.Drawing.Size(50, 175); this.iSlider.TabIndex = 1; this.iSlider.AfterChangeValue += new NationalInstruments.UI.AfterChangeNumericValueEventHandler(this.iSlider_AfterChangeValue); // // pSlider // this.pSlider.CaptionBackColor = System.Drawing.SystemColors.Control; this.pSlider.CaptionForeColor = System.Drawing.SystemColors.ControlText; this.pSlider.CoercionInterval = 0.1; this.pSlider.InteractionMode = ((NationalInstruments.UI.LinearNumericPointerInteractionModes)(((NationalInstruments.UI.LinearNumericPointerInteractionModes.DragPointer | NationalInstruments.UI.LinearNumericPointerInteractionModes.SnapPointer) | NationalInstruments.UI.LinearNumericPointerInteractionModes.EditRange))); this.pSlider.Location = new System.Drawing.Point(33, 19); this.pSlider.Name = "pSlider"; this.pSlider.OutOfRangeMode = NationalInstruments.UI.NumericOutOfRangeMode.CoerceToRange; this.pSlider.PointerColor = System.Drawing.SystemColors.HotTrack; this.pSlider.Size = new System.Drawing.Size(50, 175); this.pSlider.TabIndex = 0; this.pSlider.AfterChangeValue += new NationalInstruments.UI.AfterChangeNumericValueEventHandler(this.pSlider_AfterChangeValue); // // deviationGraph // this.deviationGraph.Location = new System.Drawing.Point(6, 52); this.deviationGraph.Name = "deviationGraph"; this.deviationGraph.Plots.AddRange(new NationalInstruments.UI.WaveformPlot[] { this.waveformPlot1}); this.deviationGraph.Size = new System.Drawing.Size(461, 168); this.deviationGraph.TabIndex = 8; this.deviationGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis1}); this.deviationGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis1}); // // waveformPlot1 // this.waveformPlot1.PointStyle = NationalInstruments.UI.PointStyle.Cross; this.waveformPlot1.XAxis = this.xAxis1; this.waveformPlot1.YAxis = this.yAxis1; // // xAxis1 // this.xAxis1.Mode = NationalInstruments.UI.AxisMode.StripChart; this.xAxis1.Range = new NationalInstruments.UI.Range(0, 100); // // yAxis1 // this.yAxis1.Mode = NationalInstruments.UI.AxisMode.AutoScaleExact; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(322, 30); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(50, 13); this.label2.TabIndex = 10; this.label2.Text = "Set Point"; // // setpointNumericEdit // this.setpointNumericEdit.CoercionInterval = 0.01; this.setpointNumericEdit.FormatMode = NationalInstruments.UI.NumericFormatMode.CreateSimpleDoubleMode(3); this.setpointNumericEdit.Location = new System.Drawing.Point(257, 26); this.setpointNumericEdit.Name = "setpointNumericEdit"; this.setpointNumericEdit.Range = new NationalInstruments.UI.Range(-100, 100); this.setpointNumericEdit.Size = new System.Drawing.Size(59, 20); this.setpointNumericEdit.TabIndex = 11; this.setpointNumericEdit.AfterChangeValue += new NationalInstruments.UI.AfterChangeNumericValueEventHandler(this.setpointNumericEdit_AfterChangeValue); // // scanNumberBox // this.scanNumberBox.Location = new System.Drawing.Point(391, 26); this.scanNumberBox.Name = "scanNumberBox"; this.scanNumberBox.Size = new System.Drawing.Size(38, 20); this.scanNumberBox.TabIndex = 12; this.scanNumberBox.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(430, 30); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(37, 13); this.label7.TabIndex = 13; this.label7.Text = "Scans"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(653, 292); this.Controls.Add(this.label7); this.Controls.Add(this.scanNumberBox); this.Controls.Add(this.setpointNumericEdit); this.Controls.Add(this.label2); this.Controls.Add(this.deviationGraph); this.Controls.Add(this.gainGroupBox); this.Controls.Add(this.LockCheck); this.Controls.Add(this.label1); this.Controls.Add(this.controlVoltageNumericEditor); this.Controls.Add(this.textBox1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.MaximizeBox = false; this.Name = "MainForm"; this.Text = "Laser Lock"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.controlVoltageNumericEditor)).EndInit(); this.gainGroupBox.ResumeLayout(false); this.gainGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.speedSwitch)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.slopeSwitch)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dSlider)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.iSlider)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pSlider)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.deviationGraph)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.setpointNumericEdit)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.scanNumberBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem parkToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem lockToolStripMenuItem; private System.Windows.Forms.TextBox textBox1; private NationalInstruments.UI.WindowsForms.NumericEdit controlVoltageNumericEditor; private System.Windows.Forms.ToolStripMenuItem unlockToolStripMenuItem; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox LockCheck; private System.Windows.Forms.GroupBox gainGroupBox; private NationalInstruments.UI.WindowsForms.Slide pSlider; private NationalInstruments.UI.WindowsForms.Slide dSlider; private NationalInstruments.UI.WindowsForms.Slide iSlider; private System.Windows.Forms.Label pLabel; private System.Windows.Forms.Label dLabel; private System.Windows.Forms.Label iLabel; private NationalInstruments.UI.WindowsForms.Switch slopeSwitch; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private NationalInstruments.UI.WindowsForms.WaveformGraph deviationGraph; private NationalInstruments.UI.WaveformPlot waveformPlot1; private NationalInstruments.UI.XAxis xAxis1; private NationalInstruments.UI.YAxis yAxis1; private System.Windows.Forms.Label label2; private NationalInstruments.UI.WindowsForms.NumericEdit setpointNumericEdit; private NationalInstruments.UI.WindowsForms.Switch speedSwitch; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown scanNumberBox; private System.Windows.Forms.Label label7; } }
using Game; using JetBrains.Annotations; using Mod; using Photon; using Photon.Enums; using UnityEngine; // ReSharper disable once CheckNamespace public class Horse : Photon.MonoBehaviour { private float awayTimer; private TITAN_CONTROLLER controller; public GameObject dust; public GameObject myHero; private Vector3 setPoint; private float speed = 45f; private string State = "idle"; private float timeElapsed; private void crossFade(string aniName, float time) { animation.CrossFade(aniName, time); if (PhotonNetwork.connected && photonView.isMine) { photonView.RPC(Rpc.CrossFade, PhotonTargets.Others, aniName, time); } } private void followed() { if (this.myHero != null) { this.State = "follow"; this.setPoint = this.myHero.transform.position + Vector3.right * Random.Range(-6, 6) + Vector3.forward * Random.Range(-6, 6); this.setPoint.y = this.getHeight(this.setPoint + Vector3.up * 5f); this.awayTimer = 0f; } } private float getHeight(Vector3 pt) { RaycastHit hit; LayerMask mask2 = 1 << LayerMask.NameToLayer("Ground"); if (Physics.Raycast(pt, -Vector3.up, out hit, 1000f, mask2.value)) { return hit.point.y; } return 0f; } public bool IsGrounded() { LayerMask mask = 1 << LayerMask.NameToLayer("Ground"); LayerMask mask2 = 1 << LayerMask.NameToLayer("EnemyBox"); LayerMask mask3 = mask2 | mask; return Physics.Raycast(gameObject.transform.position + Vector3.up * 0.1f, -Vector3.up, 0.3f, mask3.value); } private void LateUpdate() { if (this.myHero == null && photonView.isMine) { PhotonNetwork.Destroy(gameObject); } if (this.State == "mounted") { if (this.myHero == null) { this.unmounted(); return; } this.myHero.transform.position = transform.position + Vector3.up * 1.68f; this.myHero.transform.rotation = transform.rotation; this.myHero.rigidbody.velocity = rigidbody.velocity; if (this.controller.targetDirection != -874f) { gameObject.transform.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, this.controller.targetDirection, 0f), 100f * Time.deltaTime / (rigidbody.velocity.magnitude + 20f)); if (this.controller.isWALKDown) { rigidbody.AddForce(transform.forward * this.speed * 0.6f, ForceMode.Acceleration); if (rigidbody.velocity.magnitude >= this.speed * 0.6f) { rigidbody.AddForce(-this.speed * 0.6f * rigidbody.velocity.normalized, ForceMode.Acceleration); } } else { rigidbody.AddForce(transform.forward * this.speed, ForceMode.Acceleration); if (rigidbody.velocity.magnitude >= this.speed) { rigidbody.AddForce(-this.speed * rigidbody.velocity.normalized, ForceMode.Acceleration); } } if (rigidbody.velocity.magnitude > 8f) { if (!animation.IsPlaying("horse_Run")) { this.crossFade("horse_Run", 0.1f); } if (!this.myHero.animation.IsPlaying("horse_Run")) { this.myHero.GetComponent<HERO>().crossFade("horse_run", 0.1f); } if (!this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = true; photonView.RPC(Rpc.HorseParticles, PhotonTargets.Others, true); } } else { if (!animation.IsPlaying("horse_WALK")) { this.crossFade("horse_WALK", 0.1f); } if (!this.myHero.animation.IsPlaying("horse_idle")) { this.myHero.GetComponent<HERO>().crossFade("horse_idle", 0.1f); } if (this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = false; object[] objArray2 = new object[] { false }; photonView.RPC(Rpc.HorseParticles, PhotonTargets.Others, objArray2); } } } else { this.toIdleAnimation(); if (rigidbody.velocity.magnitude > 15f) { if (!this.myHero.animation.IsPlaying("horse_Run")) { this.myHero.GetComponent<HERO>().crossFade("horse_run", 0.1f); } } else if (!this.myHero.animation.IsPlaying("horse_idle")) { this.myHero.GetComponent<HERO>().crossFade("horse_idle", 0.1f); } } if ((this.controller.isAttackDown || this.controller.isAttackIIDown) && this.IsGrounded()) { rigidbody.AddForce(Vector3.up * 25f, ForceMode.VelocityChange); } } else if (this.State == "follow") { if (this.myHero == null) { this.unmounted(); return; } if (rigidbody.velocity.magnitude > 8f) { if (!animation.IsPlaying("horse_Run")) { this.crossFade("horse_Run", 0.1f); } if (!this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = true; object[] objArray3 = new object[] { true }; photonView.RPC(Rpc.HorseParticles, PhotonTargets.Others, objArray3); } } else { if (!animation.IsPlaying("horse_WALK")) { this.crossFade("horse_WALK", 0.1f); } if (this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = false; object[] objArray4 = new object[] { false }; photonView.RPC(Rpc.HorseParticles, PhotonTargets.Others, objArray4); } } float num = -Mathf.DeltaAngle(FengMath.getHorizontalAngle(transform.position, this.setPoint), gameObject.transform.rotation.eulerAngles.y - 90f); gameObject.transform.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, gameObject.transform.rotation.eulerAngles.y + num, 0f), 200f * Time.deltaTime / (rigidbody.velocity.magnitude + 20f)); if (Vector3.Distance(this.setPoint, transform.position) < 20f) { rigidbody.AddForce(transform.forward * this.speed * 0.7f, ForceMode.Acceleration); if (rigidbody.velocity.magnitude >= this.speed) { rigidbody.AddForce(-this.speed * 0.7f * rigidbody.velocity.normalized, ForceMode.Acceleration); } } else { rigidbody.AddForce(transform.forward * this.speed, ForceMode.Acceleration); if (rigidbody.velocity.magnitude >= this.speed) { rigidbody.AddForce(-this.speed * rigidbody.velocity.normalized, ForceMode.Acceleration); } } this.timeElapsed += Time.deltaTime; if (this.timeElapsed > 0.6f) { this.timeElapsed = 0f; if (Vector3.Distance(this.myHero.transform.position, this.setPoint) > 20f) { this.followed(); } } if (Vector3.Distance(this.myHero.transform.position, transform.position) < 5f) { this.unmounted(); } if (Vector3.Distance(this.setPoint, transform.position) < 5f) { this.unmounted(); } this.awayTimer += Time.deltaTime; if (this.awayTimer > 6f) { this.awayTimer = 0f; LayerMask mask2 = 1 << LayerMask.NameToLayer("Ground"); if (Physics.Linecast(transform.position + Vector3.up, this.myHero.transform.position + Vector3.up, mask2.value)) { transform.position = new Vector3(this.myHero.transform.position.x, this.getHeight(this.myHero.transform.position + Vector3.up * 5f), this.myHero.transform.position.z); } } } else if (this.State == "idle") { this.toIdleAnimation(); if (this.myHero != null && Vector3.Distance(this.myHero.transform.position, transform.position) > 20f) { this.followed(); } } rigidbody.AddForce(new Vector3(0f, -50f * rigidbody.mass, 0f)); } public void mounted() { this.State = "mounted"; gameObject.GetComponent<TITAN_CONTROLLER>().enabled = true; } [RPC] [UsedImplicitly] private void NetCrossFade(string aniName, float time) { animation.CrossFade(aniName, time); } [RPC] [UsedImplicitly] private void NetPlayAnimation(string aniName) { animation.Play(aniName); } [RPC] [UsedImplicitly] private void NetPlayAnimationAt(string aniName, float normalizedTime) { animation.Play(aniName); animation[aniName].normalizedTime = normalizedTime; } public void playAnimation(string aniName) { animation.Play(aniName); if (PhotonNetwork.connected && photonView.isMine) { photonView.RPC(Rpc.PlayAnimation, PhotonTargets.Others, aniName); } } private void playAnimationAt(string aniName, float normalizedTime) { animation.Play(aniName); animation[aniName].normalizedTime = normalizedTime; if (PhotonNetwork.connected && photonView.isMine) { photonView.RPC(Rpc.PlayAnimationAt, PhotonTargets.Others, aniName, normalizedTime); } } [RPC] [UsedImplicitly] private void SetDust(bool enable) { if (this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = enable; } } private void Start() { this.controller = gameObject.GetComponent<TITAN_CONTROLLER>(); } private void toIdleAnimation() { if (rigidbody.velocity.magnitude > 0.1f) { if (rigidbody.velocity.magnitude > 15f) { if (!animation.IsPlaying("horse_Run")) { this.crossFade("horse_Run", 0.1f); } if (!this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = true; photonView.RPC(Rpc.HorseParticles, PhotonTargets.Others, true); } } else { if (!animation.IsPlaying("horse_WALK")) { this.crossFade("horse_WALK", 0.1f); } if (this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = false; object[] objArray2 = new object[] { false }; photonView.RPC(Rpc.HorseParticles, PhotonTargets.Others, objArray2); } } } else { if (animation.IsPlaying("horse_idle1") && animation["horse_idle1"].normalizedTime >= 1f) { this.crossFade("horse_idle0", 0.1f); } if (animation.IsPlaying("horse_idle2") && animation["horse_idle2"].normalizedTime >= 1f) { this.crossFade("horse_idle0", 0.1f); } if (animation.IsPlaying("horse_idle3") && animation["horse_idle3"].normalizedTime >= 1f) { this.crossFade("horse_idle0", 0.1f); } if (!animation.IsPlaying("horse_idle0") && !animation.IsPlaying("horse_idle1") && !animation.IsPlaying("horse_idle2") && !animation.IsPlaying("horse_idle3")) { this.crossFade("horse_idle0", 0.1f); } if (animation.IsPlaying("horse_idle0")) { int num = Random.Range(0, 10000); if (num < 10) { this.crossFade("horse_idle1", 0.1f); } else if (num < 20) { this.crossFade("horse_idle2", 0.1f); } else if (num < 30) { this.crossFade("horse_idle3", 0.1f); } } if (this.dust.GetComponent<ParticleSystem>().enableEmission) { this.dust.GetComponent<ParticleSystem>().enableEmission = false; object[] objArray3 = new object[] { false }; photonView.RPC(Rpc.HorseParticles, PhotonTargets.Others, objArray3); } rigidbody.AddForce(-rigidbody.velocity, ForceMode.VelocityChange); } } public void unmounted() { this.State = "idle"; gameObject.GetComponent<TITAN_CONTROLLER>().enabled = false; } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; using System.Runtime.InteropServices; // ERROR: Not supported in C#: OptionDeclaration // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; using Microsoft.VisualBasic.PowerPacks; namespace _4PosBackOffice.NET { internal partial class frmBlockTestCode : System.Windows.Forms.Form { ADODB.Recordset adoPrimaryRS; bool mbChangedByCode; int mvBookMark; bool mbEditFlag; bool mbAddNewFlag; bool mbDataChanged; int gID; int k_posID; bool k_posNew; bool flag; float y; short c; short YY; short x; [DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int BitBlt(int hDestDC, int x, int y, int nWidth, int nHeight, int hSrcDC, int xSrc, int ySrc, int dwRop); System.Drawing.Image obj = new System.Drawing.Bitmap(1, 1); [DllImport("kernel32", EntryPoint = "GetDriveTypeA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int GetDriveType(string nDrive); object[] fox = new object[9]; string usb_drv; string yourdrive; bool CDKey; private byte[] arData; private byte[] arPWord; private short m_intCipher; string LsSection; private void loadLanguage() { //frmBlockTestCode = No Code [4MEAT Registration] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmBlockTestCode.Caption = rsLang("LanguageLayoutLnk_Description"): frmBlockTestCode.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074; //Undo|Checked if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1005; //Next|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //_lbl_5 = No Code [Please type in your 4MEAT CD-Key] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _lbl_5.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_5.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //_lblLabels_1 = No Code [CD Key] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _lblLabels_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmBlockTestCode.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } public void Reset_frmEncStrings() { arData = null; arPWord = null; } private void Form_Initialize_Renamed() { basCryptoProcs.Initial_settings(); Reset_frmEncStrings(); } public bool setupCode() { CDKey = false; System.Windows.Forms.Application.DoEvents(); //For i = 68 To 75 // c = c + 1 // fox(c) = Chr(i) & ":" //Next loadLanguage(); this.ShowDialog(); return CDKey; //Exit Function } private void frmBlockTestCode_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; System.Windows.Forms.Application.DoEvents(); // adoPrimaryRS.Move 0 cmdClose_Click(cmdClose, new System.EventArgs()); break; } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs) { // ERROR: Not supported in C#: OnErrorStatement this.Close(); } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { string lCode = null; string leCode = null; string lPassword = null; ADODB.Recordset rs = default(ADODB.Recordset); short x = 0; CDKey = false; string strSerial = null; string strTmp = null; short intDate = 0; short intYear = 0; short intMonth = 0; string dtDate = null; string dtMonth = null; string dtYear = null; string stPass = null; // clsCryptoAPI //UPGRADE_ISSUE: clsCryptoAPI object was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B85A2A7-FE9F-4FBE-AA0C-CF11AC86A305"' clsCryptoAPI cCrypto = null; if (modRecordSet.openConnection()) { rs = modRecordSet.getRS(ref "SELECT * From Company"); if (rs.RecordCount) { //if old database don't chk secuirty if (rs.Fields.Count <= 55) { CDKey = false; Interaction.MsgBox("You need to download latest 4POS upgrades in order to Register.", MsgBoxStyle.Critical, "4POS"); return; } txtFields.Text = Strings.Trim(Strings.Replace(txtFields.Text, "-", "")); cCrypto = new clsCryptoAPI(); //clsCryptoAPI System.Windows.Forms.Application.DoEvents(); txtFields.Text = Strings.LTrim(txtFields.Text); txtFields.Text = Strings.RTrim(txtFields.Text); txtFields.Text = Strings.Trim(txtFields.Text); //strTmp = cCrypto.ConvertStringFromHex(Left(rs("Company_ResMS"), 6)) //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.ConvertStringFromHex. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' strTmp = cCrypto.ConvertStringFromHex(Strings.Left(txtFields.Text, Strings.Len(txtFields.Text) - 5)); System.Windows.Forms.Application.DoEvents(); //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.StringToByteArray. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' arData = cCrypto.StringToByteArray(strTmp); System.Windows.Forms.Application.DoEvents(); //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.StringToByteArray. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' arPWord = cCrypto.StringToByteArray(Conversion.Val(Strings.Right(txtFields.Text, 5))); System.Windows.Forms.Application.DoEvents(); //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.password. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' cCrypto.PassWord = arPWord; System.Windows.Forms.Application.DoEvents(); //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.InputData. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' cCrypto.InputData = System.Text.UnicodeEncoding.Unicode.GetString(arData); System.Windows.Forms.Application.DoEvents(); // Decrypt the data input from the encrypted text box //If cCrypto.Decrypt(g_intHashType, m_intCipher) Then //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.Decrypt. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' if (cCrypto.Decrypt(2, 1)) { System.Windows.Forms.Application.DoEvents(); //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.OutputData. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' arData = cCrypto.OutputData.Clone(); //UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.ByteArrayToString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' strSerial = cCrypto.ByteArrayToString(arData); } if (Strings.Left(strSerial, 3) == "met") { //Create date password if (Information.IsNumeric(Strings.Mid(strSerial, 4, Strings.Len(strSerial)))) { strSerial = Strings.Mid(strSerial, 4, Strings.Len(strSerial)); intYear = Convert.ToInt16(Strings.Mid(strSerial, 5, 2)); intMonth = Convert.ToInt16(Strings.Mid(strSerial, 3, 2)); intDate = Convert.ToInt16(Strings.Left(strSerial, 2)); if ((intDate / 2) == System.Math.Round(intDate / 2)) { intDate = intDate / 2; } else { goto jumpOut; } if ((intMonth / 3) == System.Math.Round(intMonth / 3)) { intMonth = intMonth / 3; } else { goto jumpOut; } if ((intYear / 4) == System.Math.Round(intYear / 4)) { intYear = intYear / 4; } else { goto jumpOut; } stPass = "20"; if (Strings.Len(Convert.ToString(intYear)) == 1) stPass = stPass + "0" + intYear + "/"; else stPass = stPass + intYear + "/"; if (Strings.Len(Convert.ToString(intMonth)) == 1) stPass = stPass + "0" + intMonth + "/"; else stPass = stPass + intMonth + "/"; if (Strings.Len(Convert.ToString(intDate)) == 1) stPass = stPass + "0" + intDate; else stPass = stPass + intDate; if (Information.IsDate(stPass)) { if (Convert.ToDateTime(stPass) >= (System.Date.FromOADate(DateAndTime.Today.ToOADate() - 31))) { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_ResMS = '" + txtFields.Text + "';"); CDKey = true; } } } else { Interaction.MsgBox("Not a Valid 4MEAT Key!", MsgBoxStyle.Critical); } } else { Interaction.MsgBox("Not a Valid 4MEAT Key!", MsgBoxStyle.Critical); } jumpOut: cCrypto = null; // Free the Crypto class from memory strTmp = new string(Strings.Chr(0), 250); // overwrite data in temp variable //Exit Sub } else { Interaction.MsgBox("Unable to locate the '4POS Application Suite' database.", MsgBoxStyle.Critical, "4POS"); //End } } else { Interaction.MsgBox("Unable to locate the '4POS Application Suite' database.", MsgBoxStyle.Critical, "4POS"); //End } cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); this.Close(); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // BufferBlock.cs // // // A propagator block that provides support for unbounded and bounded FIFO buffers. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Threading.Tasks.Dataflow.Internal; using System.Diagnostics.CodeAnalysis; namespace System.Threading.Tasks.Dataflow { /// <summary>Provides a buffer for storing data.</summary> /// <typeparam name="T">Specifies the type of the data buffered by this dataflow block.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BufferBlock<>.DebugView))] public sealed class BufferBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T>, IDebuggerDisplay { /// <summary>The core logic for the buffer block.</summary> private readonly SourceCore<T> _source; /// <summary>The bounding state for when in bounding mode; null if not bounding.</summary> private readonly BoundingStateWithPostponedAndTask<T> _boundingState; /// <summary>Whether all future messages should be declined on the target.</summary> private bool _targetDecliningPermanently; /// <summary>A task has reserved the right to run the target's completion routine.</summary> private bool _targetCompletionReserved; /// <summary>Gets the lock object used to synchronize incoming requests.</summary> private object IncomingLock { get { return _source; } } /// <summary>Initializes the <see cref="BufferBlock{T}"/>.</summary> public BufferBlock() : this(DataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="BufferBlock{T}"/> with the specified <see cref="DataflowBlockOptions"/>.</summary> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BufferBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BufferBlock(DataflowBlockOptions dataflowBlockOptions) { if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions"); Contract.EndContractBlock(); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Initialize bounding state if necessary Action<ISourceBlock<T>, int> onItemsRemoved = null; if (dataflowBlockOptions.BoundedCapacity > 0) { onItemsRemoved = (owningSource, count) => ((BufferBlock<T>)owningSource).OnItemsRemoved(count); _boundingState = new BoundingStateWithPostponedAndTask<T>(dataflowBlockOptions.BoundedCapacity); } // Initialize the source state _source = new SourceCore<T>(this, dataflowBlockOptions, owningSource => ((BufferBlock<T>)owningSource).Complete(), onItemsRemoved); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BufferBlock<T>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, owningSource => ((BufferBlock<T>)owningSource).Complete(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader"); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, "consumeToAccept"); Contract.EndContractBlock(); lock (IncomingLock) { // If we've already stopped accepting messages, decline permanently if (_targetDecliningPermanently) { CompleteTargetIfPossible(); return DataflowMessageStatus.DecliningPermanently; } // We can directly accept the message if: // 1) we are not bounding, OR // 2) we are bounding AND there is room available AND there are no postponed messages AND we are not currently processing. // (If there were any postponed messages, we would need to postpone so that ordering would be maintained.) // (We should also postpone if we are currently processing, because there may be a race between consuming postponed messages and // accepting new ones directly into the queue.) if (_boundingState == null || (_boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count == 0 && _boundingState.TaskForInputProcessing == null)) { // Consume the message from the source if necessary if (consumeToAccept) { Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true."); bool consumed; messageValue = source.ConsumeMessage(messageHeader, this, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } // Once consumed, pass it to the source _source.AddMessage(messageValue); if (_boundingState != null) _boundingState.CurrentCount++; return DataflowMessageStatus.Accepted; } // Otherwise, we try to postpone if a source was provided else if (source != null) { Debug.Assert(_boundingState != null && _boundingState.PostponedMessages != null, "PostponedMessages must have been initialized during construction in bounding mode."); _boundingState.PostponedMessages.Push(source, messageHeader); return DataflowMessageStatus.Postponed; } // We can't do anything else about this message return DataflowMessageStatus.Declined; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); Contract.EndContractBlock(); CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } private void CompleteCore(Exception exception, bool storeExceptionEvenIfAlreadyCompleting, bool revertProcessingState = false) { Contract.Requires(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState, "Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true."); Contract.EndContractBlock(); lock (IncomingLock) { // Faulting from outside is allowed until we start declining permanently. // Faulting from inside is allowed at any time. if (exception != null && (!_targetDecliningPermanently || storeExceptionEvenIfAlreadyCompleting)) { _source.AddException(exception); } // Revert the dirty processing state if requested if (revertProcessingState) { Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null, "The processing state must be dirty when revertProcessingState==true."); _boundingState.TaskForInputProcessing = null; } // Trigger completion _targetDecliningPermanently = true; CompleteTargetIfPossible(); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> public Boolean TryReceive(Predicate<T> filter, out T item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> public Boolean TryReceiveAll(out IList<T> items) { return _source.TryReceiveAll(out items); } /// <summary>Gets the number of items currently stored in the buffer.</summary> public Int32 Count { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out Boolean messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary>Notifies the block that one or more items was removed from the queue.</summary> /// <param name="numItemsRemoved">The number of items removed.</param> private void OnItemsRemoved(int numItemsRemoved) { Contract.Requires(numItemsRemoved > 0, "A positive number of items to remove is required."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); // If we're bounding, we need to know when an item is removed so that we // can update the count that's mirroring the actual count in the source's queue, // and potentially kick off processing to start consuming postponed messages. if (_boundingState != null) { lock (IncomingLock) { // Decrement the count, which mirrors the count in the source half Debug.Assert(_boundingState.CurrentCount - numItemsRemoved >= 0, "It should be impossible to have a negative number of items."); _boundingState.CurrentCount -= numItemsRemoved; ConsumeAsyncIfNecessary(); CompleteTargetIfPossible(); } } } /// <summary>Called when postponed messages may need to be consumed.</summary> /// <param name="isReplacementReplica">Whether this call is the continuation of a previous message loop.</param> internal void ConsumeAsyncIfNecessary(bool isReplacementReplica = false) { Common.ContractAssertMonitorStatus(IncomingLock, held: true); Debug.Assert(_boundingState != null, "Must be in bounded mode."); if (!_targetDecliningPermanently && _boundingState.TaskForInputProcessing == null && _boundingState.PostponedMessages.Count > 0 && _boundingState.CountIsLessThanBound) { // Create task and store into _taskForInputProcessing prior to scheduling the task // so that _taskForInputProcessing will be visibly set in the task loop. _boundingState.TaskForInputProcessing = new Task(state => ((BufferBlock<T>)state).ConsumeMessagesLoopCore(), this, Common.GetCreationOptionsForTask(isReplacementReplica)); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TaskLaunchedForMessageHandling( this, _boundingState.TaskForInputProcessing, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages, _boundingState.PostponedMessages.Count); } #endif // Start the task handling scheduling exceptions Exception exception = Common.StartTaskSafe(_boundingState.TaskForInputProcessing, _source.DataflowBlockOptions.TaskScheduler); if (exception != null) { // Get out from under currently held locks. CompleteCore re-acquires the locks it needs. Task.Factory.StartNew(exc => CompleteCore(exception: (Exception)exc, storeExceptionEvenIfAlreadyCompleting: true, revertProcessingState: true), exception, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } } /// <summary>Task body used to consume postponed messages.</summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ConsumeMessagesLoopCore() { Contract.Requires(_boundingState != null && _boundingState.TaskForInputProcessing != null, "May only be called in bounded mode and when a task is in flight."); Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId, "This must only be called from the in-flight processing task."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); try { int maxMessagesPerTask = _source.DataflowBlockOptions.ActualMaxMessagesPerTask; for (int i = 0; i < maxMessagesPerTask && ConsumeAndStoreOneMessageIfAvailable(); i++) ; } catch (Exception exc) { // Prevent the creation of new processing tasks CompleteCore(exc, storeExceptionEvenIfAlreadyCompleting: true); } finally { lock (IncomingLock) { // We're no longer processing, so null out the processing task _boundingState.TaskForInputProcessing = null; // However, we may have given up early because we hit our own configured // processing limits rather than because we ran out of work to do. If that's // the case, make sure we spin up another task to keep going. ConsumeAsyncIfNecessary(isReplacementReplica: true); // If, however, we stopped because we ran out of work to do and we // know we'll never get more, then complete. CompleteTargetIfPossible(); } } } /// <summary> /// Retrieves one postponed message if there's room and if we can consume a postponed message. /// Stores any consumed message into the source half. /// </summary> /// <returns>true if a message could be consumed and stored; otherwise, false.</returns> /// <remarks>This must only be called from the asynchronous processing loop.</remarks> private bool ConsumeAndStoreOneMessageIfAvailable() { Contract.Requires(_boundingState != null && _boundingState.TaskForInputProcessing != null, "May only be called in bounded mode and when a task is in flight."); Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId, "This must only be called from the in-flight processing task."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); // Loop through the postponed messages until we get one. while (true) { // Get the next item to retrieve. If there are no more, bail. KeyValuePair<ISourceBlock<T>, DataflowMessageHeader> sourceAndMessage; lock (IncomingLock) { if (!_boundingState.CountIsLessThanBound) return false; if (!_boundingState.PostponedMessages.TryPop(out sourceAndMessage)) return false; // Optimistically assume we're going to get the item. This avoids taking the lock // again if we're right. If we're wrong, we decrement it later under lock. _boundingState.CurrentCount++; } // Consume the item bool consumed = false; try { T consumedValue = sourceAndMessage.Key.ConsumeMessage(sourceAndMessage.Value, this, out consumed); if (consumed) { _source.AddMessage(consumedValue); return true; } } finally { // We didn't get the item, so decrement the count to counteract our optimistic assumption. if (!consumed) { lock (IncomingLock) _boundingState.CurrentCount--; } } } } /// <summary>Completes the target, notifying the source, once all completion conditions are met.</summary> private void CompleteTargetIfPossible() { Common.ContractAssertMonitorStatus(IncomingLock, held: true); if (_targetDecliningPermanently && !_targetCompletionReserved && (_boundingState == null || _boundingState.TaskForInputProcessing == null)) { _targetCompletionReserved = true; // If we're in bounding mode and we have any postponed messages, we need to clear them, // which means calling back to the source, which means we need to escape the incoming lock. if (_boundingState != null && _boundingState.PostponedMessages.Count > 0) { Task.Factory.StartNew(state => { var thisBufferBlock = (BufferBlock<T>)state; // Release any postponed messages List<Exception> exceptions = null; if (thisBufferBlock._boundingState != null) { // Note: No locks should be held at this point Common.ReleaseAllPostponedMessages(thisBufferBlock, thisBufferBlock._boundingState.PostponedMessages, ref exceptions); } if (exceptions != null) { // It is important to migrate these exceptions to the source part of the owning batch, // because that is the completion task that is publically exposed. thisBufferBlock._source.AddExceptions(exceptions); } thisBufferBlock._source.Complete(); }, this, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } // Otherwise, we can just decline the source directly. else { _source.Complete(); } } } /// <summary>Gets the number of messages in the buffer. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int CountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, Count={1}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), CountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the BufferBlock.</summary> private sealed class DebugView { /// <summary>The buffer block.</summary> private readonly BufferBlock<T> _bufferBlock; /// <summary>The buffer's source half.</summary> private readonly SourceCore<T>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="bufferBlock">The BufferBlock being viewed.</param> public DebugView(BufferBlock<T> bufferBlock) { Contract.Requires(bufferBlock != null, "Need a block with which to construct the debug view."); _bufferBlock = bufferBlock; _sourceDebuggingInformation = bufferBlock._source.GetDebuggingInformation(); } /// <summary>Gets the collection of postponed message headers.</summary> public QueuedMap<ISourceBlock<T>, DataflowMessageHeader> PostponedMessages { get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.PostponedMessages : null; } } /// <summary>Gets the messages in the buffer.</summary> public IEnumerable<T> Queue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>The task used to process messages.</summary> public Task TaskForInputProcessing { get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.TaskForInputProcessing : null; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public DataflowBlockOptions DataflowBlockOptions { get { return _sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is declining further messages.</summary> public bool IsDecliningPermanently { get { return _bufferBlock._targetDecliningPermanently; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_bufferBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<T> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the set of all targets linked from this block.</summary> public ITargetBlock<T> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } }
using System; using System.Reflection; using System.Web.Mvc; using Orchard.Blogs.Extensions; using Orchard.Blogs.Models; using Orchard.Blogs.Services; using Orchard.ContentManagement; using Orchard.ContentManagement.Aspects; using Orchard.Core.Contents.Settings; using Orchard.Localization; using Orchard.Mvc.AntiForgery; using Orchard.Mvc.Extensions; using Orchard.UI.Admin; using Orchard.UI.Notify; namespace Orchard.Blogs.Controllers { /// <summary> /// TODO: (PH:Autoroute) This replicates a whole lot of Core.Contents functionality. All we actually need to do is take the BlogId from the query string in the BlogPostPartDriver, and remove /// helper extensions from UrlHelperExtensions. /// </summary> [ValidateInput(false), Admin] public class BlogPostAdminController : Controller, IUpdateModel { private readonly IBlogService _blogService; private readonly IBlogPostService _blogPostService; public BlogPostAdminController(IOrchardServices services, IBlogService blogService, IBlogPostService blogPostService) { Services = services; _blogService = blogService; _blogPostService = blogPostService; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ActionResult Create(int blogId) { var blog = _blogService.Get(blogId, VersionOptions.Latest).As<BlogPart>(); if (blog == null) return HttpNotFound(); var blogPost = Services.ContentManager.New<BlogPostPart>("BlogPost"); blogPost.BlogPart = blog; if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blog, T("Not allowed to create blog post"))) return new HttpUnauthorizedResult(); dynamic model = Services.ContentManager.BuildEditor(blogPost); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } [HttpPost, ActionName("Create")] [FormValueRequired("submit.Save")] public ActionResult CreatePOST(int blogId) { return CreatePOST(blogId, false); } [HttpPost, ActionName("Create")] [FormValueRequired("submit.Publish")] public ActionResult CreateAndPublishPOST(int blogId) { if (!Services.Authorizer.Authorize(Permissions.PublishOwnBlogPost, T("Couldn't create content"))) return new HttpUnauthorizedResult(); return CreatePOST(blogId, true); } private ActionResult CreatePOST(int blogId, bool publish = false) { var blog = _blogService.Get(blogId, VersionOptions.Latest).As<BlogPart>(); if (blog == null) return HttpNotFound(); var blogPost = Services.ContentManager.New<BlogPostPart>("BlogPost"); blogPost.BlogPart = blog; if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blog, T("Couldn't create blog post"))) return new HttpUnauthorizedResult(); Services.ContentManager.Create(blogPost, VersionOptions.Draft); var model = Services.ContentManager.UpdateEditor(blogPost, this); if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } if (publish) { if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, blog.ContentItem, T("Couldn't publish blog post"))) return new HttpUnauthorizedResult(); Services.ContentManager.Publish(blogPost.ContentItem); } Services.Notifier.Information(T("Your {0} has been created.", blogPost.TypeDefinition.DisplayName)); return Redirect(Url.BlogPostEdit(blogPost)); } //todo: the content shape template has extra bits that the core contents module does not (remove draft functionality) //todo: - move this extra functionality there or somewhere else that's appropriate? public ActionResult Edit(int blogId, int postId) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, post, T("Couldn't edit blog post"))) return new HttpUnauthorizedResult(); dynamic model = Services.ContentManager.BuildEditor(post); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Save")] public ActionResult EditPOST(int blogId, int postId, string returnUrl) { return EditPOST(blogId, postId, returnUrl, contentItem => { if (!contentItem.Has<IPublishingControlAspect>() && !contentItem.TypeDefinition.Settings.GetModel<ContentTypeSettings>().Draftable) Services.ContentManager.Publish(contentItem); }); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Publish")] public ActionResult EditAndPublishPOST(int blogId, int postId, string returnUrl) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); // Get draft (create a new version if needed) var blogPost = _blogPostService.Get(postId, VersionOptions.DraftRequired); if (blogPost == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, blogPost, T("Couldn't publish blog post"))) return new HttpUnauthorizedResult(); return EditPOST(blogId, postId, returnUrl, contentItem => Services.ContentManager.Publish(contentItem)); } public ActionResult EditPOST(int blogId, int postId, string returnUrl, Action<ContentItem> conditionallyPublish) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); // Get draft (create a new version if needed) var blogPost = _blogPostService.Get(postId, VersionOptions.DraftRequired); if (blogPost == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, blogPost, T("Couldn't edit blog post"))) return new HttpUnauthorizedResult(); // Validate form input var model = Services.ContentManager.UpdateEditor(blogPost, this); if (!ModelState.IsValid) { Services.TransactionManager.Cancel(); // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation. return View((object)model); } conditionallyPublish(blogPost.ContentItem); Services.Notifier.Information(T("Your {0} has been saved.", blogPost.TypeDefinition.DisplayName)); return this.RedirectLocal(returnUrl, Url.BlogPostEdit(blogPost)); } [ValidateAntiForgeryTokenOrchard] public ActionResult DiscardDraft(int id) { // get the current draft version var draft = Services.ContentManager.Get(id, VersionOptions.Draft); if (draft == null) { Services.Notifier.Information(T("There is no draft to discard.")); return RedirectToEdit(id); } // check edit permission if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, draft, T("Couldn't discard blog post draft"))) return new HttpUnauthorizedResult(); // locate the published revision to revert onto var published = Services.ContentManager.Get(id, VersionOptions.Published); if (published == null) { Services.Notifier.Information(T("Can not discard draft on unpublished blog post.")); return RedirectToEdit(draft); } // marking the previously published version as the latest // has the effect of discarding the draft but keeping the history draft.VersionRecord.Latest = false; published.VersionRecord.Latest = true; Services.Notifier.Information(T("Blog post draft version discarded")); return RedirectToEdit(published); } ActionResult RedirectToEdit(int id) { return RedirectToEdit(Services.ContentManager.GetLatest<BlogPostPart>(id)); } ActionResult RedirectToEdit(IContent item) { if (item == null || item.As<BlogPostPart>() == null) return HttpNotFound(); return RedirectToAction("Edit", new { BlogId = item.As<BlogPostPart>().BlogPart.Id, PostId = item.ContentItem.Id }); } [ValidateAntiForgeryTokenOrchard] public ActionResult Delete(int blogId, int postId) { //refactoring: test PublishBlogPost/PublishBlogPost in addition if published var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.DeleteBlogPost, post, T("Couldn't delete blog post"))) return new HttpUnauthorizedResult(); _blogPostService.Delete(post); Services.Notifier.Information(T("Blog post was successfully deleted")); return Redirect(Url.BlogForAdmin(blog.As<BlogPart>())); } [ValidateAntiForgeryTokenOrchard] public ActionResult Publish(int blogId, int postId) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, post, T("Couldn't publish blog post"))) return new HttpUnauthorizedResult(); _blogPostService.Publish(post); Services.Notifier.Information(T("Blog post successfully published.")); return Redirect(Url.BlogForAdmin(blog.As<BlogPart>())); } [ValidateAntiForgeryTokenOrchard] public ActionResult Unpublish(int blogId, int postId) { var blog = _blogService.Get(blogId, VersionOptions.Latest); if (blog == null) return HttpNotFound(); var post = _blogPostService.Get(postId, VersionOptions.Latest); if (post == null) return HttpNotFound(); if (!Services.Authorizer.Authorize(Permissions.PublishBlogPost, post, T("Couldn't unpublish blog post"))) return new HttpUnauthorizedResult(); _blogPostService.Unpublish(post); Services.Notifier.Information(T("Blog post successfully unpublished.")); return Redirect(Url.BlogForAdmin(blog.As<BlogPart>())); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } public class FormValueRequiredAttribute : ActionMethodSelectorAttribute { private readonly string _submitButtonName; public FormValueRequiredAttribute(string submitButtonName) { _submitButtonName = submitButtonName; } public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { var value = controllerContext.HttpContext.Request.Form[_submitButtonName]; return !string.IsNullOrEmpty(value); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ChannelResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Chat.V2.Service { public class ChannelResource : Resource { public sealed class ChannelTypeEnum : StringEnum { private ChannelTypeEnum(string value) : base(value) {} public ChannelTypeEnum() {} public static implicit operator ChannelTypeEnum(string value) { return new ChannelTypeEnum(value); } public static readonly ChannelTypeEnum Public = new ChannelTypeEnum("public"); public static readonly ChannelTypeEnum Private = new ChannelTypeEnum("private"); } public sealed class WebhookEnabledTypeEnum : StringEnum { private WebhookEnabledTypeEnum(string value) : base(value) {} public WebhookEnabledTypeEnum() {} public static implicit operator WebhookEnabledTypeEnum(string value) { return new WebhookEnabledTypeEnum(value); } public static readonly WebhookEnabledTypeEnum True = new WebhookEnabledTypeEnum("true"); public static readonly WebhookEnabledTypeEnum False = new WebhookEnabledTypeEnum("false"); } private static Request BuildFetchRequest(FetchChannelOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ChannelResource Fetch(FetchChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ChannelResource> FetchAsync(FetchChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathSid"> The SID of the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ChannelResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchChannelOptions(pathServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathSid"> The SID of the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ChannelResource> FetchAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchChannelOptions(pathServiceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteChannelOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static bool Delete(DeleteChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The SID of the Channel resource to delete </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static bool Delete(string pathServiceSid, string pathSid, ChannelResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new DeleteChannelOptions(pathServiceSid, pathSid){XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The SID of the Channel resource to delete </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSid, ChannelResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new DeleteChannelOptions(pathServiceSid, pathSid){XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateChannelOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Channels", postParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ChannelResource Create(CreateChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ChannelResource> CreateAsync(CreateChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the Channel resource under </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the Channel resource </param> /// <param name="attributes"> A valid JSON string that contains application-specific data </param> /// <param name="type"> The visibility of the channel </param> /// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param> /// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param> /// <param name="createdBy"> The identity of the User that created the Channel </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ChannelResource Create(string pathServiceSid, string friendlyName = null, string uniqueName = null, string attributes = null, ChannelResource.ChannelTypeEnum type = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string createdBy = null, ChannelResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new CreateChannelOptions(pathServiceSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes, Type = type, DateCreated = dateCreated, DateUpdated = dateUpdated, CreatedBy = createdBy, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the Channel resource under </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the Channel resource </param> /// <param name="attributes"> A valid JSON string that contains application-specific data </param> /// <param name="type"> The visibility of the channel </param> /// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param> /// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param> /// <param name="createdBy"> The identity of the User that created the Channel </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ChannelResource> CreateAsync(string pathServiceSid, string friendlyName = null, string uniqueName = null, string attributes = null, ChannelResource.ChannelTypeEnum type = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string createdBy = null, ChannelResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new CreateChannelOptions(pathServiceSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes, Type = type, DateCreated = dateCreated, DateUpdated = dateUpdated, CreatedBy = createdBy, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadChannelOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Channels", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ResourceSet<ChannelResource> Read(ReadChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ChannelResource>.FromJson("channels", response.Content); return new ResourceSet<ChannelResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ResourceSet<ChannelResource>> ReadAsync(ReadChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ChannelResource>.FromJson("channels", response.Content); return new ResourceSet<ChannelResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> /// <param name="type"> The visibility of the channel to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ResourceSet<ChannelResource> Read(string pathServiceSid, List<ChannelResource.ChannelTypeEnum> type = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadChannelOptions(pathServiceSid){Type = type, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> /// <param name="type"> The visibility of the channel to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ResourceSet<ChannelResource>> ReadAsync(string pathServiceSid, List<ChannelResource.ChannelTypeEnum> type = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadChannelOptions(pathServiceSid){Type = type, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ChannelResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ChannelResource>.FromJson("channels", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ChannelResource> NextPage(Page<ChannelResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<ChannelResource>.FromJson("channels", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ChannelResource> PreviousPage(Page<ChannelResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<ChannelResource>.FromJson("channels", response.Content); } private static Request BuildUpdateRequest(UpdateChannelOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathSid + "", postParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ChannelResource Update(UpdateChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Channel parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ChannelResource> UpdateAsync(UpdateChannelOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the resource from </param> /// <param name="pathSid"> The SID of the Channel resource to update </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param> /// <param name="attributes"> A valid JSON string that contains application-specific data </param> /// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param> /// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param> /// <param name="createdBy"> The identity of the User that created the Channel </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Channel </returns> public static ChannelResource Update(string pathServiceSid, string pathSid, string friendlyName = null, string uniqueName = null, string attributes = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string createdBy = null, ChannelResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new UpdateChannelOptions(pathServiceSid, pathSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes, DateCreated = dateCreated, DateUpdated = dateUpdated, CreatedBy = createdBy, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The SID of the Service to update the resource from </param> /// <param name="pathSid"> The SID of the Channel resource to update </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param> /// <param name="attributes"> A valid JSON string that contains application-specific data </param> /// <param name="dateCreated"> The ISO 8601 date and time in GMT when the resource was created </param> /// <param name="dateUpdated"> The ISO 8601 date and time in GMT when the resource was updated </param> /// <param name="createdBy"> The identity of the User that created the Channel </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Channel </returns> public static async System.Threading.Tasks.Task<ChannelResource> UpdateAsync(string pathServiceSid, string pathSid, string friendlyName = null, string uniqueName = null, string attributes = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string createdBy = null, ChannelResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new UpdateChannelOptions(pathServiceSid, pathSid){FriendlyName = friendlyName, UniqueName = uniqueName, Attributes = attributes, DateCreated = dateCreated, DateUpdated = dateUpdated, CreatedBy = createdBy, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ChannelResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ChannelResource object represented by the provided JSON </returns> public static ChannelResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ChannelResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> [JsonProperty("unique_name")] public string UniqueName { get; private set; } /// <summary> /// The JSON string that stores application-specific data /// </summary> [JsonProperty("attributes")] public string Attributes { get; private set; } /// <summary> /// The visibility of the channel. Can be: `public` or `private` /// </summary> [JsonProperty("type")] [JsonConverter(typeof(StringEnumConverter))] public ChannelResource.ChannelTypeEnum Type { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The identity of the User that created the channel /// </summary> [JsonProperty("created_by")] public string CreatedBy { get; private set; } /// <summary> /// The number of Members in the Channel /// </summary> [JsonProperty("members_count")] public int? MembersCount { get; private set; } /// <summary> /// The number of Messages that have been passed in the Channel /// </summary> [JsonProperty("messages_count")] public int? MessagesCount { get; private set; } /// <summary> /// The absolute URL of the Channel resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private ChannelResource() { } } }
/* ==================================================================== 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.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; namespace fyiReporting.RdlDesign { /// <summary> /// Summary description for ChartCtl. /// </summary> internal class ChartAxisCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; // change flags bool fMonth, fVisible, fMajorTickMarks, fMargin,fReverse,fInterlaced; bool fMajorGLWidth,fMajorGLColor,fMajorGLStyle; bool fMinorGLWidth,fMinorGLColor,fMinorGLStyle; bool fMajorInterval, fMinorInterval,fMax,fMin; bool fMinorTickMarks,fScalar,fLogScale,fMajorGLShow, fMinorGLShow, fCanOmit; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.CheckBox chkMonth; private System.Windows.Forms.CheckBox chkVisible; private System.Windows.Forms.ComboBox cbMajorTickMarks; private System.Windows.Forms.CheckBox chkMargin; private System.Windows.Forms.CheckBox chkReverse; private System.Windows.Forms.CheckBox chkInterlaced; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox tbMajorGLWidth; private System.Windows.Forms.Button bMajorGLColor; private System.Windows.Forms.ComboBox cbMajorGLColor; private System.Windows.Forms.ComboBox cbMajorGLStyle; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox tbMinorGLWidth; private System.Windows.Forms.Button bMinorGLColor; private System.Windows.Forms.ComboBox cbMinorGLColor; private System.Windows.Forms.ComboBox cbMinorGLStyle; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox tbMajorInterval; private System.Windows.Forms.TextBox tbMinorInterval; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox tbMax; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox tbMin; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox cbMinorTickMarks; private System.Windows.Forms.CheckBox chkScalar; private System.Windows.Forms.CheckBox chkLogScale; private System.Windows.Forms.CheckBox chkMajorGLShow; private System.Windows.Forms.CheckBox chkMinorGLShow; private System.Windows.Forms.Button bMinorIntervalExpr; private System.Windows.Forms.Button bMajorIntervalExpr; private System.Windows.Forms.Button bMinExpr; private System.Windows.Forms.Button bMaxExpr; private CheckBox chkCanOmit; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal ChartAxisCtl(DesignXmlDraw dxDraw, List<XmlNode> ris) { _ReportItems = ris; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { cbMajorGLColor.Items.AddRange(StaticLists.ColorList); cbMinorGLColor.Items.AddRange(StaticLists.ColorList); XmlNode node = _ReportItems[0]; chkMonth.Checked = _Draw.GetElementValue(node, "fyi:Month", "false").ToLower() == "true" ? true : false; //added checkbox for month category axis WP 12 may 2008 chkVisible.Checked = _Draw.GetElementValue(node, "Visible", "false").ToLower() == "true"? true: false; chkMargin.Checked = _Draw.GetElementValue(node, "Margin", "false").ToLower() == "true"? true: false; chkReverse.Checked = _Draw.GetElementValue(node, "Reverse", "false").ToLower() == "true"? true: false; chkInterlaced.Checked = _Draw.GetElementValue(node, "Interlaced", "false").ToLower() == "true"? true: false; chkScalar.Checked = _Draw.GetElementValue(node, "Scalar", "false").ToLower() == "true"? true: false; chkLogScale.Checked = _Draw.GetElementValue(node, "LogScale", "false").ToLower() == "true"? true: false; chkCanOmit.Checked = _Draw.GetElementValue(node, "fyi:CanOmit", "false").ToLower() == "true" ? true : false; cbMajorTickMarks.Text = _Draw.GetElementValue(node, "MajorTickMarks", "None"); cbMinorTickMarks.Text = _Draw.GetElementValue(node, "MinorTickMarks", "None"); // Major Grid Lines InitGridLines(node, "MajorGridLines", chkMajorGLShow, cbMajorGLColor, cbMajorGLStyle, tbMajorGLWidth); // Minor Grid Lines InitGridLines(node, "MinorGridLines", chkMinorGLShow, cbMinorGLColor, cbMinorGLStyle, tbMinorGLWidth); tbMajorInterval.Text = _Draw.GetElementValue(node, "MajorInterval", ""); tbMinorInterval.Text = _Draw.GetElementValue(node, "MinorInterval", ""); tbMax.Text = _Draw.GetElementValue(node, "Max", ""); tbMin.Text = _Draw.GetElementValue(node, "Min", ""); fMonth = fVisible = fMajorTickMarks = fMargin=fReverse=fInterlaced= fMajorGLWidth=fMajorGLColor=fMajorGLStyle= fMinorGLWidth=fMinorGLColor=fMinorGLStyle= fMajorInterval= fMinorInterval=fMax=fMin= fMinorTickMarks=fScalar=fLogScale=fMajorGLShow=fMinorGLShow=fCanOmit=false; } private void InitGridLines(XmlNode node, string type, CheckBox show, ComboBox color, ComboBox style, TextBox width) { XmlNode m = _Draw.GetNamedChildNode(node, type); if (m != null) { show.Checked = _Draw.GetElementValue(m, "ShowGridLines", "false").ToLower() == "true"? true: false; XmlNode st = _Draw.GetNamedChildNode(m, "Style"); if (st != null) { XmlNode work = _Draw.GetNamedChildNode(st, "BorderColor"); if (work != null) color.Text = _Draw.GetElementValue(work, "Default", "Black"); work = _Draw.GetNamedChildNode(st, "BorderStyle"); if (work != null) style.Text = _Draw.GetElementValue(work, "Default", "Solid"); work = _Draw.GetNamedChildNode(st, "BorderWidth"); if (work != null) width.Text = _Draw.GetElementValue(work, "Default", "1pt"); } } if (color.Text.Length == 0) color.Text = "Black"; if (style.Text.Length == 0) style.Text = "Solid"; if (width.Text.Length == 0) width.Text = "1pt"; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ChartAxisCtl)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.cbMajorTickMarks = new System.Windows.Forms.ComboBox(); this.cbMinorTickMarks = new System.Windows.Forms.ComboBox(); this.chkVisible = new System.Windows.Forms.CheckBox(); this.chkMargin = new System.Windows.Forms.CheckBox(); this.chkReverse = new System.Windows.Forms.CheckBox(); this.chkInterlaced = new System.Windows.Forms.CheckBox(); this.chkScalar = new System.Windows.Forms.CheckBox(); this.chkLogScale = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.chkMajorGLShow = new System.Windows.Forms.CheckBox(); this.tbMajorGLWidth = new System.Windows.Forms.TextBox(); this.bMajorGLColor = new System.Windows.Forms.Button(); this.cbMajorGLColor = new System.Windows.Forms.ComboBox(); this.cbMajorGLStyle = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.chkMinorGLShow = new System.Windows.Forms.CheckBox(); this.tbMinorGLWidth = new System.Windows.Forms.TextBox(); this.bMinorGLColor = new System.Windows.Forms.Button(); this.cbMinorGLColor = new System.Windows.Forms.ComboBox(); this.cbMinorGLStyle = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.tbMajorInterval = new System.Windows.Forms.TextBox(); this.tbMinorInterval = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.tbMax = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.tbMin = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.bMinorIntervalExpr = new System.Windows.Forms.Button(); this.bMajorIntervalExpr = new System.Windows.Forms.Button(); this.bMinExpr = new System.Windows.Forms.Button(); this.bMaxExpr = new System.Windows.Forms.Button(); this.chkCanOmit = new System.Windows.Forms.CheckBox(); this.chkMonth = new System.Windows.Forms.CheckBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // cbMajorTickMarks // resources.ApplyResources(this.cbMajorTickMarks, "cbMajorTickMarks"); this.cbMajorTickMarks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbMajorTickMarks.Items.AddRange(new object[] { resources.GetString("cbMajorTickMarks.Items"), resources.GetString("cbMajorTickMarks.Items1"), resources.GetString("cbMajorTickMarks.Items2"), resources.GetString("cbMajorTickMarks.Items3")}); this.cbMajorTickMarks.Name = "cbMajorTickMarks"; this.cbMajorTickMarks.SelectedIndexChanged += new System.EventHandler(this.cbMajorTickMarks_SelectedIndexChanged); // // cbMinorTickMarks // resources.ApplyResources(this.cbMinorTickMarks, "cbMinorTickMarks"); this.cbMinorTickMarks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbMinorTickMarks.Items.AddRange(new object[] { resources.GetString("cbMinorTickMarks.Items"), resources.GetString("cbMinorTickMarks.Items1"), resources.GetString("cbMinorTickMarks.Items2"), resources.GetString("cbMinorTickMarks.Items3")}); this.cbMinorTickMarks.Name = "cbMinorTickMarks"; this.cbMinorTickMarks.SelectedIndexChanged += new System.EventHandler(this.cbMinorTickMarks_SelectedIndexChanged); // // chkVisible // resources.ApplyResources(this.chkVisible, "chkVisible"); this.chkVisible.Name = "chkVisible"; this.chkVisible.CheckedChanged += new System.EventHandler(this.chkVisible_CheckedChanged); // // chkMargin // resources.ApplyResources(this.chkMargin, "chkMargin"); this.chkMargin.Name = "chkMargin"; this.chkMargin.CheckedChanged += new System.EventHandler(this.chkMargin_CheckedChanged); // // chkReverse // resources.ApplyResources(this.chkReverse, "chkReverse"); this.chkReverse.Name = "chkReverse"; this.chkReverse.CheckedChanged += new System.EventHandler(this.chkReverse_CheckedChanged); // // chkInterlaced // resources.ApplyResources(this.chkInterlaced, "chkInterlaced"); this.chkInterlaced.Name = "chkInterlaced"; this.chkInterlaced.CheckedChanged += new System.EventHandler(this.chkInterlaced_CheckedChanged); // // chkScalar // resources.ApplyResources(this.chkScalar, "chkScalar"); this.chkScalar.Name = "chkScalar"; this.chkScalar.CheckedChanged += new System.EventHandler(this.chkScalar_CheckedChanged); // // chkLogScale // resources.ApplyResources(this.chkLogScale, "chkLogScale"); this.chkLogScale.Name = "chkLogScale"; this.chkLogScale.CheckedChanged += new System.EventHandler(this.chkLogScale_CheckedChanged); // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.cbMajorGLStyle); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.chkMajorGLShow); this.groupBox1.Controls.Add(this.tbMajorGLWidth); this.groupBox1.Controls.Add(this.bMajorGLColor); this.groupBox1.Controls.Add(this.cbMajorGLColor); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // chkMajorGLShow // resources.ApplyResources(this.chkMajorGLShow, "chkMajorGLShow"); this.chkMajorGLShow.Name = "chkMajorGLShow"; this.chkMajorGLShow.CheckedChanged += new System.EventHandler(this.chkMajorGLShow_CheckedChanged); // // tbMajorGLWidth // resources.ApplyResources(this.tbMajorGLWidth, "tbMajorGLWidth"); this.tbMajorGLWidth.Name = "tbMajorGLWidth"; this.tbMajorGLWidth.TextChanged += new System.EventHandler(this.tbMajorGLWidth_TextChanged); // // bMajorGLColor // resources.ApplyResources(this.bMajorGLColor, "bMajorGLColor"); this.bMajorGLColor.Name = "bMajorGLColor"; this.bMajorGLColor.Click += new System.EventHandler(this.bMajorGLColor_Click); // // cbMajorGLColor // resources.ApplyResources(this.cbMajorGLColor, "cbMajorGLColor"); this.cbMajorGLColor.Name = "cbMajorGLColor"; this.cbMajorGLColor.SelectedIndexChanged += new System.EventHandler(this.cbMajorGLColor_SelectedIndexChanged); // // cbMajorGLStyle // resources.ApplyResources(this.cbMajorGLStyle, "cbMajorGLStyle"); this.cbMajorGLStyle.Items.AddRange(new object[] { resources.GetString("cbMajorGLStyle.Items"), resources.GetString("cbMajorGLStyle.Items1"), resources.GetString("cbMajorGLStyle.Items2"), resources.GetString("cbMajorGLStyle.Items3"), resources.GetString("cbMajorGLStyle.Items4"), resources.GetString("cbMajorGLStyle.Items5"), resources.GetString("cbMajorGLStyle.Items6"), resources.GetString("cbMajorGLStyle.Items7"), resources.GetString("cbMajorGLStyle.Items8"), resources.GetString("cbMajorGLStyle.Items9")}); this.cbMajorGLStyle.Name = "cbMajorGLStyle"; this.cbMajorGLStyle.SelectedIndexChanged += new System.EventHandler(this.cbMajorGLStyle_SelectedIndexChanged); // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // groupBox2 // resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.Controls.Add(this.cbMinorGLStyle); this.groupBox2.Controls.Add(this.label8); this.groupBox2.Controls.Add(this.chkMinorGLShow); this.groupBox2.Controls.Add(this.tbMinorGLWidth); this.groupBox2.Controls.Add(this.bMinorGLColor); this.groupBox2.Controls.Add(this.cbMinorGLColor); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // chkMinorGLShow // resources.ApplyResources(this.chkMinorGLShow, "chkMinorGLShow"); this.chkMinorGLShow.Name = "chkMinorGLShow"; this.chkMinorGLShow.CheckedChanged += new System.EventHandler(this.chkMinorGLShow_CheckedChanged); // // tbMinorGLWidth // resources.ApplyResources(this.tbMinorGLWidth, "tbMinorGLWidth"); this.tbMinorGLWidth.Name = "tbMinorGLWidth"; this.tbMinorGLWidth.TextChanged += new System.EventHandler(this.tbMinorGLWidth_TextChanged); // // bMinorGLColor // resources.ApplyResources(this.bMinorGLColor, "bMinorGLColor"); this.bMinorGLColor.Name = "bMinorGLColor"; this.bMinorGLColor.Click += new System.EventHandler(this.bMinorGLColor_Click); // // cbMinorGLColor // resources.ApplyResources(this.cbMinorGLColor, "cbMinorGLColor"); this.cbMinorGLColor.Name = "cbMinorGLColor"; this.cbMinorGLColor.SelectedIndexChanged += new System.EventHandler(this.cbMinorGLColor_SelectedIndexChanged); // // cbMinorGLStyle // resources.ApplyResources(this.cbMinorGLStyle, "cbMinorGLStyle"); this.cbMinorGLStyle.Items.AddRange(new object[] { resources.GetString("cbMinorGLStyle.Items"), resources.GetString("cbMinorGLStyle.Items1"), resources.GetString("cbMinorGLStyle.Items2"), resources.GetString("cbMinorGLStyle.Items3"), resources.GetString("cbMinorGLStyle.Items4"), resources.GetString("cbMinorGLStyle.Items5"), resources.GetString("cbMinorGLStyle.Items6"), resources.GetString("cbMinorGLStyle.Items7"), resources.GetString("cbMinorGLStyle.Items8"), resources.GetString("cbMinorGLStyle.Items9")}); this.cbMinorGLStyle.Name = "cbMinorGLStyle"; this.cbMinorGLStyle.SelectedIndexChanged += new System.EventHandler(this.cbMinorGLStyle_SelectedIndexChanged); // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // label9 // resources.ApplyResources(this.label9, "label9"); this.label9.Name = "label9"; // // tbMajorInterval // resources.ApplyResources(this.tbMajorInterval, "tbMajorInterval"); this.tbMajorInterval.Name = "tbMajorInterval"; this.tbMajorInterval.TextChanged += new System.EventHandler(this.tbMajorInterval_TextChanged); // // tbMinorInterval // resources.ApplyResources(this.tbMinorInterval, "tbMinorInterval"); this.tbMinorInterval.Name = "tbMinorInterval"; this.tbMinorInterval.TextChanged += new System.EventHandler(this.tbMinorInterval_TextChanged); // // label10 // resources.ApplyResources(this.label10, "label10"); this.label10.Name = "label10"; // // tbMax // resources.ApplyResources(this.tbMax, "tbMax"); this.tbMax.Name = "tbMax"; this.tbMax.TextChanged += new System.EventHandler(this.tbMax_TextChanged); // // label11 // resources.ApplyResources(this.label11, "label11"); this.label11.Name = "label11"; // // tbMin // resources.ApplyResources(this.tbMin, "tbMin"); this.tbMin.Name = "tbMin"; this.tbMin.TextChanged += new System.EventHandler(this.tbMin_TextChanged); // // label12 // resources.ApplyResources(this.label12, "label12"); this.label12.Name = "label12"; // // bMinorIntervalExpr // resources.ApplyResources(this.bMinorIntervalExpr, "bMinorIntervalExpr"); this.bMinorIntervalExpr.Name = "bMinorIntervalExpr"; this.bMinorIntervalExpr.Tag = "minorinterval"; this.bMinorIntervalExpr.Click += new System.EventHandler(this.bExpr_Click); // // bMajorIntervalExpr // resources.ApplyResources(this.bMajorIntervalExpr, "bMajorIntervalExpr"); this.bMajorIntervalExpr.Name = "bMajorIntervalExpr"; this.bMajorIntervalExpr.Tag = "majorinterval"; this.bMajorIntervalExpr.Click += new System.EventHandler(this.bExpr_Click); // // bMinExpr // resources.ApplyResources(this.bMinExpr, "bMinExpr"); this.bMinExpr.Name = "bMinExpr"; this.bMinExpr.Tag = "min"; this.bMinExpr.Click += new System.EventHandler(this.bExpr_Click); // // bMaxExpr // resources.ApplyResources(this.bMaxExpr, "bMaxExpr"); this.bMaxExpr.Name = "bMaxExpr"; this.bMaxExpr.Tag = "max"; this.bMaxExpr.Click += new System.EventHandler(this.bExpr_Click); // // chkCanOmit // resources.ApplyResources(this.chkCanOmit, "chkCanOmit"); this.chkCanOmit.Name = "chkCanOmit"; this.chkCanOmit.CheckedChanged += new System.EventHandler(this.chkCanOmit_CheckedChanged); // // chkMonth // resources.ApplyResources(this.chkMonth, "chkMonth"); this.chkMonth.Name = "chkMonth"; this.chkMonth.CheckedChanged += new System.EventHandler(this.chkMonth_CheckedChanged); // // ChartAxisCtl // resources.ApplyResources(this, "$this"); this.Controls.Add(this.chkReverse); this.Controls.Add(this.chkMonth); this.Controls.Add(this.chkCanOmit); this.Controls.Add(this.bMaxExpr); this.Controls.Add(this.bMinExpr); this.Controls.Add(this.bMajorIntervalExpr); this.Controls.Add(this.bMinorIntervalExpr); this.Controls.Add(this.tbMax); this.Controls.Add(this.label11); this.Controls.Add(this.tbMin); this.Controls.Add(this.label12); this.Controls.Add(this.tbMinorInterval); this.Controls.Add(this.label10); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.chkLogScale); this.Controls.Add(this.chkScalar); this.Controls.Add(this.chkInterlaced); this.Controls.Add(this.chkMargin); this.Controls.Add(this.chkVisible); this.Controls.Add(this.cbMinorTickMarks); this.Controls.Add(this.cbMajorTickMarks); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.tbMajorInterval); this.Controls.Add(this.label9); this.Name = "ChartAxisCtl"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); fMonth = fVisible = fMajorTickMarks = fMargin=fReverse=fInterlaced= fMajorGLWidth=fMajorGLColor=fMajorGLStyle= fMinorGLWidth=fMinorGLColor=fMinorGLStyle= fMajorInterval= fMinorInterval=fMax=fMin= fMinorTickMarks=fScalar=fLogScale=fMajorGLShow=fMinorGLShow=fCanOmit=false; } public void ApplyChanges(XmlNode node) { if (fMonth) { _Draw.SetElement(node, "fyi:Month", this.chkMonth.Checked? "true" : "false"); } if (fVisible) { _Draw.SetElement(node, "Visible", this.chkVisible.Checked? "true": "false"); } if (fMajorTickMarks) { _Draw.SetElement(node, "MajorTickMarks", this.cbMajorTickMarks.Text); } if (fMargin) { _Draw.SetElement(node, "Margin", this.chkMargin.Checked? "true": "false"); } if (fReverse) { _Draw.SetElement(node, "Reverse", this.chkReverse.Checked? "true": "false"); } if (fInterlaced) { _Draw.SetElement(node, "Interlaced", this.chkInterlaced.Checked? "true": "false"); } if (fMajorGLShow || fMajorGLWidth || fMajorGLColor || fMajorGLStyle) { ApplyGridLines(node, "MajorGridLines", chkMajorGLShow, cbMajorGLColor, cbMajorGLStyle, tbMajorGLWidth); } if (fMinorGLShow || fMinorGLWidth || fMinorGLColor || fMinorGLStyle) { ApplyGridLines(node, "MinorGridLines", chkMinorGLShow, cbMinorGLColor, cbMinorGLStyle, tbMinorGLWidth); } if (fMajorInterval) { _Draw.SetElement(node, "MajorInterval", this.tbMajorInterval.Text); } if (fMinorInterval) { _Draw.SetElement(node, "MinorInterval", this.tbMinorInterval.Text); } if (fMax) { _Draw.SetElement(node, "Max", this.tbMax.Text); } if (fMin) { _Draw.SetElement(node, "Min", this.tbMin.Text); } if (fMinorTickMarks) { _Draw.SetElement(node, "MinorTickMarks", this.cbMinorTickMarks.Text); } if (fScalar) { _Draw.SetElement(node, "Scalar", this.chkScalar.Checked? "true": "false"); } if (fLogScale) { _Draw.SetElement(node, "LogScale", this.chkLogScale.Checked? "true": "false"); } if (fCanOmit) { _Draw.SetElement(node, "fyi:CanOmit", this.chkCanOmit.Checked ? "true" : "false"); } } private void ApplyGridLines(XmlNode node, string type, CheckBox show, ComboBox color, ComboBox style, TextBox width) { XmlNode m = _Draw.GetNamedChildNode(node, type); if (m == null) { m = _Draw.CreateElement(node, type, null); } _Draw.SetElement(m, "ShowGridLines", show.Checked? "true": "false"); XmlNode st = _Draw.GetNamedChildNode(m, "Style"); if (st == null) st = _Draw.CreateElement(m, "Style", null); XmlNode work = _Draw.GetNamedChildNode(st, "BorderColor"); if (work == null) work = _Draw.CreateElement(st, "BorderColor", null); _Draw.SetElement(work, "Default", color.Text); work = _Draw.GetNamedChildNode(st, "BorderStyle"); if (work == null) work = _Draw.CreateElement(st, "BorderStyle", null); _Draw.SetElement(work, "Default", style.Text); work = _Draw.GetNamedChildNode(st, "BorderWidth"); if (work == null) work = _Draw.CreateElement(st, "BorderWidth", null); _Draw.SetElement(work, "Default", width.Text); } private void cbMajorTickMarks_SelectedIndexChanged(object sender, System.EventArgs e) { fMajorTickMarks = true; } private void cbMinorTickMarks_SelectedIndexChanged(object sender, System.EventArgs e) { fMinorTickMarks = true; } private void cbMajorGLStyle_SelectedIndexChanged(object sender, System.EventArgs e) { fMajorGLStyle = true; } private void cbMajorGLColor_SelectedIndexChanged(object sender, System.EventArgs e) { fMajorGLColor = true; } private void tbMajorGLWidth_TextChanged(object sender, System.EventArgs e) { fMajorGLWidth = true; } private void cbMinorGLStyle_SelectedIndexChanged(object sender, System.EventArgs e) { fMinorGLStyle = true; } private void cbMinorGLColor_SelectedIndexChanged(object sender, System.EventArgs e) { fMinorGLColor = true; } private void tbMinorGLWidth_TextChanged(object sender, System.EventArgs e) { fMinorGLWidth = true; } private void tbMajorInterval_TextChanged(object sender, System.EventArgs e) { fMajorInterval = true; } private void tbMinorInterval_TextChanged(object sender, System.EventArgs e) { fMinorInterval = true; } private void tbMin_TextChanged(object sender, System.EventArgs e) { fMin = true; } private void tbMax_TextChanged(object sender, System.EventArgs e) { fMax = true; } private void chkMonth_CheckedChanged(object sender, System.EventArgs e) { fMonth = true; } private void chkVisible_CheckedChanged(object sender, System.EventArgs e) { fVisible = true; } private void chkLogScale_CheckedChanged(object sender, System.EventArgs e) { fLogScale = true; } private void chkCanOmit_CheckedChanged(object sender, System.EventArgs e) { fCanOmit = true; } private void chkMargin_CheckedChanged(object sender, System.EventArgs e) { fMargin = true; } private void chkScalar_CheckedChanged(object sender, System.EventArgs e) { fScalar = true; } private void chkReverse_CheckedChanged(object sender, System.EventArgs e) { fReverse = true; } private void chkInterlaced_CheckedChanged(object sender, System.EventArgs e) { fInterlaced = true; } private void chkMajorGLShow_CheckedChanged(object sender, System.EventArgs e) { fMajorGLShow = true; } private void chkMinorGLShow_CheckedChanged(object sender, System.EventArgs e) { fMinorGLShow = true; } private void bMajorGLColor_Click(object sender, System.EventArgs e) { SetColor(this.cbMajorGLColor); } private void bMinorGLColor_Click(object sender, System.EventArgs e) { SetColor(this.cbMinorGLColor); } private void SetColor(ComboBox cbColor) { ColorDialog cd = new ColorDialog(); cd.AnyColor = true; cd.FullOpen = true; cd.CustomColors = RdlDesigner.GetCustomColors(); cd.Color = DesignerUtility.ColorFromHtml(cbColor.Text, System.Drawing.Color.Empty); try { if (cd.ShowDialog() != DialogResult.OK) return; RdlDesigner.SetCustomColors(cd.CustomColors); cbColor.Text = ColorTranslator.ToHtml(cd.Color); } finally { cd.Dispose(); } return; } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; bool bColor=false; switch (b.Tag as string) { case "min": c = this.tbMin; break; case "max": c = this.tbMax; break; case "majorinterval": c = this.tbMajorInterval; break; case "minorinterval": c = this.tbMinorInterval; break; } if (c == null) return; XmlNode sNode = _ReportItems[0]; DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode, bColor); try { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; } finally { ee.Dispose(); } return; } } }
/* * ContainerControl.cs - Implementation of the * "System.Windows.Forms.ContainerControl" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * Copyright (C) 2003 Neil Cawse. * * 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 */ /* Information on Keyboard handling * Key event processing always starts at the control that has the input focus (e.g. a text control). From there various methods are called upwards in the window hierarchy (from child to parent). This gives parent controls such as forms and panels an opportunity to handle and consume key events before they can reach the target control. There is only one method (ProcessMnemonic) that is called in the opposite direction (from parent to child). Each of the 8 methods returns a boolean value. If a method returns true the key event is considered handled (consumed) and processing of that particular key event will stop immediatly (no further processing methods will be called). Key event processing actually happens in two phases: preprocessing and processing. The preprocessing phase starts with a call to PreProcessMessage, the processing phase with a call to ProcessKeyMessage. While the processing phase is very similar for all three types of key events (WM_KEYDOWN, WM_KEYUP and WM_CHAR) preprocessing differs completely for WM_KEYDOWN and WM_CHAR and there is no preprocessing phase for WM_KEYUP. Here is what happens in detail: Preprocessing Phase (WM_KEYDOWN): 1. PreProcessMessage is called on the focused control. 2. The focused control calls its own ProcessCmdKey method. 3. ProcessCmdKey by default just returns the result of calling ProcessCmdKey on its parent. So effectivly this bubbles the event up the windows hierarchy until the top-most control is reached which - by default - simply returns false. 4. The focused control calls IsInputKey on itself. If the result is true the PreProcessMessage terminates at this point with a return value of false. 6. The focused control calls its own ProcessDialogKey method. 7. Again, ProcessDialogKey is called from child to parent along the parent chaim until the top-most control is reached which usually returns false. 7. PreProcessMessage returns. Preprocessing Phase (WM_CHAR): 1. PreProcessMessage is called on the focused control. 2. The focused control calls IsInputChar on itself. If the result is true the PreProcessMessage terminates at this point with a return value of false. 3. The focused control calls its own ProcessDialogChar method. 4. ProcessDialogChar is called from child to parent along the parent chain until the top-most control is reached which usually returns false. In addition, for each ContainerControl the following step is performed before the parent's ProcessDialogChar method is invoked: 5. The container control calls its own ProcessMnemonic method. 6. ProcessMnemonic is called for all child controls of the container (which in turn might call ProcessMnemonic on their children). 7. PreProcessMessage returns. Processing Phase (WM_KEYDOWN, WM_KEYUP and WM_CHAR): 1. ProcessKeyMessage is called on the focused control. 2. The focused control calls ProcessKeyPreview on the parent control. 3. ProcessKeyPreview is called from child to parent along the parent chain until the top-most control is reached which usually returns false. 4. The focused control calls ProcessKeyEventArgs on itself. 5. ProcessKeyEventArgs calls one of the methods OnKeyDown, OnKeyUp or OnKeyPress depending on the type of key event. 6. The On* method invokes all event handlers that have been registerd for the corresponding event. 7. ProcessKeyMessage returns. Note again that as soon as one method returns true processing will stop and the calling method will immediately return true as well. Also, if the preprocessing phase returns true the processing phase will be skipped. You may have noticed that in preprocessing of WM_CHAR when there are several container controls in the parent chain the ProcessMnemonic method of child controls will be called unnecessarily often. */ namespace System.Windows.Forms { using System.Drawing; using System.ComponentModel; public class ContainerControl : ScrollableControl, IContainerControl { // Internal state. private Control activeControl; private Control focusedControl; private Control unvalidatedControl; private bool validating = false; // Constructor. public ContainerControl() { SetStyle(ControlStyles.AllPaintingInWmPaint, false); SetStyle(ControlStyles.ContainerControl, true); } #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public override BindingContext BindingContext { get { // Containers must always have a binding context. BindingContext context = base.BindingContext; if(context == null) { context = new BindingContext(); base.BindingContext = context; } return context; } set { base.BindingContext = value; } } protected override CreateParams CreateParams { get { return base.CreateParams; } } #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public virtual Control ActiveControl { get { return activeControl; } set { // Already set? if (activeControl == value && (value == null || value.Focused)) { return; } // Can't set the active control to a control thats not a child of the container. if (value != null && !Contains(value)) { throw new ArgumentException(S._("SWF_CouldNotActivate")); } bool activated; // Find outer container. ContainerControl parentContainer = this; if (value != null && value.Parent != null) { parentContainer = value.Parent.GetContainerControl() as ContainerControl; } if (parentContainer != null) { activated = parentContainer.ActivateControlInternal(value); } else { activated = SetActiveControl(value); } if (parentContainer != null && activated) { // Only focus if the control that currently has the focus falls in the same hierarchy as the control we are setting the focus to. ContainerControl outerContainer = this; while (outerContainer.Parent != null && outerContainer.Parent.GetContainerControl() is ContainerControl) { outerContainer = outerContainer.Parent.GetContainerControl() as ContainerControl; } if (outerContainer.ContainsFocus) { parentContainer.SetFocus(activeControl); } } } } #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public Form ParentForm { get { Control parent = Parent; if (parent != null) { return parent.FindForm(); } if (this is Form) { return null; } else { return FindForm(); } } } // Activate a specific control. public bool ActivateControl(Control active) { bool activated = ActivateControlInternal(active); //TODO: Scroll active into view if its not visible. return activated; } private bool ActivateControlInternal(Control active) { bool activated = true; bool activate = false; ContainerControl container; Control parent = base.Parent; if (parent != null) { container = parent.GetContainerControl() as ContainerControl; if (container != null && container.ActiveControl != this) { activate = true; if (!container.ActivateControlInternal(this)) { return false; } } } if (active != activeControl || activate) { if (active == this) { activated = SetActiveControl(null); } else { activated = SetActiveControl(active); } } return activated; } #if CONFIG_COMPONENT_MODEL [EditorBrowsable(EditorBrowsableState.Advanced)] #endif // CONFIG_COMPONENT_MODEL protected override void AdjustFormScrollbars(bool displayScrollbars) { AdjustFormScrollbars(displayScrollbars); ScrollControlIntoView(activeControl); } protected virtual void UpdateDefaultButton() { } private bool SetActiveControl(Control value) { if (activeControl == value) { return true; } activeControl = value; if (!validating && unvalidatedControl == null) { // Set the unvalidatedControl to outermost active control. // Start with the focused control. unvalidatedControl = focusedControl; while (true) { ContainerControl c = unvalidatedControl as ContainerControl; if (c == null || c.activeControl == null) { break; } unvalidatedControl = c.activeControl; } } // Go through the hierarchy, doing the leave and enter events, as we change active control. Control currentFocusedControl = focusedControl; ReDo: while (activeControl != currentFocusedControl) { if (currentFocusedControl == null || IsParent(currentFocusedControl, activeControl)) { Control currentActiveControl = activeControl; while (true) { Control parent = currentActiveControl.Parent; // Find which is lower in the hierarchy (which comes first), the active Control or the focused Control. // Set the focus to this if validated. if (parent == this || parent == currentFocusedControl) { Control prevFocusedControl = focusedControl = currentFocusedControl; ValidateEnter(currentActiveControl); if (focusedControl != prevFocusedControl) { currentFocusedControl = focusedControl; } else { currentFocusedControl = currentActiveControl; try { currentFocusedControl.DoEnter(); } catch (Exception e) { Application.OnThreadException(e); } } goto ReDo; } currentActiveControl = currentActiveControl.Parent; } } // Find innermost focused container. ContainerControl innerMostFocusedContainer = this; while (innerMostFocusedContainer.focusedControl is ContainerControl) { innerMostFocusedContainer = innerMostFocusedContainer.focusedControl as ContainerControl; } // Reset the focusedControl and activeControl of the innermost container. Control highestResetControl = null; if (innerMostFocusedContainer.focusedControl == null) { // The container has the focus set. currentFocusedControl = innerMostFocusedContainer; if (innerMostFocusedContainer.Parent != null) { // Remove the active control and focused control of this containers container. ContainerControl parentContainer = innerMostFocusedContainer.Parent.GetContainerControl() as ContainerControl; highestResetControl = parentContainer; if (parentContainer != null && parentContainer != this) { parentContainer.activeControl = null; parentContainer.focusedControl = null; } } } else { // There is a focused control of the innermost container. currentFocusedControl = innerMostFocusedContainer.focusedControl; highestResetControl = innerMostFocusedContainer; if (innerMostFocusedContainer != this) { innerMostFocusedContainer.focusedControl = null; if (innerMostFocusedContainer.Parent == null || !(innerMostFocusedContainer.Parent is MdiClient)) { innerMostFocusedContainer.activeControl = null; } } } // Do all the leave events up the hierarchy. do { Control prevFocusedControl = currentFocusedControl; if (currentFocusedControl != null) { currentFocusedControl = currentFocusedControl.Parent; } if (currentFocusedControl == this) { currentFocusedControl = null; } if (prevFocusedControl != null) { try { prevFocusedControl.DoLeave(); } catch (Exception e) { Application.OnThreadException(e); } } } while (currentFocusedControl != null && currentFocusedControl != highestResetControl && !IsParent(currentFocusedControl, activeControl)); } focusedControl = activeControl; if (activeControl != null) { ValidateEnter(activeControl); } if (activeControl == value) { Form form = FindForm(); if (form != null) { form.UpdateDefaultButton(); } } return (activeControl == value); } protected override void OnCreateControl() { base.OnCreateControl(); OnBindingContextChanged(EventArgs.Empty); } #if CONFIG_COMPONENT_MODEL [EditorBrowsable(EditorBrowsableState.Advanced)] #endif // CONFIG_COMPONENT_MODEL protected override void OnControlRemoved(ControlEventArgs e) { Control control = e.Control; // Make sure the unvalidated control and active control are cleaned up. if (control == unvalidatedControl || control.Contains(unvalidatedControl)) { unvalidatedControl = null; } if (control == activeControl || control.Contains(activeControl)) { ActiveControl = null; } base.OnControlRemoved(e); } // Brubbel internal virtual void AfterControlRemoved(Control control) { // Select next control, if control was active and removed. if (control == activeControl || control.Contains(activeControl)) { if( base.SelectNextControl( control, true, true, true, true ) ) { this.SetFocus( activeControl ); } else { this.SetActiveControl( null ); } } else if( (this.activeControl == null) && (this.Parent != null) ) { ContainerControl container = Parent.GetContainerControl() as ContainerControl; if( null != container && container.ActiveControl == this ) { Form form = base.FindForm(); if( null != form ) { form.SelectNextControl( this, true, true, true, true ); } } } else { } // Make sure the unvalidated control and active control are cleaned up. if (control == unvalidatedControl || control.Contains(unvalidatedControl)) { unvalidatedControl = null; } } #if CONFIG_COMPONENT_MODEL [EditorBrowsable(EditorBrowsableState.Advanced)] #endif // CONFIG_COMPONENT_MODEL protected override bool ProcessDialogChar(char charCode) { if (GetTopLevel()) { if(charCode != ' ' && ProcessMnemonic(charCode)) { return true; } } return base.ProcessDialogChar(charCode); } protected override bool ProcessDialogKey(Keys keyData) { if ((keyData & (Keys.Alt | Keys.Control)) == 0) { Keys key = keyData & Keys.KeyCode; if (key == Keys.Tab) { if (ProcessTabKey((keyData & Keys.Shift) == 0)) { return true; } } else if (key == Keys.Left || key == Keys.Up || key == Keys.Right || key == Keys.Down) { Control control; if (activeControl != null) { control = activeControl.Parent; } else { control = this; } bool forward = (key == Keys.Right || key == Keys.Down); if (control.SelectNextControl(activeControl, forward , false, false, true)) { return true; } } } return base.ProcessDialogKey(keyData); } protected override bool ProcessMnemonic(char charCode) { if (Controls.Count == 0) { return false; } Control active = ActiveControl; // Find the bottom most active control or the container if there isn't one. while (true) { ContainerControl container = active as ContainerControl; if (container == null) { break; } Control newActiveControl = container.ActiveControl; if (newActiveControl == null) { break; } active = newActiveControl; } // Process the mnemonics if needed. bool back = false; Control mnemonicControl = active; do { mnemonicControl = GetNextControl(mnemonicControl, true); if (mnemonicControl == null) { if (back) { break; } back = true; } else { if (mnemonicControl.ProcessMnemonicInternal(charCode)) { return true; } } } while (mnemonicControl != active); return false; } private new void ScrollControlIntoView(Control control) { // Find scrollable parent. while (true) { control = control.Parent; if (control == null) { return; } ScrollableControl scrollableControl = control as ScrollableControl; if (scrollableControl != null) { scrollableControl.ScrollControlIntoView(activeControl); continue; } } } protected override void Select(bool directed, bool forward) { if (Parent != null) { IContainerControl container = Parent.GetContainerControl(); if (container != null) { container.ActiveControl = this; if (directed && container.ActiveControl == this) { SelectNextControl(null, forward, true, true, false); } } } if (directed) { SelectNextControl(null, forward, true, true, false); } } private void ValidateEnter(Control control) { if (unvalidatedControl == null || control.CausesValidation) { return; } while (control != null && !IsParent(control, unvalidatedControl)) { control = control.Parent; } ValidateHierarchy(control); } public bool Validate() { if (unvalidatedControl == null) { if (focusedControl is ContainerControl && focusedControl.CausesValidation) { (focusedControl as ContainerControl).Validate(); } else { unvalidatedControl = focusedControl; } } return ValidateHierarchy(null); } // Validate from control back up to unvalidated or the currently focused control. private bool ValidateHierarchy(Control control) { if (unvalidatedControl == null) { unvalidatedControl = focusedControl; return true; } if (validating) { return false; } if (control == null) { control = this; } if (!IsParent(control, unvalidatedControl)) { return false; } validating = true; bool cancelValidate = false; Control currentControl = unvalidatedControl; // Validate starts off uncancelled. if (activeControl != null) { activeControl.DoValidationCancel(false); } try { while(currentControl != control) { // Do the validating and validated events if needed. if (currentControl.CausesValidation) { bool cancelled = false; try { cancelled = currentControl.DoValidating(); } catch (Exception) { cancelValidate = true; throw; } if (cancelled) { cancelValidate = true; break; } try { currentControl.DoValidated(); } catch (Exception e) { Application.OnThreadException(e); } } // Move up the hierarchy. currentControl = currentControl.Parent; } if (cancelValidate) { if (activeControl != null) { activeControl.DoValidationCancel(true); if (activeControl is ContainerControl) { ContainerControl containerControl = activeControl as ContainerControl; if (containerControl.focusedControl != null) { containerControl.focusedControl.DoValidationCancel(true); } containerControl.ResetControlsRecursive(); } } ActiveControl = unvalidatedControl; } } finally { unvalidatedControl = null; validating = false; } return !cancelValidate; } internal void ResetControlsRecursive() { if (activeControl is ContainerControl) { (activeControl as ContainerControl).ResetControlsRecursive(); } focusedControl = null; activeControl = null; } private bool IsParent(Control parent, Control control) { while (control != null) { if (parent == control) { return true; } control = control.Parent; } return false; } // Dispose of this control. protected override void Dispose(bool disposing) { activeControl = null; focusedControl = null; unvalidatedControl = null; base.Dispose(disposing); } // Process the tab key. protected virtual bool ProcessTabKey(bool forward) { return SelectNextControl(activeControl, forward, true, true, false); } private void SetFocus(Control control) { if (control != null && control.toolkitWindow != null && control.Visible) { control.toolkitWindow.Focus(); return; } // Find the first visible container. ContainerControl container = this; Control parent; while (container != null && !container.Visible) { parent = container.Parent; if (parent == null) { if (container.Visible) { container.toolkitWindow.Focus(); } break; } container = parent.GetContainerControl() as ContainerControl; } } protected override void OnGotFocus(EventArgs e) { if (ActiveControl != null) { if (!ActiveControl.Visible) { base.OnGotFocus(EventArgs.Empty); } SetFocus(activeControl); return; } if (Parent != null) { IContainerControl container = Parent.GetContainerControl(); if (container != null) { if (!container.ActivateControl(this)) { return; } } } base.OnGotFocus (e); } #if !CONFIG_COMPACT_FORMS // Process a message. #if CONFIG_COMPONENT_MODEL [EditorBrowsable(EditorBrowsableState.Advanced)] #endif // CONFIG_COMPONENT_MODEL protected override void WndProc(ref Message m) { base.WndProc(ref m); } #endif // !CONFIG_COMPACT_FORMS }; // class ContainerControl }; // namespace System.Windows.Forms
using System; using System.Collections.Generic; using System.Linq; using BugsnagUnity.Payload; using UnityEngine; namespace BugsnagUnity { public class Configuration : IMetadataEditor, IFeatureFlagStore { public string AppType; public string BundleVersion; public string[] RedactedKeys = new string[] { "password" }; public int VersionCode = -1; public long LaunchDurationMillis = 5000; public ThreadSendPolicy SendThreads = ThreadSendPolicy.UnhandledOnly; public bool SendLaunchCrashesSynchronously = true; public bool GenerateAnonymousId = true; public bool PersistUser = true; public string HostName; private User _user = null; internal Metadata Metadata = new Metadata(); internal List<FeatureFlag> FeatureFlags = new List<FeatureFlag>(); public bool KeyIsRedacted(string key) { if (RedactedKeys == null || RedactedKeys.Length == 0) { return false; } foreach (var redactedKey in RedactedKeys) { if (key.ToLower() == redactedKey.ToLower()) { return true; } } return false; } public Configuration(string apiKey) { ApiKey = apiKey; } public string PersistenceDirectory; public bool ReportExceptionLogsAsHandled = true; public TimeSpan MaximumLogsTimePeriod = TimeSpan.FromSeconds(1); public Dictionary<LogType, int> MaximumTypePerTimePeriod = new Dictionary<LogType, int> { { LogType.Assert, 5 }, { LogType.Error, 5 }, { LogType.Exception, 20 }, { LogType.Log, 5 }, { LogType.Warning, 5 }, }; public TimeSpan SecondsPerUniqueLog = TimeSpan.FromSeconds(5); public LogType BreadcrumbLogLevel = LogType.Log; public bool ShouldLeaveLogBreadcrumb(LogType logType) { return IsBreadcrumbTypeEnabled(BreadcrumbType.Log) && logType.IsGreaterThanOrEqualTo(BreadcrumbLogLevel); } public BreadcrumbType[] EnabledBreadcrumbTypes { get; set; } public bool IsBreadcrumbTypeEnabled(BreadcrumbType breadcrumbType) { return EnabledBreadcrumbTypes == null || EnabledBreadcrumbTypes.Contains(breadcrumbType); } public string ApiKey { get; set; } private int _maximumBreadcrumbs = 50; public int MaximumBreadcrumbs { get { return _maximumBreadcrumbs; } set { if (value < 0 || value > 100) { if (IsRunningInEditor()) { Debug.LogError("Invalid configuration value detected. Option maxBreadcrumbs should be an integer between 0-100. Supplied value is " + value); } return; } else { _maximumBreadcrumbs = value; } } } public string ReleaseStage = "production"; public string[] EnabledReleaseStages; public string[] ProjectPackages; public string AppVersion = Application.version; public EndpointConfiguration Endpoints = new EndpointConfiguration(); internal string PayloadVersion { get; } = "4.0"; internal string SessionPayloadVersion { get; } = "1.0"; public string Context; public LogType NotifyLogLevel = LogType.Exception; public bool AutoDetectErrors = true; public bool AutoTrackSessions = true; public LogTypeSeverityMapping LogTypeSeverityMapping { get; } = new LogTypeSeverityMapping(); public string ScriptingBackend; public string DotnetScriptingRuntime; public string DotnetApiCompatibility; public EnabledErrorTypes EnabledErrorTypes = new EnabledErrorTypes(); private ulong _appHangThresholdMillis = 0; public ulong AppHangThresholdMillis { get { return _appHangThresholdMillis; } set { if (value < 250) { if (IsRunningInEditor()) { Debug.LogError("Invalid configuration value detected. Option AppHangThresholdMillis should be a ulong higher than 249. Supplied value is " + value); } return; } else { _appHangThresholdMillis = value; } } } public string[] DiscardClasses; public int MaxPersistedEvents = 32; public int MaxPersistedSessions = 128; internal bool ErrorClassIsDiscarded(string className) { return DiscardClasses != null && DiscardClasses.Contains(className); } private bool IsRunningInEditor() { return Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.LinuxEditor; } private List<Func<IEvent, bool>> _onErrorCallbacks = new List<Func<IEvent, bool>>(); public void AddOnError(Func<IEvent, bool> callback) { _onErrorCallbacks.Add(callback); } internal List<Func<IEvent, bool>> GetOnErrorCallbacks() { return _onErrorCallbacks; } public void RemoveOnError(Func<IEvent, bool> callback) { _onErrorCallbacks.Remove(callback); } private List<Func<IEvent, bool>> _onSendErrorCallbacks = new List<Func<IEvent, bool>>(); public void AddOnSendError(Func<IEvent, bool> callback) { _onSendErrorCallbacks.Add(callback); } internal List<Func<IEvent, bool>> GetOnSendErrorCallbacks() { return _onSendErrorCallbacks; } public void RemoveOnSendError(Func<IEvent, bool> callback) { _onSendErrorCallbacks.Remove(callback); } private List<Func<ISession, bool>> _onSessionCallbacks = new List<Func<ISession, bool>>(); public void AddOnSession(Func<ISession, bool> callback) { _onSessionCallbacks.Add(callback); } public void RemoveOnSession(Func<ISession, bool> callback) { _onSessionCallbacks.Remove(callback); } internal List<Func<ISession, bool>> GetOnSessionCallbacks() { return _onSessionCallbacks; } public void AddMetadata(string section, string key, object value) => Metadata.AddMetadata(section, key, value); public void AddMetadata(string section, IDictionary<string, object> metadata) => Metadata.AddMetadata(section, metadata); public void ClearMetadata(string section) => Metadata.ClearMetadata(section); public void ClearMetadata(string section, string key) => Metadata.ClearMetadata(section, key); public IDictionary<string, object> GetMetadata(string section) => Metadata.GetMetadata(section); public object GetMetadata(string section, string key) => Metadata.GetMetadata(section, key); public User GetUser() => _user; public void SetUser(string id, string email, string name) { _user = new User(id, email, name); } internal Configuration Clone() { var clone = (Configuration)MemberwiseClone(); if (_user != null) { clone._user = _user.Clone(); } if (Endpoints.IsValid) { clone.Endpoints = Endpoints.Clone(); } return clone; } public void AddFeatureFlag(string name, string variant = null) { foreach (var flag in FeatureFlags) { if (flag.Name.Equals(name)) { flag.Variant = variant; return; } } FeatureFlags.Add(new FeatureFlag(name,variant)); } public void AddFeatureFlags(FeatureFlag[] featureFlags) { foreach (var flag in featureFlags) { AddFeatureFlag(flag.Name,flag.Variant); } } public void ClearFeatureFlag(string name) { FeatureFlags.RemoveAll(item => item.Name == name); } public void ClearFeatureFlags() { FeatureFlags.Clear(); } } [Serializable] public class EnabledErrorTypes { public bool ANRs = true; public bool AppHangs = true; public bool OOMs = true; public bool Crashes = true; public bool ThermalKills = true; public bool UnityLog = true; public EnabledErrorTypes() { } } }
/* * 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 log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Services.InventoryService { /// <summary> /// The Inventory service reference implementation /// </summary> public class InventoryService : InventoryServiceBase, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public InventoryService(IConfigSource config) : base(config) { m_log.Debug("[INVENTORY SERVICE]: Initialized."); } #region IInventoryServices methods public string Host { get { return "default"; } } public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { m_log.DebugFormat("[INVENTORY SERVICE]: Getting inventory skeleton for {0}", userId); InventoryFolderBase rootFolder = GetRootFolder(userId); // Agent has no inventory structure yet. if (null == rootFolder) { return null; } List<InventoryFolderBase> userFolders = new List<InventoryFolderBase>(); userFolders.Add(rootFolder); IList<InventoryFolderBase> folders = m_Database.getFolderHierarchy(rootFolder.ID); userFolders.AddRange(folders); // m_log.DebugFormat("[INVENTORY SERVICE]: Got folder {0} {1}", folder.name, folder.folderID); return userFolders; } public virtual bool HasInventoryForUser(UUID userID) { return false; } // See IInventoryServices public virtual InventoryFolderBase GetRootFolder(UUID userID) { //m_log.DebugFormat("[INVENTORY SERVICE]: Getting root folder for {0}", userID); // Retrieve the first root folder we get from the DB. InventoryFolderBase rootFolder = m_Database.getUserRootFolder(userID); if (rootFolder != null) return rootFolder; // Return nothing if the plugin was unable to supply a root folder return null; } // See IInventoryServices public bool CreateUserInventory(UUID user) { InventoryFolderBase existingRootFolder; try { existingRootFolder = GetRootFolder(user); } catch (Exception e) { // Munch the exception, it has already been reported // return false; } if (null != existingRootFolder) { m_log.WarnFormat( "[INVENTORY SERVICE]: Did not create a new inventory for user {0} since they already have " + "a root inventory folder with id {1}", user, existingRootFolder.ID); } else { UsersInventory inven = new UsersInventory(); inven.CreateNewInventorySet(user); AddNewInventorySet(inven); return true; } return false; } // See IInventoryServices /// <summary> /// Return a user's entire inventory synchronously /// </summary> /// <param name="rawUserID"></param> /// <returns>The user's inventory. If an inventory cannot be found then an empty collection is returned.</returns> public InventoryCollection GetUserInventory(UUID userID) { m_log.InfoFormat("[INVENTORY SERVICE]: Processing request for inventory of {0}", userID); // Uncomment me to simulate a slow responding inventory server //Thread.Sleep(16000); InventoryCollection invCollection = new InventoryCollection(); List<InventoryFolderBase> allFolders = GetInventorySkeleton(userID); if (null == allFolders) { m_log.WarnFormat("[INVENTORY SERVICE]: No inventory found for user {0}", userID); return invCollection; } List<InventoryItemBase> allItems = new List<InventoryItemBase>(); foreach (InventoryFolderBase folder in allFolders) { List<InventoryItemBase> items = GetFolderItems(userID, folder.ID); if (items != null) { allItems.InsertRange(0, items); } } invCollection.UserID = userID; invCollection.Folders = allFolders; invCollection.Items = allItems; // foreach (InventoryFolderBase folder in invCollection.Folders) // { // m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back folder {0} {1}", folder.Name, folder.ID); // } // // foreach (InventoryItemBase item in invCollection.Items) // { // m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back item {0} {1}, folder {2}", item.Name, item.ID, item.Folder); // } m_log.InfoFormat( "[INVENTORY SERVICE]: Sending back inventory response to user {0} containing {1} folders and {2} items", invCollection.UserID, invCollection.Folders.Count, invCollection.Items.Count); return invCollection; } /// <summary> /// Asynchronous inventory fetch. /// </summary> /// <param name="userID"></param> /// <param name="callback"></param> public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) { m_log.InfoFormat("[INVENTORY SERVICE]: Requesting inventory for user {0}", userID); List<InventoryFolderImpl> folders = new List<InventoryFolderImpl>(); List<InventoryItemBase> items = new List<InventoryItemBase>(); List<InventoryFolderBase> skeletonFolders = GetInventorySkeleton(userID); if (skeletonFolders != null) { InventoryFolderImpl rootFolder = null; // Need to retrieve the root folder on the first pass foreach (InventoryFolderBase folder in skeletonFolders) { if (folder.ParentID == UUID.Zero) { rootFolder = new InventoryFolderImpl(folder); folders.Add(rootFolder); items.AddRange(GetFolderItems(userID, rootFolder.ID)); break; // Only 1 root folder per user } } if (rootFolder != null) { foreach (InventoryFolderBase folder in skeletonFolders) { if (folder.ID != rootFolder.ID) { folders.Add(new InventoryFolderImpl(folder)); items.AddRange(GetFolderItems(userID, folder.ID)); } } } m_log.InfoFormat( "[INVENTORY SERVICE]: Received inventory response for user {0} containing {1} folders and {2} items", userID, folders.Count, items.Count); } else { m_log.WarnFormat("[INVENTORY SERVICE]: User {0} inventory not available", userID); } Util.FireAndForget(delegate { callback(folders, items); }); } public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { // Uncomment me to simulate a slow responding inventory server //Thread.Sleep(16000); InventoryCollection invCollection = new InventoryCollection(); List<InventoryItemBase> items = GetFolderItems(userID, folderID); List<InventoryFolderBase> folders = RequestSubFolders(folderID); invCollection.UserID = userID; invCollection.Folders = folders; invCollection.Items = items; m_log.DebugFormat("[INVENTORY SERVICE]: Found {0} items and {1} folders in folder {2}", items.Count, folders.Count, folderID); return invCollection; } public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) { InventoryFolderBase root = m_Database.getUserRootFolder(userID); if (root != null) { List<InventoryFolderBase> folders = RequestSubFolders(root.ID); foreach (InventoryFolderBase folder in folders) { if (folder.Type == (short)type) return folder; } } // we didn't find any folder of that type. Return the root folder // hopefully the root folder is not null. If it is, too bad return root; } public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID) { InventoryFolderBase root = GetRootFolder(userID); if (root != null) { InventoryCollection content = GetFolderContent(userID, root.ID); if (content != null) { Dictionary<AssetType, InventoryFolderBase> folders = new Dictionary<AssetType, InventoryFolderBase>(); foreach (InventoryFolderBase folder in content.Folders) { if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown)) folders[(AssetType)folder.Type] = folder; } return folders; } } m_log.WarnFormat("[INVENTORY SERVICE]: System folders for {0} not found", userID); return new Dictionary<AssetType, InventoryFolderBase>(); } public List<InventoryItemBase> GetActiveGestures(UUID userId) { List<InventoryItemBase> activeGestures = new List<InventoryItemBase>(); activeGestures.AddRange(m_Database.fetchActiveGestures(userId)); return activeGestures; } #endregion #region Methods used by GridInventoryService public List<InventoryFolderBase> RequestSubFolders(UUID parentFolderID) { List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>(); inventoryList.AddRange(m_Database.getInventoryFolders(parentFolderID)); return inventoryList; } public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { List<InventoryItemBase> itemsList = new List<InventoryItemBase>(); itemsList.AddRange(m_Database.getInventoryInFolder(folderID)); return itemsList; } #endregion // See IInventoryServices public virtual bool AddFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Adding folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); m_Database.addInventoryFolder(folder); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool UpdateFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Updating folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); m_Database.updateInventoryFolder(folder); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool MoveFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Moving folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID); m_Database.moveInventoryFolder(folder); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool AddItem(InventoryItemBase item) { m_log.DebugFormat( "[INVENTORY SERVICE]: Adding item {0} {1} to folder {2}", item.Name, item.ID, item.Folder); m_Database.addInventoryItem(item); // FIXME: Should return false on failure return true; } // See IInventoryServices public virtual bool UpdateItem(InventoryItemBase item) { m_log.InfoFormat( "[INVENTORY SERVICE]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder); m_Database.updateInventoryItem(item); // FIXME: Should return false on failure return true; } public virtual bool MoveItems(UUID ownerID, List<InventoryItemBase> items) { m_log.InfoFormat( "[INVENTORY SERVICE]: Moving {0} items from user {1}", items.Count, ownerID); InventoryItemBase itm = null; foreach (InventoryItemBase item in items) { itm = GetInventoryItem(item.ID); itm.Folder = item.Folder; if ((item.Name != null) && !item.Name.Equals(string.Empty)) itm.Name = item.Name; m_Database.updateInventoryItem(itm); } return true; } // See IInventoryServices public virtual bool DeleteItems(UUID owner, List<UUID> itemIDs) { m_log.InfoFormat( "[INVENTORY SERVICE]: Deleting {0} items from user {1}", itemIDs.Count, owner); // uhh..... foreach (UUID uuid in itemIDs) m_Database.deleteInventoryItem(uuid); // FIXME: Should return false on failure return true; } public virtual InventoryItemBase GetItem(InventoryItemBase item) { InventoryItemBase result = m_Database.getInventoryItem(item.ID); if (result != null) return result; m_log.DebugFormat("[INVENTORY SERVICE]: GetItem failed to find item {0}", item.ID); return null; } public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder) { InventoryFolderBase result = m_Database.getInventoryFolder(folder.ID); if (result != null) return result; m_log.DebugFormat("[INVENTORY SERVICE]: GetFolder failed to find folder {0}", folder.ID); return null; } public virtual bool DeleteFolders(UUID ownerID, List<UUID> folderIDs) { m_log.InfoFormat("[INVENTORY SERVICE]: Deleting {0} folders from user {1}", folderIDs.Count, ownerID); foreach (UUID id in folderIDs) { InventoryFolderBase folder = new InventoryFolderBase(id, ownerID); PurgeFolder(folder); m_Database.deleteInventoryFolder(id); } return true; } /// <summary> /// Purge a folder of all items items and subfolders. /// /// FIXME: Really nasty in a sense, because we have to query the database to get information we may /// already know... Needs heavy refactoring. /// </summary> /// <param name="folder"></param> public virtual bool PurgeFolder(InventoryFolderBase folder) { m_log.DebugFormat( "[INVENTORY SERVICE]: Purging folder {0} {1} of its contents", folder.Name, folder.ID); List<InventoryFolderBase> subFolders = RequestSubFolders(folder.ID); foreach (InventoryFolderBase subFolder in subFolders) { // m_log.DebugFormat("[INVENTORY SERVICE]: Deleting folder {0} {1}", subFolder.Name, subFolder.ID); m_Database.deleteInventoryFolder(subFolder.ID); } List<InventoryItemBase> items = GetFolderItems(folder.Owner, folder.ID); List<UUID> uuids = new List<UUID>(); foreach (InventoryItemBase item in items) { uuids.Add(item.ID); } DeleteItems(folder.Owner, uuids); // FIXME: Should return false on failure return true; } private void AddNewInventorySet(UsersInventory inventory) { foreach (InventoryFolderBase folder in inventory.Folders.Values) { AddFolder(folder); } } public InventoryItemBase GetInventoryItem(UUID itemID) { InventoryItemBase item = m_Database.getInventoryItem(itemID); if (item != null) return item; return null; } public int GetAssetPermissions(UUID userID, UUID assetID) { InventoryFolderBase parent = GetRootFolder(userID); return FindAssetPerms(parent, assetID); } private int FindAssetPerms(InventoryFolderBase folder, UUID assetID) { InventoryCollection contents = GetFolderContent(folder.Owner, folder.ID); int perms = 0; foreach (InventoryItemBase item in contents.Items) { if (item.AssetID == assetID) perms = (int)item.CurrentPermissions | perms; } foreach (InventoryFolderBase subfolder in contents.Folders) perms = perms | FindAssetPerms(subfolder, assetID); return perms; } /// <summary> /// Used to create a new user inventory. /// </summary> private class UsersInventory { public Dictionary<UUID, InventoryFolderBase> Folders = new Dictionary<UUID, InventoryFolderBase>(); public Dictionary<UUID, InventoryItemBase> Items = new Dictionary<UUID, InventoryItemBase>(); public virtual void CreateNewInventorySet(UUID user) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ParentID = UUID.Zero; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "My Inventory"; folder.Type = (short)AssetType.Folder; folder.Version = 1; Folders.Add(folder.ID, folder); UUID rootFolder = folder.ID; folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Animations"; folder.Type = (short)AssetType.Animation; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Body Parts"; folder.Type = (short)AssetType.Bodypart; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Calling Cards"; folder.Type = (short)AssetType.CallingCard; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Clothing"; folder.Type = (short)AssetType.Clothing; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Gestures"; folder.Type = (short)AssetType.Gesture; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Landmarks"; folder.Type = (short)AssetType.Landmark; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Lost And Found"; folder.Type = (short)AssetType.LostAndFoundFolder; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Notecards"; folder.Type = (short)AssetType.Notecard; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Objects"; folder.Type = (short)AssetType.Object; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Photo Album"; folder.Type = (short)AssetType.SnapshotFolder; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Scripts"; folder.Type = (short)AssetType.LSLText; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Sounds"; folder.Type = (short)AssetType.Sound; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Textures"; folder.Type = (short)AssetType.Texture; folder.Version = 1; Folders.Add(folder.ID, folder); folder = new InventoryFolderBase(); folder.ParentID = rootFolder; folder.Owner = user; folder.ID = UUID.Random(); folder.Name = "Trash"; folder.Type = (short)AssetType.TrashFolder; folder.Version = 1; Folders.Add(folder.ID, folder); } } } }
using UnityEngine; using UnityEditor; using System.Collections; using Pathfinding; [CustomGraphEditor (typeof(RecastGraph),"RecastGraph")] /** \astarpro */ public class RecastGraphEditor : GraphEditor { #if UNITY_3_5 public GameObject meshRenderer; public MeshFilter meshFilter; #endif public Mesh navmeshRender; public Renderer navmeshRenderer; /** Material to use for navmeshes in the editor */ public static Material navmeshMaterial; public static bool tagMaskFoldout = false; public override void OnEnable () { #if UNITY_3_5 CreateDebugMesh (); #else UpdateDebugMesh (editor.script); #endif //Get a callback when scanning has finished AstarPath.OnLatePostScan += UpdateDebugMesh; } public override void OnDestroy () { #if UNITY_3_5 if (meshRenderer != null) { GameObject.DestroyImmediate (meshRenderer); } #else //Avoid memory leak Mesh.DestroyImmediate (navmeshRender); #endif } public override void OnDisable () { AstarPath.OnLatePostScan -= UpdateDebugMesh; #if UNITY_3_5 if (meshRenderer != null) { //GameObject.DestroyImmediate (meshRenderer); } #endif } #if UNITY_3_5 public void CreateDebugMesh () { RecastGraph graph = target as RecastGraph; meshRenderer = GameObject.Find ("RecastGraph_"+graph.guid.ToString ()); if (meshRenderer == null || meshFilter == null || navmeshRender == null || navmeshRenderer == null) { if (meshRenderer == null) { meshRenderer = new GameObject ("RecastGraph_"+graph.guid.ToString ()); meshRenderer.hideFlags = /*HideFlags.NotEditable |*/ HideFlags.DontSave; } if (meshRenderer.GetComponent<NavMeshRenderer>() == null) { meshRenderer.AddComponent<NavMeshRenderer>(); } MeshFilter filter; if ((filter = meshRenderer.GetComponent<MeshFilter>()) == null) { filter = meshRenderer.AddComponent<MeshFilter>(); } navmeshRenderer = meshRenderer.GetComponent<MeshRenderer>(); if (navmeshRenderer == null) { navmeshRenderer = meshRenderer.AddComponent<MeshRenderer>(); navmeshRenderer.castShadows = false; navmeshRenderer.receiveShadows = false; } if (filter.sharedMesh == null) { navmeshRender = new Mesh (); filter.sharedMesh = navmeshRender; } else { navmeshRender = filter.sharedMesh; } navmeshRender.name = "Navmesh_"+graph.guid.ToString (); } if (navmeshMaterial == null) { navmeshMaterial = AssetDatabase.LoadAssetAtPath (AstarPathEditor.editorAssets + "/Materials/Navmesh.mat",typeof(Material)) as Material; if (navmeshMaterial == null) { Debug.LogWarning ("Could not find navmesh material at path "+AstarPathEditor.editorAssets + "/Materials/Navmesh.mat"); } navmeshRenderer.material = navmeshMaterial; } } #endif public void UpdateDebugMesh (AstarPath astar) { #if UNITY_3_5 CreateDebugMesh (); meshRenderer.transform.position = Vector3.zero; meshRenderer.transform.localScale = Vector3.one; #endif RecastGraph graph = target as RecastGraph; if (graph != null && graph.nodes != null && graph.vectorVertices != null) { if (navmeshRender == null) navmeshRender = new Mesh(); navmeshRender.Clear (); navmeshRender.vertices = graph.vectorVertices; int[] tris = new int[graph.nodes.Length*3]; Color[] vColors = new Color[graph.vectorVertices.Length]; for (int i=0;i<graph.nodes.Length;i++) { MeshNode node = graph.nodes[i] as MeshNode; tris[i*3] = node.v1; tris[i*3+1] = node.v2; tris[i*3+2] = node.v3; Color col = Mathfx.IntToColor (node.area,1F); vColors[node.v1] = col; vColors[node.v2] = col; vColors[node.v3] = col; } navmeshRender.triangles = tris; navmeshRender.colors = vColors; //meshRenderer.transform.position = graph.forcedBoundsCenter-graph.forcedBoundsSize*0.5F; //meshRenderer.transform.localScale = Int3.Precision*Voxelize.CellScale; navmeshRender.RecalculateNormals (); navmeshRender.RecalculateBounds (); if (navmeshMaterial == null) { navmeshMaterial = AssetDatabase.LoadAssetAtPath (AstarPathEditor.editorAssets + "/Materials/Navmesh.mat",typeof(Material)) as Material; } navmeshRender.hideFlags = HideFlags.HideAndDontSave; #if UNITY_3_5 navmeshRenderer.material = navmeshMaterial; #endif } } public override void OnSceneGUI (NavGraph target) { #if UNITY_3_5 if (navmeshRenderer != null) { navmeshRenderer.enabled = editor.script.showNavGraphs; } #else if (editor.script.showNavGraphs) { //navmeshMaterial, 0 if (navmeshRender != null && navmeshMaterial != null) { //Render the navmesh-mesh. The shader has three passes if (navmeshMaterial.SetPass (0)) Graphics.DrawMeshNow (navmeshRender, Matrix4x4.identity); if (navmeshMaterial.SetPass (1)) Graphics.DrawMeshNow (navmeshRender, Matrix4x4.identity); if (navmeshMaterial.SetPass (2)) Graphics.DrawMeshNow (navmeshRender, Matrix4x4.identity); } } #endif } public override void OnDrawGizmos () { } public override void OnInspectorGUI (NavGraph target) { RecastGraph graph = target as RecastGraph; bool preEnabled = GUI.enabled; //if (graph.forceBounds) { graph.useCRecast = GUILayout.Toolbar (graph.useCRecast ?1:0,new GUIContent[2] { new GUIContent ("C# Recast","I have translated a portion of Recast to C#, this can be used in a webplayer but is more limited than the C++ version"), new GUIContent ("C++ Recast","Use the original C++ version of Recast, faster scanning times and has more features than the C# version, but it can only be used in the editor or on standalone applications (note that you can still scan the graph in the editor and then cache the startup if you want to build for a webplayer)" +"\nTake a look in the docs on RecastGraph.useCRecast for more information on the special considerations when using this mode")}) == 1; if (graph.useCRecast) { BuildTarget bt = EditorUserBuildSettings.activeBuildTarget; if (bt != BuildTarget.StandaloneOSXIntel) { if (GUILayout.Button ("Note that the C++ version of Recast does not work in your selected build target ("+bt+")\n" + "Change build target to standalone (osx) if you want to be able to use C++\n" + "Click here for more info",AstarPathEditor.helpBox)) { Application.OpenURL (AstarPathEditor.GetURL ("cRecastHelp")); } } else { if (GUILayout.Button ("Note the special considerations when using C++ Recast\nClick here for more info",AstarPathEditor.helpBox)) { Application.OpenURL (AstarPathEditor.GetURL ("cRecastHelp")); } } if (Application.platform == RuntimePlatform.WindowsEditor) { GUILayout.Label ("C++ Recast can currently not be used on Windows",AstarPathEditor.helpBox); } } System.Int64 estWidth = Mathf.RoundToInt (Mathf.Ceil (graph.forcedBoundsSize.x / graph.cellSize)); System.Int64 estDepth = Mathf.RoundToInt (Mathf.Ceil (graph.forcedBoundsSize.z / graph.cellSize)); if (estWidth*estDepth >= 1024*1024 || estDepth >= 1024*1024 || estWidth >= 1024*1024) { GUIStyle helpBox = GUI.skin.FindStyle ("HelpBox"); if (helpBox == null) helpBox = GUI.skin.FindStyle ("Box"); Color preColor = GUI.color; if (estWidth*estDepth >= 2048*2048 || estDepth >= 2048*2048 || estWidth >= 2048*2048) { GUI.color = Color.red; } else { GUI.color = Color.yellow; } GUILayout.Label ("Warning : Might take some time to calculate",helpBox); GUI.color = preColor; } GUI.enabled = false; EditorGUILayout.LabelField ("Width (samples)",estWidth.ToString ()); EditorGUILayout.LabelField ("Depth (samples)",estDepth.ToString ()); /*} else { GUI.enabled = false; EditorGUILayout.LabelField ("Width (samples)","undetermined"); EditorGUILayout.LabelField ("Depth (samples)","undetermined"); }*/ GUI.enabled = preEnabled; graph.cellSize = EditorGUILayout.FloatField (new GUIContent ("Cell Size","Size of one voxel in world units"),graph.cellSize); if (graph.cellSize < 0.001F) graph.cellSize = 0.001F; graph.cellHeight = EditorGUILayout.FloatField (new GUIContent ("Cell Height","Height of one voxel in world units"),graph.cellHeight); if (graph.cellHeight < 0.001F) graph.cellHeight = 0.001F; graph.walkableHeight = EditorGUILayout.FloatField (new GUIContent ("Walkable Height","Minimum distance to the roof for an area to be walkable"),graph.walkableHeight); graph.walkableClimb = EditorGUILayout.FloatField (new GUIContent ("Walkable Climb","How high can the character climb"),graph.walkableClimb); graph.characterRadius = EditorGUILayout.FloatField (new GUIContent ("Character Radius","Radius of the character, it's good to add some margin though"),graph.characterRadius); if(graph.useCRecast) { graph.regionMinSize = EditorGUILayout.IntField (new GUIContent ("Min Region Size","The lowest number of voxles in one area for it not to be deleted"),graph.regionMinSize); } graph.maxSlope = EditorGUILayout.Slider (new GUIContent ("Max Slope","Approximate maximum slope"),graph.maxSlope,0F,90F); graph.maxEdgeLength = EditorGUILayout.FloatField (new GUIContent ("Max Edge Length","Maximum length of one edge in the completed navmesh before it is split. A lower value can often yield better quality graphs"),graph.maxEdgeLength); graph.maxEdgeLength = graph.maxEdgeLength < graph.cellSize ? graph.cellSize : graph.maxEdgeLength; /*if (!graph.useCRecast) { graph.erosionRadius = EditorGUILayout.IntSlider ("Erosion radius",graph.erosionRadius,0,256); }*/ graph.contourMaxError = EditorGUILayout.FloatField (new GUIContent ("Max edge error","Amount of simplification to apply to edges"),graph.contourMaxError); graph.rasterizeTerrain = EditorGUILayout.Toggle (new GUIContent ("Rasterize Terrain","Should a rasterized terrain be included"), graph.rasterizeTerrain); if (graph.rasterizeTerrain) { EditorGUI.indentLevel++; graph.rasterizeTrees = EditorGUILayout.Toggle (new GUIContent ("Rasterize Trees", "Rasterize tree colliders on terrains. " + "If the tree prefab has a collider, that collider will be rasterized. " + "Otherwise a simple box collider will be used and the script will " + "try to adjust it to the tree's scale, it might not do a very good job though so " + "an attached collider is preferable."), graph.rasterizeTrees); if (graph.rasterizeTrees) { EditorGUI.indentLevel++; graph.colliderRasterizeDetail = EditorGUILayout.FloatField (new GUIContent ("Collider Detail", "Controls the detail of the generated collider meshes. Increasing does not necessarily yield better navmeshes, but lowering will speed up scan"), graph.colliderRasterizeDetail); EditorGUI.indentLevel--; } graph.terrainSampleSize = EditorGUILayout.IntField (new GUIContent ("Terrain Sample Size","Size of terrain samples. A lower value is better, but slower"), graph.terrainSampleSize); graph.terrainSampleSize = graph.terrainSampleSize < 1 ? 1 : graph.terrainSampleSize;//Clamp to at least 1 EditorGUI.indentLevel--; } graph.rasterizeMeshes = EditorGUILayout.Toggle (new GUIContent ("Rasterize Meshes", "Should meshes be rasterized and used for building the navmesh"), graph.rasterizeMeshes); graph.rasterizeColliders = EditorGUILayout.Toggle (new GUIContent ("Rasterize Colliders", "Should colliders be rasterized and used for building the navmesh"), graph.rasterizeColliders); if (graph.rasterizeColliders) { EditorGUI.indentLevel++; graph.colliderRasterizeDetail = EditorGUILayout.FloatField (new GUIContent ("Collider Detail", "Controls the detail of the generated collider meshes. Increasing does not necessarily yield better navmeshes, but lowering will speed up scan"), graph.colliderRasterizeDetail); EditorGUI.indentLevel--; } graph.mask = EditorGUILayoutx.LayerMaskField ("Layer Mask",graph.mask); graph.includeOutOfBounds = EditorGUILayout.Toggle (new GUIContent ("Include out of bounds","Should voxels out of bounds, on the Y axis below the graph, be included or not"),graph.includeOutOfBounds); Separator (); graph.forcedBoundsCenter = EditorGUILayout.Vector3Field ("Center",graph.forcedBoundsCenter); graph.forcedBoundsSize = EditorGUILayout.Vector3Field ("Size",graph.forcedBoundsSize); if (GUILayout.Button (new GUIContent ("Snap bounds to scene","Will snap the bounds of the graph to exactly contain all active meshes in the scene"))) { graph.SnapForceBoundsToScene (); GUI.changed = true; } Separator (); tagMaskFoldout = EditorGUILayoutx.UnityTagMaskList (new GUIContent("Tag Mask"), tagMaskFoldout, graph.tagMask); Separator (); graph.showMeshOutline = EditorGUILayout.Toggle (new GUIContent ("Show mesh outline","Toggles gizmos for drawing an outline of the mesh"),graph.showMeshOutline); graph.accurateNearestNode = EditorGUILayout.Toggle (new GUIContent ("Accurate Nearest Node Queries","More accurate nearest node queries. See docs for more info"),graph.accurateNearestNode); if (GUILayout.Button ("Export to file")) { ExportToFile (graph); } /*graph.replaceMesh = (Mesh)ObjectField (new GUIContent ("Replacement Mesh","If you make edits to the mesh manually, you can drop the new mesh file here to import it"), graph.replaceMesh,typeof(Mesh),false); if (graph.replaceMesh != null) { HelpBox ("Note: Graph will be replaced by the mesh"); }*/ //graph.mask = 1 << EditorGUILayout.LayerField ("Mask",(int)Mathf.Log (graph.mask,2)); } /** Exports the INavmesh graph to a file */ public void ExportToFile (NavGraph target) { INavmesh graph = (INavmesh)target; if (graph == null) return; Int3[] vertices = graph.vertices; if (vertices == null || target.nodes == null) { if (EditorUtility.DisplayDialog ("Scan graph before exporting?","The graph does not contain any mesh data. Do you want to scan it?","Ok","Cancel")) { AstarPath.MenuScan (); } else { return; } } vertices = graph.vertices; if (vertices == null || target.nodes == null) { Debug.LogError ("Graph still does not contain any nodes or vertices. Canceling"); return; } string path = EditorUtility.SaveFilePanel ("Export .obj","","navmesh.obj","obj"); if (path == "") return; //Generate .obj System.Text.StringBuilder sb = new System.Text.StringBuilder(); string name = System.IO.Path.GetFileNameWithoutExtension (path); sb.Append ("g ").Append(name).AppendLine(); //Write vertices for (int i=0;i<vertices.Length;i++) { Vector3 v = (Vector3)vertices[i]; sb.Append(string.Format("v {0} {1} {2}\n",-v.x,v.y,v.z)); } //Define single texture coordinate to zero sb.Append ("vt 0\n"); //Write triangles for (int i=0;i<target.nodes.Length;i++) { MeshNode node = target.nodes[i] as MeshNode; if (node == null) { Debug.LogError ("Node could not be casted to MeshNode. Node was null or no MeshNode"); return; } sb.Append(string.Format("f {0}/0 {1}/0 {2}/0\n", node.v1+1,node.v2+1,node.v3+1)); } string obj = sb.ToString(); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path)) { sw.Write(obj); } } }
// 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.InteropServices; using System.Security; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: This is the implementation of the DataCollector /// functionality. To enable safe access to the DataCollector from /// untrusted code, there is one thread-local instance of this structure /// per thread. The instance must be Enabled before any data is written to /// it. The instance must be Finished before the data is passed to /// EventWrite. The instance must be Disabled before the arrays referenced /// by the pointers are freed or unpinned. /// </summary> internal unsafe struct DataCollector { [ThreadStatic] internal static DataCollector ThreadInstance; private byte* scratchEnd; private EventSource.EventData* datasEnd; private GCHandle* pinsEnd; private EventSource.EventData* datasStart; private byte* scratch; private EventSource.EventData* datas; private GCHandle* pins; private byte[] buffer; private int bufferPos; private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this. private bool writingScalars; internal void Enable( byte* scratch, int scratchSize, EventSource.EventData* datas, int dataCount, GCHandle* pins, int pinCount) { this.datasStart = datas; this.scratchEnd = scratch + scratchSize; this.datasEnd = datas + dataCount; this.pinsEnd = pins + pinCount; this.scratch = scratch; this.datas = datas; this.pins = pins; this.writingScalars = false; } internal void Disable() { this = new DataCollector(); } /// <summary> /// Completes the list of scalars. Finish must be called before the data /// descriptor array is passed to EventWrite. /// </summary> /// <returns> /// A pointer to the next unused data descriptor, or datasEnd if they were /// all used. (Descriptors may be unused if a string or array was null.) /// </returns> internal EventSource.EventData* Finish() { this.ScalarsEnd(); return this.datas; } internal void AddScalar(void* value, int size) { var pb = (byte*)value; if (this.bufferNesting == 0) { var scratchOld = this.scratch; var scratchNew = scratchOld + size; if (this.scratchEnd < scratchNew) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_AddScalarOutOfRange")); } this.ScalarsBegin(); this.scratch = scratchNew; for (int i = 0; i != size; i++) { scratchOld[i] = pb[i]; } } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); for (int i = 0; i != size; i++, oldPos++) { this.buffer[oldPos] = pb[i]; } } } internal void AddBinary(string value, int size) { if (size > ushort.MaxValue) { size = ushort.MaxValue - 1; } if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&size, 2); if (size != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); fixed (void* p = value) { Marshal.Copy((IntPtr)p, buffer, oldPos, size); } } } } internal void AddBinary(Array value, int size) { this.AddArray(value, size, 1); } internal void AddArray(Array value, int length, int itemSize) { if (length > ushort.MaxValue) { length = ushort.MaxValue; } var size = length * itemSize; if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&length, 2); if (length != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); Buffer.BlockCopy(value, 0, this.buffer, oldPos, size); } } } /// <summary> /// Marks the start of a non-blittable array or enumerable. /// </summary> /// <returns>Bookmark to be passed to EndBufferedArray.</returns> internal int BeginBufferedArray() { this.BeginBuffered(); this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable) return this.bufferPos; } /// <summary> /// Marks the end of a non-blittable array or enumerable. /// </summary> /// <param name="bookmark">The value returned by BeginBufferedArray.</param> /// <param name="count">The number of items in the array.</param> internal void EndBufferedArray(int bookmark, int count) { this.EnsureBuffer(); this.buffer[bookmark - 2] = unchecked((byte)count); this.buffer[bookmark - 1] = unchecked((byte)(count >> 8)); this.EndBuffered(); } /// <summary> /// Marks the start of dynamically-buffered data. /// </summary> internal void BeginBuffered() { this.ScalarsEnd(); this.bufferNesting += 1; } /// <summary> /// Marks the end of dynamically-buffered data. /// </summary> internal void EndBuffered() { this.bufferNesting -= 1; if (this.bufferNesting == 0) { /* TODO (perf): consider coalescing adjacent buffered regions into a single buffer, similar to what we're already doing for adjacent scalars. In addition, if a type contains a buffered region adjacent to a blittable array, and the blittable array is small, it would be more efficient to buffer the array instead of pinning it. */ this.EnsureBuffer(); this.PinArray(this.buffer, this.bufferPos); this.buffer = null; this.bufferPos = 0; } } private void EnsureBuffer() { var required = this.bufferPos; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void EnsureBuffer(int additionalSize) { var required = this.bufferPos + additionalSize; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void GrowBuffer(int required) { var newSize = this.buffer == null ? 64 : this.buffer.Length; do { newSize *= 2; } while (newSize < required); Array.Resize(ref this.buffer, newSize); } private void PinArray(object value, int size) { var pinsTemp = this.pins; if (this.pinsEnd <= pinsTemp) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_PinArrayOutOfRange")); } var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange")); } this.pins = pinsTemp + 1; this.datas = datasTemp + 1; *pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned); datasTemp->DataPointer = pinsTemp->AddrOfPinnedObject(); datasTemp->m_Size = size; } private void ScalarsBegin() { if (!this.writingScalars) { var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange")); } datasTemp->DataPointer = (IntPtr) this.scratch; this.writingScalars = true; } } private void ScalarsEnd() { if (this.writingScalars) { var datasTemp = this.datas; datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr)); this.datas = datasTemp + 1; this.writingScalars = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.Tests { public class EncoderConvert2Encoder : Encoder { private Encoder _encoder = null; public EncoderConvert2Encoder() { _encoder = Encoding.UTF8.GetEncoder(); } public override int GetByteCount(char[] chars, int index, int count, bool flush) { if (index >= count) throw new ArgumentException(); return _encoder.GetByteCount(chars, index, count, flush); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { return _encoder.GetBytes(chars, charIndex, charCount, bytes, byteIndex, flush); } } // Convert(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@) public class EncoderConvert2 { private const int c_SIZE_OF_ARRAY = 256; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); public static IEnumerable<object[]> Encoders_RandomInput() { yield return new object[] { Encoding.ASCII.GetEncoder() }; yield return new object[] { Encoding.UTF8.GetEncoder() }; yield return new object[] { Encoding.Unicode.GetEncoder() }; } public static IEnumerable<object[]> Encoders_Convert() { yield return new object[] { Encoding.ASCII.GetEncoder(), 1 }; yield return new object[] { Encoding.UTF8.GetEncoder(), 1 }; yield return new object[] { Encoding.Unicode.GetEncoder(), 2 }; } // Call Convert to convert an arbitrary character array encoders [Theory] [MemberData(nameof(Encoders_RandomInput))] public void EncoderConvertRandomCharArray(Encoder encoder) { char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; for (int i = 0; i < chars.Length; ++i) { chars[i] = _generator.GetChar(-55); } int charsUsed; int bytesUsed; bool completed; encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed); // set flush to true and try again encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, true, out charsUsed, out bytesUsed, out completed); } // Call Convert to convert a ASCII character array encoders [Theory] [MemberData(nameof(Encoders_Convert))] public void EncoderConvertASCIICharArray(Encoder encoder, int multiplier) { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length * multiplier]; VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length * multiplier, expectedCompleted: true); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length * multiplier, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 0, bytes, 0, 0, true, 0, 0, expectedCompleted: true); } // Call Convert to convert a ASCII character array with user implemented encoder [Fact] public void EncoderCustomConvertASCIICharArray() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = new EncoderConvert2Encoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length, expectedCompleted: true); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length, expectedCompleted: true); } // Call Convert to convert partial of a ASCII character array with UTF8 encoder [Fact] public void EncoderUTF8ConvertASCIICharArrayPartial() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, expectedCompleted: true); // Verify maxBytes is large than character count VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, expectedCompleted: true); } // Call Convert to convert partial of a ASCII character array with Unicode encoder [Fact] public void EncoderUnicodeConvertASCIICharArrayPartial() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, expectedCompleted: true); } // Call Convert to convert a Unicode character array with Unicode encoder [Fact] public void EncoderUnicodeConvertUnicodeCharArray() { char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, bytes.Length, expectedCompleted: true); VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, bytes.Length, expectedCompleted: true); } // Call Convert to convert partial of a Unicode character array with Unicode encoder [Fact] public void EncoderUnicodeConvertUnicodeCharArrayPartial() { char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.Unicode.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, expectedCompleted: true); } // Call Convert to convert partial of a ASCII character array with ASCII encoder [Fact] public void EncoderASCIIConvertASCIICharArrayPartial() { char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray(); byte[] bytes = new byte[chars.Length]; Encoder encoder = Encoding.ASCII.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, expectedCompleted: true); // Verify maxBytes is large than character count VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, expectedCompleted: true); } // Call Convert to convert partial of a Unicode character array with ASCII encoder [Fact] public void EncoderASCIIConvertUnicodeCharArrayPartial() { char[] chars = "\uD83D\uDE01Test".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.ASCII.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, 2, false, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, false, 4, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, true, 4, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, false, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 1, expectedCompleted: true); } // Call Convert to convert partial of a Unicode character array with UTF8 encoder [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue(11057)] public void EncoderUTF8ConvertUnicodeCharArrayPartial() { char[] chars = "\uD83D\uDE01Test".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 3, true, 1, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, 7, false, 2, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, false, 4, 6, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, true, 4, 6, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, false, 1, 3, expectedCompleted: false); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 0, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 4, expectedCompleted: true); } // Call Convert to convert partial of a ASCII+Unicode character array with ASCII encoder [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue(11057)] public void EncoderASCIIConvertMixedASCIIUnicodeCharArrayPartial() { char[] chars = "T\uD83D\uDE01est".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.ASCII.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 1, false, 3, 1, expectedCompleted: false); VerificationHelper(encoder, chars, 3, 1, bytes, 0, 2, false, 0, 2, expectedCompleted: false); VerificationHelper(encoder, chars, 3, 1, bytes, 0, 2, false, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 5, bytes, 0, 5, false, 5, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 4, true, 4, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 2, true, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, false, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 3, true, 3, 3, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, bytes.Length, false, 2, 2, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 1, expectedCompleted: true); } // Call Convert to convert partial of a ASCII+Unicode character array with UTF8 encoder [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue(11057)] public void EncoderUTF8ConvertMixedASCIIUnicodeCharArrayPartial() { char[] chars = "T\uD83D\uDE01est".ToCharArray(); byte[] bytes = new byte[chars.Length * 2]; Encoder encoder = Encoding.UTF8.GetEncoder(); VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, 1, false, 2, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 1, bytes, 0, 5, false, 1, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 2, bytes, 0, 7, false, 2, 4, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 5, bytes, 0, 7, false, 5, 7, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 4, bytes, 0, 6, true, 4, 6, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, 3, true, 1, 3, expectedCompleted: false); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, false, 3, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 3, bytes, 1, 5, true, 3, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 0, 2, bytes, 0, bytes.Length, false, 2, 1, expectedCompleted: true); VerificationHelper(encoder, chars, 2, 2, bytes, 0, bytes.Length, false, 2, 5, expectedCompleted: true); VerificationHelper(encoder, chars, 1, 1, bytes, 0, bytes.Length, true, 1, 3, expectedCompleted: true); } private void VerificationHelper(Encoder encoder, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, int expectedCharsUsed, int expectedBytesUsed, bool expectedCompleted) { int charsUsed; int bytesUsed; bool completed; encoder.Convert(chars, charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); Assert.Equal(expectedCharsUsed, charsUsed); Assert.Equal(expectedBytesUsed, bytesUsed); Assert.Equal(expectedCompleted, completed); } } }
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 WebApiThrottle.Demo.Areas.HelpPage.ModelDescriptions; using WebApiThrottle.Demo.Areas.HelpPage.Models; namespace WebApiThrottle.Demo.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 (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Validation; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableArray{T}" />. /// </summary> public static class ImmutableArray { /// <summary> /// A two element array useful for throwing exceptions the way LINQ does. /// </summary> internal static readonly byte[] TwoElementArray = new byte[2]; /// <summary> /// Creates an empty ImmutableArray{T}. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <returns>An empty array.</returns> [Pure] public static ImmutableArray<T> Create<T>() { return ImmutableArray<T>.Empty; } /// <summary> /// Creates an ImmutableArray{T} with the specified element as its only member. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item">The element to store in the array.</param> /// <returns>A 1-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item) { T[] array = new[] { item }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <returns>A 2-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2) { T[] array = new[] { item1, item2 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <param name="item3">The third element to store in the array.</param> /// <returns>A 3-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2, T item3) { T[] array = new[] { item1, item2, item3 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} with the specified elements. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="item1">The first element to store in the array.</param> /// <param name="item2">The second element to store in the array.</param> /// <param name="item3">The third element to store in the array.</param> /// <param name="item4">The third element to store in the array.</param> /// <returns>A 4-element array.</returns> [Pure] public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4) { T[] array = new[] { item1, item2, item3, item4 }; return new ImmutableArray<T>(array); } /// <summary> /// Creates an ImmutableArray{T} populated with the contents of the specified sequence. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="items">The elements to store in the array.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items) { Requires.NotNull(items, "items"); // As an optimization, if the provided enumerable is actually a // boxed ImmutableArray<T> instance, reuse the underlying array if possible. // Note that this allows for automatic upcasting and downcasting of arrays // where the CLR allows it. var immutableArray = items as IImmutableArray; if (immutableArray != null) { immutableArray.ThrowInvalidOperationIfNotInitialized(); var existingImmutableArray = immutableArray.Array as T[]; if (existingImmutableArray != null || immutableArray.Array == null) { return new ImmutableArray<T>(existingImmutableArray); } } // We don't recognize the source as an array that is safe to use. // So clone the sequence into an array and return an immutable wrapper. int count; if (items.TryGetCount(out count)) { if (count == 0) { // Return a wrapper around the singleton empty array. return Create<T>(); } else { // We know how long the sequence is. Linq's built-in ToArray extension method // isn't as comprehensive in finding the length as we are, so call our own method // to avoid reallocating arrays as the sequence is enumerated. return new ImmutableArray<T>(items.ToArray(count)); } } else { return new ImmutableArray<T>(items.ToArray()); } } /// <summary> /// Creates an empty ImmutableArray{T}. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="items">The elements to store in the array.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<T> Create<T>(params T[] items) { if (items == null) { return Create<T>(); } // We can't trust that the array passed in will never be mutated by the caller. // The caller may have passed in an array explicitly (not relying on compiler params keyword) // and could then change the array after the call, thereby violating the immutable // guarantee provided by this struct. So we always copy the array to ensure it won't ever change. return CreateDefensiveCopy(items); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct. /// </summary> /// <param name="items">The array to initialize the array with. A defensive copy is made.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <remarks> /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant /// tax for copying an array when the new array is a segment of an existing array. /// </remarks> [Pure] public static ImmutableArray<T> Create<T>(T[] items, int start, int length) { Requires.NotNull(items, "items"); Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { // Avoid allocating an array. return Create<T>(); } var array = new T[length]; for (int i = 0; i < length; i++) { array[i] = items[start + i]; } return new ImmutableArray<T>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct. /// </summary> /// <param name="items">The array to initialize the array with. /// The selected array segment may be copied into a new array.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <remarks> /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant /// tax for copying an array when the new array is a segment of an existing array. /// </remarks> [Pure] public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length) { Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { return Create<T>(); } if (start == 0 && length == items.Length) { return items; } var array = new T[length]; Array.Copy(items.array, start, array, 0, length); return new ImmutableArray<T>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="selector">The function to apply to each element from the source array.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from /// the source array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i]); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on a slice of an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from the source array /// included in the resulting array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector) { int itemsLength = items.Length; Requires.Range(start >= 0 && start <= itemsLength, "start"); Requires.Range(length >= 0 && start + length <= itemsLength, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i + start]); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="selector">The function to apply to each element from the source array.</param> /// <param name="arg">An argument to be passed to the selector mapping function.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from /// the source array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i], arg); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;" /> struct. /// </summary> /// <param name="items">The source array to initialize the resulting array with.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param> /// <param name="arg">An argument to be passed to the selector mapping function.</param> /// <remarks> /// This overload allows efficient creation of an <see cref="ImmutableArray&lt;T&gt;" /> based on a slice of an existing /// <see cref="ImmutableArray&lt;T&gt;" />, where a mapping function needs to be applied to each element from the source array /// included in the resulting array. /// </remarks> [Pure] public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg) { int itemsLength = items.Length; Requires.Range(start >= 0 && start <= itemsLength, "start"); Requires.Range(length >= 0 && start + length <= itemsLength, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } var array = new TResult[length]; for (int i = 0; i < length; i++) { array[i] = selector(items[i + start], arg); } return new ImmutableArray<TResult>(array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct based on the contents /// of an existing instance, allowing a covariant static cast to efficiently reuse the existing array. /// </summary> /// <param name="items">The array to initialize the array with. No copy is made.</param> /// <remarks> /// Covariant upcasts from this method may be reversed by calling the /// <see cref="ImmutableArray&lt;T&gt;.As&lt;TOther&gt;"/> instance method. /// </remarks> [Pure] public static ImmutableArray<T> Create<T, TDerived>(ImmutableArray<TDerived> items) where TDerived : class, T { return new ImmutableArray<T>(items.array); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;.Builder"/> class. /// </summary> /// <typeparam name="T">The type of elements stored in the array.</typeparam> /// <returns>A new builder.</returns> [Pure] public static ImmutableArray<T>.Builder CreateBuilder<T>() { return Create<T>().ToBuilder(); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray&lt;T&gt;.Builder"/> class. /// </summary> /// <typeparam name="T">The type of elements stored in the array.</typeparam> /// <param name="initialCapacity">The size of the initial array backing the builder.</param> /// <returns>A new builder.</returns> [Pure] public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity) { return new ImmutableArray<T>.Builder(initialCapacity); } /// <summary> /// Enumerates a sequence exactly once and produces an immutable array of its contents. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <param name="items">The sequence to enumerate.</param> /// <returns>An immutable array.</returns> [Pure] public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items) { if (items is ImmutableArray<TSource>) { return (ImmutableArray<TSource>)items; } return CreateRange(items); } /// <summary> /// Searches an entire one-dimensional sorted System.Array for a specific element, /// using the System.IComparable&lt;T&gt; generic interface implemented by each element /// of the System.Array and by the specified object. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="value">The object to search for.</param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// value does not implement the System.IComparable&lt;T&gt; generic interface, and /// the search encounters an element that does not implement the System.IComparable&lt;T&gt; /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, T value) { return Array.BinarySearch<T>(array.array, value); } /// <summary> /// Searches an entire one-dimensional sorted System.Array for a value using /// the specified System.Collections.Generic.IComparer&lt;T&gt; generic interface. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="value">The object to search for.</param> /// <param name="comparer"> /// The System.Collections.Generic.IComparer&lt;T&gt; implementation to use when comparing /// elements; or null to use the System.IComparable&lt;T&gt; implementation of each /// element. /// </param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// value does not implement the System.IComparable&lt;T&gt; generic interface, and /// the search encounters an element that does not implement the System.IComparable&lt;T&gt; /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T> comparer) { return Array.BinarySearch<T>(array.array, value, comparer); } /// <summary> /// Searches a range of elements in a one-dimensional sorted System.Array for /// a value, using the System.IComparable&lt;T&gt; generic interface implemented by /// each element of the System.Array and by the specified value. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="index">The starting index of the range to search.</param> /// <param name="length">The length of the range to search.</param> /// <param name="value">The object to search for.</param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// value does not implement the System.IComparable&lt;T&gt; generic interface, and /// the search encounters an element that does not implement the System.IComparable&lt;T&gt; /// generic interface. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value) { return Array.BinarySearch<T>(array.array, index, length, value); } /// <summary> /// Searches a range of elements in a one-dimensional sorted System.Array for /// a value, using the specified System.Collections.Generic.IComparer&lt;T&gt; generic /// interface. /// </summary> /// <typeparam name="T">The type of element stored in the array.</typeparam> /// <param name="array">The sorted, one-dimensional array to search.</param> /// <param name="index">The starting index of the range to search.</param> /// <param name="length">The length of the range to search.</param> /// <param name="value">The object to search for.</param> /// <param name="comparer"> /// The System.Collections.Generic.IComparer&lt;T&gt; implementation to use when comparing /// elements; or null to use the System.IComparable&lt;T&gt; implementation of each /// element. /// </param> /// <returns> /// The index of the specified value in the specified array, if value is found. /// If value is not found and value is less than one or more elements in array, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If value is not found and value is greater /// than any of the elements in array, a negative number which is the bitwise /// complement of (the index of the last element plus 1). /// </returns> /// <exception cref="System.InvalidOperationException"> /// comparer is null, value does not implement the System.IComparable&lt;T&gt; generic /// interface, and the search encounters an element that does not implement the /// System.IComparable&lt;T&gt; generic interface. /// </exception> /// <exception cref="ArgumentException"> /// index and length do not specify a valid range in array.-or-comparer is null, /// and value is of a type that is not compatible with the elements of array. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// index is less than the lower bound of array. -or- length is less than zero. /// </exception> [Pure] public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T> comparer) { return Array.BinarySearch<T>(array.array, index, length, value, comparer); } /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray"/> struct. /// </summary> /// <param name="items">The array to use or copy from. May be null for "default" arrays.</param> internal static ImmutableArray<T> CreateDefensiveCopy<T>(T[] items) { // Some folks lazily initialize fields containing these structs, so retaining a null vs. empty array status is useful. if (items == null) { return default(ImmutableArray<T>); } if (items.Length == 0) { return ImmutableArray<T>.Empty; // use just a shared empty array, allowing the input array to be potentially GC'd } // defensive copy var tmp = new T[items.Length]; Array.Copy(items, tmp, items.Length); return new ImmutableArray<T>(tmp); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/api.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class ApiReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/api.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ApiReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chlnb29nbGUvcHJvdG9idWYvYXBpLnByb3RvEg9nb29nbGUucHJvdG9idWYa", "JGdvb2dsZS9wcm90b2J1Zi9zb3VyY2VfY29udGV4dC5wcm90bxoaZ29vZ2xl", "L3Byb3RvYnVmL3R5cGUucHJvdG8igQIKA0FwaRIMCgRuYW1lGAEgASgJEigK", "B21ldGhvZHMYAiADKAsyFy5nb29nbGUucHJvdG9idWYuTWV0aG9kEigKB29w", "dGlvbnMYAyADKAsyFy5nb29nbGUucHJvdG9idWYuT3B0aW9uEg8KB3ZlcnNp", "b24YBCABKAkSNgoOc291cmNlX2NvbnRleHQYBSABKAsyHi5nb29nbGUucHJv", "dG9idWYuU291cmNlQ29udGV4dBImCgZtaXhpbnMYBiADKAsyFi5nb29nbGUu", "cHJvdG9idWYuTWl4aW4SJwoGc3ludGF4GAcgASgOMhcuZ29vZ2xlLnByb3Rv", "YnVmLlN5bnRheCLVAQoGTWV0aG9kEgwKBG5hbWUYASABKAkSGAoQcmVxdWVz", "dF90eXBlX3VybBgCIAEoCRIZChFyZXF1ZXN0X3N0cmVhbWluZxgDIAEoCBIZ", "ChFyZXNwb25zZV90eXBlX3VybBgEIAEoCRIaChJyZXNwb25zZV9zdHJlYW1p", "bmcYBSABKAgSKAoHb3B0aW9ucxgGIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5P", "cHRpb24SJwoGc3ludGF4GAcgASgOMhcuZ29vZ2xlLnByb3RvYnVmLlN5bnRh", "eCIjCgVNaXhpbhIMCgRuYW1lGAEgASgJEgwKBHJvb3QYAiABKAlCSwoTY29t", "Lmdvb2dsZS5wcm90b2J1ZkIIQXBpUHJvdG9QAaABAaICA0dQQqoCHkdvb2ds", "ZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.SourceContextReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Api), global::Google.Protobuf.WellKnownTypes.Api.Parser, new[]{ "Name", "Methods", "Options", "Version", "SourceContext", "Mixins", "Syntax" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Method), global::Google.Protobuf.WellKnownTypes.Method.Parser, new[]{ "Name", "RequestTypeUrl", "RequestStreaming", "ResponseTypeUrl", "ResponseStreaming", "Options", "Syntax" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Mixin), global::Google.Protobuf.WellKnownTypes.Mixin.Parser, new[]{ "Name", "Root" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Api is a light-weight descriptor for a protocol buffer service. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Api : pb::IMessage<Api> { private static readonly pb::MessageParser<Api> _parser = new pb::MessageParser<Api>(() => new Api()); public static pb::MessageParser<Api> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.ApiReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Api() { OnConstruction(); } partial void OnConstruction(); public Api(Api other) : this() { name_ = other.name_; methods_ = other.methods_.Clone(); options_ = other.options_.Clone(); version_ = other.version_; SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; mixins_ = other.mixins_.Clone(); syntax_ = other.syntax_; } public Api Clone() { return new Api(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The fully qualified name of this api, including package name /// followed by the api's simple name. /// </summary> public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "methods" field.</summary> public const int MethodsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Method> _repeated_methods_codec = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Method.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Method> methods_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Method>(); /// <summary> /// The methods of this api, in unspecified order. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Method> Methods { get { return methods_; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// Any metadata attached to the API. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "version" field.</summary> public const int VersionFieldNumber = 4; private string version_ = ""; /// <summary> /// A version string for this api. If specified, must have the form /// `major-version.minor-version`, as in `1.10`. If the minor version /// is omitted, it defaults to zero. If the entire version field is /// empty, the major version is derived from the package name, as /// outlined below. If the field is not empty, the version in the /// package name will be verified to be consistent with what is /// provided here. /// /// The versioning schema uses [semantic /// versioning](http://semver.org) where the major version number /// indicates a breaking change and the minor version an additive, /// non-breaking change. Both version numbers are signals to users /// what to expect from different versions, and should be carefully /// chosen based on the product plan. /// /// The major version is also reflected in the package name of the /// API, which must end in `v&lt;major-version>`, as in /// `google.feature.v1`. For major versions 0 and 1, the suffix can /// be omitted. Zero major versions must only be used for /// experimental, none-GA apis. /// </summary> public string Version { get { return version_; } set { version_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "source_context" field.</summary> public const int SourceContextFieldNumber = 5; private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; /// <summary> /// Source context for the protocol buffer service represented by this /// message. /// </summary> public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { get { return sourceContext_; } set { sourceContext_ = value; } } /// <summary>Field number for the "mixins" field.</summary> public const int MixinsFieldNumber = 6; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Mixin> _repeated_mixins_codec = pb::FieldCodec.ForMessage(50, global::Google.Protobuf.WellKnownTypes.Mixin.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Mixin> mixins_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Mixin>(); /// <summary> /// Included APIs. See [Mixin][]. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Mixin> Mixins { get { return mixins_; } } /// <summary>Field number for the "syntax" field.</summary> public const int SyntaxFieldNumber = 7; private global::Google.Protobuf.WellKnownTypes.Syntax syntax_ = 0; /// <summary> /// The source syntax of the service. /// </summary> public global::Google.Protobuf.WellKnownTypes.Syntax Syntax { get { return syntax_; } set { syntax_ = value; } } public override bool Equals(object other) { return Equals(other as Api); } public bool Equals(Api other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!methods_.Equals(other.methods_)) return false; if(!options_.Equals(other.options_)) return false; if (Version != other.Version) return false; if (!object.Equals(SourceContext, other.SourceContext)) return false; if(!mixins_.Equals(other.mixins_)) return false; if (Syntax != other.Syntax) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= methods_.GetHashCode(); hash ^= options_.GetHashCode(); if (Version.Length != 0) hash ^= Version.GetHashCode(); if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); hash ^= mixins_.GetHashCode(); if (Syntax != 0) hash ^= Syntax.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } methods_.WriteTo(output, _repeated_methods_codec); options_.WriteTo(output, _repeated_options_codec); if (Version.Length != 0) { output.WriteRawTag(34); output.WriteString(Version); } if (sourceContext_ != null) { output.WriteRawTag(42); output.WriteMessage(SourceContext); } mixins_.WriteTo(output, _repeated_mixins_codec); if (Syntax != 0) { output.WriteRawTag(56); output.WriteEnum((int) Syntax); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += methods_.CalculateSize(_repeated_methods_codec); size += options_.CalculateSize(_repeated_options_codec); if (Version.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Version); } if (sourceContext_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); } size += mixins_.CalculateSize(_repeated_mixins_codec); if (Syntax != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Syntax); } return size; } public void MergeFrom(Api other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } methods_.Add(other.methods_); options_.Add(other.options_); if (other.Version.Length != 0) { Version = other.Version; } if (other.sourceContext_ != null) { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } SourceContext.MergeFrom(other.SourceContext); } mixins_.Add(other.mixins_); if (other.Syntax != 0) { Syntax = other.Syntax; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { methods_.AddEntriesFrom(input, _repeated_methods_codec); break; } case 26: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 34: { Version = input.ReadString(); break; } case 42: { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } input.ReadMessage(sourceContext_); break; } case 50: { mixins_.AddEntriesFrom(input, _repeated_mixins_codec); break; } case 56: { syntax_ = (global::Google.Protobuf.WellKnownTypes.Syntax) input.ReadEnum(); break; } } } } } /// <summary> /// Method represents a method of an api. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Method : pb::IMessage<Method> { private static readonly pb::MessageParser<Method> _parser = new pb::MessageParser<Method>(() => new Method()); public static pb::MessageParser<Method> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.ApiReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Method() { OnConstruction(); } partial void OnConstruction(); public Method(Method other) : this() { name_ = other.name_; requestTypeUrl_ = other.requestTypeUrl_; requestStreaming_ = other.requestStreaming_; responseTypeUrl_ = other.responseTypeUrl_; responseStreaming_ = other.responseStreaming_; options_ = other.options_.Clone(); syntax_ = other.syntax_; } public Method Clone() { return new Method(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The simple name of this method. /// </summary> public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "request_type_url" field.</summary> public const int RequestTypeUrlFieldNumber = 2; private string requestTypeUrl_ = ""; /// <summary> /// A URL of the input message type. /// </summary> public string RequestTypeUrl { get { return requestTypeUrl_; } set { requestTypeUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "request_streaming" field.</summary> public const int RequestStreamingFieldNumber = 3; private bool requestStreaming_; /// <summary> /// If true, the request is streamed. /// </summary> public bool RequestStreaming { get { return requestStreaming_; } set { requestStreaming_ = value; } } /// <summary>Field number for the "response_type_url" field.</summary> public const int ResponseTypeUrlFieldNumber = 4; private string responseTypeUrl_ = ""; /// <summary> /// The URL of the output message type. /// </summary> public string ResponseTypeUrl { get { return responseTypeUrl_; } set { responseTypeUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "response_streaming" field.</summary> public const int ResponseStreamingFieldNumber = 5; private bool responseStreaming_; /// <summary> /// If true, the response is streamed. /// </summary> public bool ResponseStreaming { get { return responseStreaming_; } set { responseStreaming_ = value; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 6; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(50, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// Any metadata attached to the method. /// </summary> public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "syntax" field.</summary> public const int SyntaxFieldNumber = 7; private global::Google.Protobuf.WellKnownTypes.Syntax syntax_ = 0; /// <summary> /// The source syntax of this method. /// </summary> public global::Google.Protobuf.WellKnownTypes.Syntax Syntax { get { return syntax_; } set { syntax_ = value; } } public override bool Equals(object other) { return Equals(other as Method); } public bool Equals(Method other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (RequestTypeUrl != other.RequestTypeUrl) return false; if (RequestStreaming != other.RequestStreaming) return false; if (ResponseTypeUrl != other.ResponseTypeUrl) return false; if (ResponseStreaming != other.ResponseStreaming) return false; if(!options_.Equals(other.options_)) return false; if (Syntax != other.Syntax) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (RequestTypeUrl.Length != 0) hash ^= RequestTypeUrl.GetHashCode(); if (RequestStreaming != false) hash ^= RequestStreaming.GetHashCode(); if (ResponseTypeUrl.Length != 0) hash ^= ResponseTypeUrl.GetHashCode(); if (ResponseStreaming != false) hash ^= ResponseStreaming.GetHashCode(); hash ^= options_.GetHashCode(); if (Syntax != 0) hash ^= Syntax.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (RequestTypeUrl.Length != 0) { output.WriteRawTag(18); output.WriteString(RequestTypeUrl); } if (RequestStreaming != false) { output.WriteRawTag(24); output.WriteBool(RequestStreaming); } if (ResponseTypeUrl.Length != 0) { output.WriteRawTag(34); output.WriteString(ResponseTypeUrl); } if (ResponseStreaming != false) { output.WriteRawTag(40); output.WriteBool(ResponseStreaming); } options_.WriteTo(output, _repeated_options_codec); if (Syntax != 0) { output.WriteRawTag(56); output.WriteEnum((int) Syntax); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (RequestTypeUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RequestTypeUrl); } if (RequestStreaming != false) { size += 1 + 1; } if (ResponseTypeUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResponseTypeUrl); } if (ResponseStreaming != false) { size += 1 + 1; } size += options_.CalculateSize(_repeated_options_codec); if (Syntax != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Syntax); } return size; } public void MergeFrom(Method other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.RequestTypeUrl.Length != 0) { RequestTypeUrl = other.RequestTypeUrl; } if (other.RequestStreaming != false) { RequestStreaming = other.RequestStreaming; } if (other.ResponseTypeUrl.Length != 0) { ResponseTypeUrl = other.ResponseTypeUrl; } if (other.ResponseStreaming != false) { ResponseStreaming = other.ResponseStreaming; } options_.Add(other.options_); if (other.Syntax != 0) { Syntax = other.Syntax; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { RequestTypeUrl = input.ReadString(); break; } case 24: { RequestStreaming = input.ReadBool(); break; } case 34: { ResponseTypeUrl = input.ReadString(); break; } case 40: { ResponseStreaming = input.ReadBool(); break; } case 50: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 56: { syntax_ = (global::Google.Protobuf.WellKnownTypes.Syntax) input.ReadEnum(); break; } } } } } /// <summary> /// Declares an API to be included in this API. The including API must /// redeclare all the methods from the included API, but documentation /// and options are inherited as follows: /// /// - If after comment and whitespace stripping, the documentation /// string of the redeclared method is empty, it will be inherited /// from the original method. /// /// - Each annotation belonging to the service config (http, /// visibility) which is not set in the redeclared method will be /// inherited. /// /// - If an http annotation is inherited, the path pattern will be /// modified as follows. Any version prefix will be replaced by the /// version of the including API plus the [root][] path if specified. /// /// Example of a simple mixin: /// /// package google.acl.v1; /// service AccessControl { /// // Get the underlying ACL object. /// rpc GetAcl(GetAclRequest) returns (Acl) { /// option (google.api.http).get = "/v1/{resource=**}:getAcl"; /// } /// } /// /// package google.storage.v2; /// service Storage { /// rpc GetAcl(GetAclRequest) returns (Acl); /// /// // Get a data record. /// rpc GetData(GetDataRequest) returns (Data) { /// option (google.api.http).get = "/v2/{resource=**}"; /// } /// } /// /// Example of a mixin configuration: /// /// apis: /// - name: google.storage.v2.Storage /// mixins: /// - name: google.acl.v1.AccessControl /// /// The mixin construct implies that all methods in `AccessControl` are /// also declared with same name and request/response types in /// `Storage`. A documentation generator or annotation processor will /// see the effective `Storage.GetAcl` method after inherting /// documentation and annotations as follows: /// /// service Storage { /// // Get the underlying ACL object. /// rpc GetAcl(GetAclRequest) returns (Acl) { /// option (google.api.http).get = "/v2/{resource=**}:getAcl"; /// } /// ... /// } /// /// Note how the version in the path pattern changed from `v1` to `v2`. /// /// If the `root` field in the mixin is specified, it should be a /// relative path under which inherited HTTP paths are placed. Example: /// /// apis: /// - name: google.storage.v2.Storage /// mixins: /// - name: google.acl.v1.AccessControl /// root: acls /// /// This implies the following inherited HTTP annotation: /// /// service Storage { /// // Get the underlying ACL object. /// rpc GetAcl(GetAclRequest) returns (Acl) { /// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; /// } /// ... /// } /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Mixin : pb::IMessage<Mixin> { private static readonly pb::MessageParser<Mixin> _parser = new pb::MessageParser<Mixin>(() => new Mixin()); public static pb::MessageParser<Mixin> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.ApiReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Mixin() { OnConstruction(); } partial void OnConstruction(); public Mixin(Mixin other) : this() { name_ = other.name_; root_ = other.root_; } public Mixin Clone() { return new Mixin(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The fully qualified name of the API which is included. /// </summary> public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "root" field.</summary> public const int RootFieldNumber = 2; private string root_ = ""; /// <summary> /// If non-empty specifies a path under which inherited HTTP paths /// are rooted. /// </summary> public string Root { get { return root_; } set { root_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as Mixin); } public bool Equals(Mixin other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Root != other.Root) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Root.Length != 0) hash ^= Root.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Root.Length != 0) { output.WriteRawTag(18); output.WriteString(Root); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Root.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Root); } return size; } public void MergeFrom(Mixin other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Root.Length != 0) { Root = other.Root; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { Root = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// // Copyright (c) 2012-2021 Antmicro // // This file is licensed under the MIT License. // Full license text is available in the LICENSE file. using System; using System.Collections.Generic; using Antmicro.Migrant.Customization; using System.Linq; namespace Antmicro.Migrant.VersionTolerance { internal class TypeFullDescriptor : TypeDescriptor { public static implicit operator TypeFullDescriptor(Type type) { var justCreated = false; var result = fullCache.GetOrAdd(type, x => { justCreated = true; return new TypeFullDescriptor(); }); if(justCreated) { // we need to call init after creating empty `TypeDescriptor` // and putting it in cache as field types can refer to the // cache result.Init(type); } return result; } public TypeFullDescriptor() { fields = new List<FieldDescriptor>(); } public override void Read(ObjectReader reader) { ReadStamp(reader); ReadStructureStampIfNeeded(reader, reader.VersionToleranceLevel, reader.ForceStampVerification); } public void ReadStamp(ObjectReader reader) { TypeModule = reader.Modules.Read(); GenericFullName = reader.PrimitiveReader.ReadString(); Resolve(); } public override void Write(ObjectWriter writer) { WriteTypeStamp(writer); WriteStructureStampIfNeeded(writer); } public void ReadStructureStampIfNeeded(ObjectReader reader, VersionToleranceLevel versionToleranceLevel, bool forceStampVerification = false) { if(StampHelpers.IsStampNeeded(this, reader.TreatCollectionAsUserObject)) { ReadStructureStamp(reader, versionToleranceLevel, forceStampVerification); } } public void WriteStructureStampIfNeeded(ObjectWriter writer) { if(StampHelpers.IsStampNeeded(this, writer.TreatCollectionAsUserObject)) { WriteStructureStamp(writer); } } public void WriteTypeStamp(ObjectWriter writer) { writer.Modules.TouchAndWriteId(TypeModule); writer.PrimitiveWriter.Write(GenericFullName); } public bool Equals(TypeFullDescriptor obj, VersionToleranceLevel versionToleranceLevel) { if(versionToleranceLevel.HasFlag(VersionToleranceLevel.AllowAssemblyVersionChange)) { return obj.UnderlyingType.FullName == UnderlyingType.FullName && obj.TypeModule.Equals(TypeModule, versionToleranceLevel); } return Equals(obj); } public TypeDescriptorCompareResult CompareWith(TypeFullDescriptor previous, VersionToleranceLevel versionToleranceLevel = 0) { var result = new TypeDescriptorCompareResult(); var prevFields = previous.fields.ToDictionary(x => x.FullName, x => x); foreach(var field in fields.Where(f => !f.IsTransient)) { FieldDescriptor currentField; if(!prevFields.TryGetValue(field.FullName, out currentField)) { // field is missing in the previous version of the class result.FieldsAdded.Add(field); continue; } // are the types compatible? var compareResult = currentField.CompareWith(field, versionToleranceLevel); if(compareResult != FieldDescriptor.CompareResult.Match) { result.FieldsChanged.Add(field); } // why do we remove a field from current ones? if some field is still left after our operation, then field addition occured // we have to check that, cause it can be illegal from the version tolerance point of view prevFields.Remove(field.FullName); } // result should also contain transient fields, because some of them may // be marked with the [Constructor] attribute foreach(var nonTransient in prevFields.Values.Where(x => !x.IsTransient)) { result.FieldsRemoved.Add(nonTransient); } return result; } public string GenericFullName { get; private set; } public ModuleDescriptor TypeModule { get; private set; } private void Init(Type t) { UnderlyingType = t; TypeModule = new ModuleDescriptor(t.Module); if(UnderlyingType.IsGenericType) { GenericFullName = UnderlyingType.GetGenericTypeDefinition().FullName; Name = UnderlyingType.GetGenericTypeDefinition().AssemblyQualifiedName; } else { Name = UnderlyingType.AssemblyQualifiedName; GenericFullName = UnderlyingType.FullName; } if(t.BaseType != null) { baseType = t.BaseType; } var fieldsToDeserialize = new List<FieldInfoOrEntryToOmit>(); foreach(var field in StampHelpers.GetFieldsInSerializationOrder(UnderlyingType, true)) { fieldsToDeserialize.Add(new FieldInfoOrEntryToOmit(field)); if(!field.IsTransient()) { fields.Add(new FieldDescriptor(field)); } } FieldsToDeserialize = fieldsToDeserialize; } private void Resolve() { var type = TypeModule.ModuleAssembly.UnderlyingAssembly.GetType(GenericFullName); if(type == null) { throw new InvalidOperationException(string.Format("Couldn't load type '{0}'", GenericFullName)); } Name = type.AssemblyQualifiedName; UnderlyingType = type; } private IEnumerable<FieldInfoOrEntryToOmit> GetConstructorRecreatedFields() { return FieldsToDeserialize.Where(x => x.Field != null && x.Field.IsConstructor()); } private List<FieldInfoOrEntryToOmit> VerifyStructure(VersionToleranceLevel versionToleranceLevel, bool forceStampVerification) { if(TypeModule.GUID != UnderlyingType.Module.ModuleVersionId) { if(!versionToleranceLevel.HasFlag(VersionToleranceLevel.AllowGuidChange)) { throw new VersionToleranceException(string.Format("The class {2} was serialized with different module version id {0}, current one is {1}.", TypeModule.GUID, UnderlyingType.Module.ModuleVersionId, UnderlyingType.FullName)); } } else if(!forceStampVerification) { return StampHelpers.GetFieldsInSerializationOrder(UnderlyingType, true).Select(x => new FieldInfoOrEntryToOmit(x)).ToList(); } var result = new List<FieldInfoOrEntryToOmit>(); var assemblyTypeDescriptor = ((TypeFullDescriptor)UnderlyingType); if( !(assemblyTypeDescriptor.baseType == null && baseType == null) && ((assemblyTypeDescriptor.baseType == null && baseType != null) || !assemblyTypeDescriptor.baseType.Equals(baseType)) && !versionToleranceLevel.HasFlag(VersionToleranceLevel.AllowInheritanceChainChange)) { throw new VersionToleranceException(string.Format("Class hierarchy for {2} changed. Expected '{1}' as base class, but found '{0}'.", baseType != null ? baseType.UnderlyingType.FullName : "null", assemblyTypeDescriptor.baseType != null ? assemblyTypeDescriptor.baseType.UnderlyingType.FullName : "null", UnderlyingType.FullName)); } if(assemblyTypeDescriptor.TypeModule.ModuleAssembly.Version != TypeModule.ModuleAssembly.Version && !versionToleranceLevel.HasFlag(VersionToleranceLevel.AllowAssemblyVersionChange)) { throw new VersionToleranceException(string.Format("Assembly version changed from {0} to {1} for class {2}", TypeModule.ModuleAssembly.Version, assemblyTypeDescriptor.TypeModule.ModuleAssembly.Version, UnderlyingType.FullName)); } var cmpResult = assemblyTypeDescriptor.CompareWith(this, versionToleranceLevel); if(cmpResult.FieldsChanged.Any()) { throw new VersionToleranceException(string.Format("Field {0} type changed in class {1}.", cmpResult.FieldsChanged[0].Name, UnderlyingType.FullName)); } if(cmpResult.FieldsAdded.Any() && !versionToleranceLevel.HasFlag(VersionToleranceLevel.AllowFieldAddition)) { throw new VersionToleranceException(string.Format("Field {0} added to class {1}.", cmpResult.FieldsAdded[0].Name, UnderlyingType.FullName)); } if(cmpResult.FieldsRemoved.Any() && !versionToleranceLevel.HasFlag(VersionToleranceLevel.AllowFieldRemoval)) { throw new VersionToleranceException(string.Format("Field {0} removed from class {1}.", cmpResult.FieldsRemoved[0].Name, UnderlyingType.FullName)); } foreach(var field in fields) { if(cmpResult.FieldsRemoved.Contains(field)) { result.Add(new FieldInfoOrEntryToOmit(field.FieldType.UnderlyingType)); } else { result.Add(new FieldInfoOrEntryToOmit(field.UnderlyingFieldInfo)); } } foreach(var field in assemblyTypeDescriptor.GetConstructorRecreatedFields().Select(x => x.Field)) { result.Add(new FieldInfoOrEntryToOmit(field)); } return result; } private void ReadStructureStamp(ObjectReader reader, VersionToleranceLevel versionToleranceLevel, bool forceStampVerification) { baseType = (TypeFullDescriptor)reader.ReadType(); var noOfFields = reader.PrimitiveReader.ReadInt32(); for(int i = 0; i < noOfFields; i++) { var fieldDescriptor = new FieldDescriptor(this); fieldDescriptor.ReadFrom(reader); fields.Add(fieldDescriptor); } FieldsToDeserialize = VerifyStructure(versionToleranceLevel, forceStampVerification); // TODO: do we need this line? fullCache[UnderlyingType] = this; } private void WriteStructureStamp(ObjectWriter writer) { if(baseType == null) { writer.PrimitiveWriter.Write(Consts.NullObjectId); } else { writer.TouchAndWriteTypeId(baseType.UnderlyingType); } writer.PrimitiveWriter.Write(fields.Count); foreach(var field in fields) { field.WriteTo(writer); } } private TypeFullDescriptor baseType; private readonly List<FieldDescriptor> fields; public class TypeDescriptorCompareResult { public List<FieldDescriptor> FieldsRemoved { get; private set; } public List<FieldDescriptor> FieldsAdded { get; private set; } public List<FieldDescriptor> FieldsChanged { get; private set; } public bool Empty { get { return FieldsRemoved.Count == 0 && FieldsAdded.Count == 0 && FieldsChanged.Count == 0; } } public TypeDescriptorCompareResult() { FieldsRemoved = new List<FieldDescriptor>(); FieldsAdded = new List<FieldDescriptor>(); FieldsChanged = new List<FieldDescriptor>(); } } } }
// ---------------------------------------------------------------------------------- // // 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.Generic; using System.IO; using System.Management.Automation; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Used to initiate a failover operation. /// </summary> [Cmdlet( VerbsLifecycle.Start, "AzureRmRecoveryServicesAsrUnplannedFailoverJob", DefaultParameterSetName = ASRParameterSets.ByRPIObject, SupportsShouldProcess = true)] [Alias( "Start-ASRFO", "Start-ASRUnplannedFailoverJob")] [OutputType(typeof(ASRJob))] public class StartAzureRmRecoveryServicesAsrUnplannedFailoverJob : SiteRecoveryCmdletBase { /// <summary> /// Gets or sets Recovery Plan object. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRRecoveryPlan RecoveryPlan { get; set; } /// <summary> /// Gets or sets Replication Protected Item. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPIObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRReplicationProtectedItem ReplicationProtectedItem { get; set; } /// <summary> /// Gets or sets Failover direction for the recovery plan. /// </summary> [Parameter(Mandatory = true)] [ValidateSet( Constants.PrimaryToRecovery, Constants.RecoveryToPrimary)] public string Direction { get; set; } /// <summary> /// Gets or sets switch parameter. This is required to PerformSourceSideActions. /// </summary> [Parameter] [Alias("PerformSourceSideActions")] public SwitchParameter PerformSourceSideAction { get; set; } /// <summary> /// Gets or sets Data encryption certificate file path for failover of Protected Item. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public string DataEncryptionPrimaryCertFile { get; set; } /// <summary> /// Gets or sets Data encryption certificate file path for failover of Protected Item. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public string DataEncryptionSecondaryCertFile { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( "Protected item or Recovery plan", "Start failover")) { if (!string.IsNullOrEmpty(this.DataEncryptionPrimaryCertFile)) { var certBytesPrimary = File.ReadAllBytes(this.DataEncryptionPrimaryCertFile); this.primaryKekCertpfx = Convert.ToBase64String(certBytesPrimary); } if (!string.IsNullOrEmpty(this.DataEncryptionSecondaryCertFile)) { var certBytesSecondary = File.ReadAllBytes(this.DataEncryptionSecondaryCertFile); this.secondaryKekCertpfx = Convert.ToBase64String(certBytesSecondary); } switch (this.ParameterSetName) { case ASRParameterSets.ByRPIObject: this.protectionContainerName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers); this.fabricName = Utilities.GetValueFromArmId( this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationFabrics); this.StartRPIUnplannedFailover(); break; case ASRParameterSets.ByRPObject: this.StartRpUnplannedFailover(); break; } } } /// <summary> /// Starts RPI Unplanned failover. /// </summary> private void StartRPIUnplannedFailover() { var unplannedFailoverInputProperties = new UnplannedFailoverInputProperties { FailoverDirection = this.Direction, SourceSiteOperations = this.PerformSourceSideAction ? "Required" : "NotRequired", ProviderSpecificDetails = new ProviderSpecificFailoverInput() }; var input = new UnplannedFailoverInput { Properties = unplannedFailoverInputProperties }; if (0 == string.Compare( this.ReplicationProtectedItem.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase)) { if (this.Direction == Constants.PrimaryToRecovery) { var failoverInput = new HyperVReplicaAzureFailoverProviderInput { PrimaryKekCertificatePfx = this.primaryKekCertpfx, SecondaryKekCertificatePfx = this.secondaryKekCertpfx, VaultLocation = "dummy" }; input.Properties.ProviderSpecificDetails = failoverInput; } } var response = this.RecoveryServicesClient.StartAzureSiteRecoveryUnplannedFailover( this.fabricName, this.protectionContainerName, this.ReplicationProtectedItem.Name, input); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } /// <summary> /// Starts RP Unplanned failover. /// </summary> private void StartRpUnplannedFailover() { // Refresh RP Object var rp = this.RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan( this.RecoveryPlan.Name); var recoveryPlanUnplannedFailoverInputProperties = new RecoveryPlanUnplannedFailoverInputProperties { FailoverDirection = this.Direction == PossibleOperationsDirections.PrimaryToRecovery.ToString() ? PossibleOperationsDirections.PrimaryToRecovery : PossibleOperationsDirections.RecoveryToPrimary, SourceSiteOperations = this.PerformSourceSideAction ? SourceSiteOperations.Required : SourceSiteOperations.NotRequired, //Required|NotRequired ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() }; foreach (var replicationProvider in rp.Properties.ReplicationProviders) { if (0 == string.Compare( replicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase)) { if (this.Direction == Constants.PrimaryToRecovery) { var recoveryPlanHyperVReplicaAzureFailoverInput = new RecoveryPlanHyperVReplicaAzureFailoverInput { PrimaryKekCertificatePfx = this.primaryKekCertpfx, SecondaryKekCertificatePfx = this.secondaryKekCertpfx, VaultLocation = "dummy" }; recoveryPlanUnplannedFailoverInputProperties.ProviderSpecificDetails.Add( recoveryPlanHyperVReplicaAzureFailoverInput); } } } var recoveryPlanUnplannedFailoverInput = new RecoveryPlanUnplannedFailoverInput { Properties = recoveryPlanUnplannedFailoverInputProperties }; var response = this.RecoveryServicesClient.StartAzureSiteRecoveryUnplannedFailover( this.RecoveryPlan.Name, recoveryPlanUnplannedFailoverInput); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } #region local parameters /// <summary> /// Gets or sets Name of the PE. /// </summary> public string protectionEntityName; /// <summary> /// Gets or sets Name of the Protection Container. /// </summary> public string protectionContainerName; /// <summary> /// Gets or sets Name of the Fabric. /// </summary> public string fabricName; /// <summary> /// Primary Kek Cert pfx file. /// </summary> private string primaryKekCertpfx; /// <summary> /// Secondary Kek Cert pfx file. /// </summary> private string secondaryKekCertpfx; #endregion local parameters } }
using System; using System.Collections.Generic; using Quartz.Collections; using Quartz.Impl.Matchers; using Quartz.Util; namespace Quartz.Core { /// <summary> /// Default concrete implementation of <see cref="IListenerManager" />. /// </summary> public class ListenerManagerImpl : IListenerManager { private readonly OrderedDictionary<string, IJobListener> globalJobListeners = new OrderedDictionary<string, IJobListener>(10); private readonly OrderedDictionary<string, ITriggerListener> globalTriggerListeners = new OrderedDictionary<string, ITriggerListener>(10); private readonly Dictionary<string, List<IMatcher<JobKey>>> globalJobListenersMatchers = new Dictionary<string, List<IMatcher<JobKey>>>(10); private readonly Dictionary<string, List<IMatcher<TriggerKey>>> globalTriggerListenersMatchers = new Dictionary<string, List<IMatcher<TriggerKey>>>(10); private readonly List<ISchedulerListener> schedulerListeners = new List<ISchedulerListener>(10); public void AddJobListener(IJobListener jobListener, params IMatcher<JobKey>[] matchers) { AddJobListener(jobListener, new List<IMatcher<JobKey>>(matchers)); } public void AddJobListener(IJobListener jobListener, IReadOnlyCollection<IMatcher<JobKey>> matchers) { if (string.IsNullOrEmpty(jobListener.Name)) { throw new ArgumentException("JobListener name cannot be empty."); } lock (globalJobListeners) { globalJobListeners[jobListener.Name] = jobListener; List<IMatcher<JobKey>> matchersL = new List<IMatcher<JobKey>>(); if (matchers != null && matchers.Count > 0) { matchersL.AddRange(matchers); } else { matchersL.Add(EverythingMatcher<JobKey>.AllJobs()); } globalJobListenersMatchers[jobListener.Name] = matchersL; } } public bool AddJobListenerMatcher(string listenerName, IMatcher<JobKey> matcher) { if (matcher == null) { throw new ArgumentException("Non-null value not acceptable."); } lock (globalJobListeners) { var matchers = globalJobListenersMatchers.TryGetAndReturn(listenerName); if (matchers == null) { return false; } matchers.Add(matcher); return true; } } public bool RemoveJobListenerMatcher(string listenerName, IMatcher<JobKey> matcher) { if (matcher == null) { throw new ArgumentException("Non-null value not acceptable."); } lock (globalJobListeners) { var matchers = globalJobListenersMatchers.TryGetAndReturn(listenerName); if (matchers == null) { return false; } return matchers.Remove(matcher); } } public IReadOnlyCollection<IMatcher<JobKey>>? GetJobListenerMatchers(string listenerName) { lock (globalJobListeners) { var matchers = globalJobListenersMatchers.TryGetAndReturn(listenerName); return matchers?.AsReadOnly(); } } public bool SetJobListenerMatchers(string listenerName, IReadOnlyCollection<IMatcher<JobKey>> matchers) { if (matchers == null) { throw new ArgumentException("Non-null value not acceptable."); } lock (globalJobListeners) { var oldMatchers = globalJobListenersMatchers.TryGetAndReturn(listenerName); if (oldMatchers == null) { return false; } globalJobListenersMatchers[listenerName] = new List<IMatcher<JobKey>>(matchers); return true; } } public bool RemoveJobListener(string name) { lock (globalJobListeners) { return globalJobListeners.Remove(name); } } public IReadOnlyCollection<IJobListener> GetJobListeners() { lock (globalJobListeners) { return globalJobListeners.Count > 0 ? new List<IJobListener>(globalJobListeners.Values) : EmptyReadOnlyCollection<IJobListener>.Instance; } } public IJobListener GetJobListener(string name) { lock (globalJobListeners) { return globalJobListeners[name]; } } public void AddTriggerListener(ITriggerListener triggerListener, params IMatcher<TriggerKey>[] matchers) { AddTriggerListener(triggerListener, new List<IMatcher<TriggerKey>>(matchers)); } public void AddTriggerListener(ITriggerListener triggerListener, IReadOnlyCollection<IMatcher<TriggerKey>> matchers) { if (string.IsNullOrEmpty(triggerListener.Name)) { throw new ArgumentException("TriggerListener name cannot be empty."); } lock (globalTriggerListeners) { globalTriggerListeners[triggerListener.Name] = triggerListener; List<IMatcher<TriggerKey>> matchersL = new List<IMatcher<TriggerKey>>(); if (matchers != null && matchers.Count > 0) { matchersL.AddRange(matchers); } else { matchersL.Add(EverythingMatcher<TriggerKey>.AllTriggers()); } globalTriggerListenersMatchers[triggerListener.Name] = matchersL; } } public void AddTriggerListener(ITriggerListener triggerListener, IMatcher<TriggerKey> matcher) { if (matcher == null) { throw new ArgumentException("Non-null value not acceptable for matcher."); } if (string.IsNullOrEmpty(triggerListener.Name)) { throw new ArgumentException("TriggerListener name cannot be empty."); } lock (globalTriggerListeners) { globalTriggerListeners[triggerListener.Name] = triggerListener; var matchers = new List<IMatcher<TriggerKey>> {matcher}; globalTriggerListenersMatchers[triggerListener.Name] = matchers; } } public bool AddTriggerListenerMatcher(string listenerName, IMatcher<TriggerKey> matcher) { if (matcher == null) { throw new ArgumentException("Non-null value not acceptable."); } lock (globalTriggerListeners) { var matchers = globalTriggerListenersMatchers.TryGetAndReturn(listenerName); if (matchers == null) { return false; } matchers.Add(matcher); return true; } } public bool RemoveTriggerListenerMatcher(string listenerName, IMatcher<TriggerKey> matcher) { if (matcher == null) { throw new ArgumentException("Non-null value not acceptable."); } lock (globalTriggerListeners) { var matchers = globalTriggerListenersMatchers.TryGetAndReturn(listenerName); if (matchers == null) { return false; } return matchers.Remove(matcher); } } public IReadOnlyCollection<IMatcher<TriggerKey>>? GetTriggerListenerMatchers(string listenerName) { lock (globalTriggerListeners) { var matchers = globalTriggerListenersMatchers.TryGetAndReturn(listenerName); return matchers; } } public bool SetTriggerListenerMatchers(string listenerName, IReadOnlyCollection<IMatcher<TriggerKey>> matchers) { if (matchers == null) { throw new ArgumentException("Non-null value not acceptable."); } lock (globalTriggerListeners) { var oldMatchers = globalTriggerListenersMatchers.TryGetAndReturn(listenerName); if (oldMatchers == null) { return false; } globalTriggerListenersMatchers[listenerName] = new List<IMatcher<TriggerKey>>(matchers); return true; } } public bool RemoveTriggerListener(string name) { lock (globalTriggerListeners) { return globalTriggerListeners.Remove(name); } } public IReadOnlyCollection<ITriggerListener> GetTriggerListeners() { lock (globalTriggerListeners) { return globalTriggerListeners.Count > 0 ? new List<ITriggerListener>(globalTriggerListeners.Values) : EmptyReadOnlyCollection<ITriggerListener>.Instance; } } public ITriggerListener GetTriggerListener(string name) { lock (globalTriggerListeners) { return globalTriggerListeners[name]; } } public void AddSchedulerListener(ISchedulerListener schedulerListener) { lock (schedulerListeners) { schedulerListeners.Add(schedulerListener); } } public bool RemoveSchedulerListener(ISchedulerListener schedulerListener) { lock (schedulerListeners) { return schedulerListeners.Remove(schedulerListener); } } public IReadOnlyCollection<ISchedulerListener> GetSchedulerListeners() { lock (schedulerListeners) { return schedulerListeners.Count > 0 ? new List<ISchedulerListener>(schedulerListeners) : EmptyReadOnlyCollection<ISchedulerListener>.Instance; } } } }
//----------------------------------------------------------------------- // <copyright file="SmartDateTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using Csla; using Csla.Serialization; using Csla.Testing.Business.ReadOnlyTest; using System; using UnitDriven; #if !WINDOWS_PHONE using Microsoft.VisualBasic; #endif using Csla.Serialization.Mobile; using System.Threading; #if NUNIT using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestSetup = NUnit.Framework.SetUpAttribute; using Microsoft.VisualBasic; using Csla.Serialization.Mobile; #elif MSTEST using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Csla.Test.SmartDate { [TestClass()] public class SmartDateTests { System.Globalization.CultureInfo CurrentCulture { get; set; } System.Globalization.CultureInfo CurrentUICulture { get; set; } [TestInitialize] public void Setup() { // store current cultures CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture; CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; // set to "en-US" for all tests System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); } [TestCleanup] public void Cleanup() { // restore original cultures System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = CurrentUICulture; } #region Test Constructors [TestMethod()] public void TestSmartDateConstructors() { DateTime now = DateTime.Now; Csla.SmartDate d = new Csla.SmartDate(now); Assert.AreEqual(now, d.Date); d = new Csla.SmartDate(true); Assert.IsTrue(d.EmptyIsMin); d = new Csla.SmartDate(false); Assert.IsFalse(d.EmptyIsMin); d = new Csla.SmartDate("1/1/2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate("Jan/1/2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate("January-1-2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate("1-1-2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate(""); Assert.AreEqual("", d.ToString()); Assert.IsTrue(d.IsEmpty); d = new Csla.SmartDate("1/1/2005", true); Assert.AreEqual("1/1/2005", d.ToString()); Assert.IsTrue(d.EmptyIsMin); d = new Csla.SmartDate("1/1/2005", false); Assert.AreEqual("1/1/2005", d.ToString()); Assert.IsFalse(d.EmptyIsMin); d = new Csla.SmartDate("", true); Assert.AreEqual(DateTime.MinValue, d.Date); Assert.AreEqual("", d.ToString()); d = new Csla.SmartDate("", false); Assert.AreEqual(DateTime.MaxValue, d.Date); Assert.AreEqual("", d.ToString()); try { d = new Csla.SmartDate("Invalid Date", true); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } try { d = new Csla.SmartDate("Invalid Date", false); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } d = new Csla.SmartDate(now, true); Assert.AreEqual(now, d.Date); Assert.IsTrue(d.EmptyIsMin); d = new Csla.SmartDate(now, false); Assert.AreEqual(now, d.Date); Assert.IsFalse(d.EmptyIsMin); d = new Csla.SmartDate((DateTime?)null, true); Assert.AreEqual(DateTime.MinValue, d.Date); d = new Csla.SmartDate((DateTime?)null, false); Assert.AreEqual(DateTime.MaxValue, d.Date); d = new Csla.SmartDate((DateTime?)null, Csla.SmartDate.EmptyValue.MinDate); Assert.AreEqual(DateTime.MinValue, d.Date); d = new Csla.SmartDate((DateTime?)null, Csla.SmartDate.EmptyValue.MaxDate); Assert.AreEqual(DateTime.MaxValue, d.Date); } #endregion #region Converters [TestMethod] public void TestConverters() { DateTime d = Csla.SmartDate.StringToDate("1/1/2005"); Assert.AreEqual("1/1/2005", d.ToShortDateString()); d = Csla.SmartDate.StringToDate("january-1-2005"); Assert.AreEqual("1/1/2005", d.ToShortDateString()); d = Csla.SmartDate.StringToDate("."); Assert.AreEqual(DateTime.Now.ToShortDateString(), d.ToShortDateString()); d = Csla.SmartDate.StringToDate("-"); Assert.AreEqual(DateTime.Now.AddDays(-1.0).ToShortDateString(), d.ToShortDateString()); d = Csla.SmartDate.StringToDate("+"); Assert.AreEqual(DateTime.Now.AddDays(1.0).ToShortDateString(), d.ToShortDateString()); try { d = Csla.SmartDate.StringToDate("Invalid Date"); } catch (Exception ex) { Assert.IsTrue(ex is System.ArgumentException); } d = Csla.SmartDate.StringToDate(""); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate(null); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate("", true); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate("", false); Assert.AreEqual(DateTime.MaxValue, d); try { d = Csla.SmartDate.StringToDate("Invalid Date", true); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } try { d = Csla.SmartDate.StringToDate("Invalid Date", false); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } d = Csla.SmartDate.StringToDate(null, true); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate(null, false); Assert.AreEqual(DateTime.MaxValue, d); d = new DateTime(2005, 1, 2); string date = Csla.SmartDate.DateToString(d, "dd/MM/yyyy"); Assert.AreEqual("02/01/2005", date, "dd/MM/yyyy test"); date = Csla.SmartDate.DateToString(d, "MM/dd/yy"); Assert.AreEqual("01/02/05", date, "MM/dd/yy test"); date = Csla.SmartDate.DateToString(d, ""); Assert.AreEqual("1/2/2005 12:00:00 AM", date); date = Csla.SmartDate.DateToString(d, "d"); Assert.AreEqual("1/2/2005", date); date = new Csla.SmartDate(d).ToString(); Assert.AreEqual("1/2/2005", date); date = Csla.SmartDate.DateToString(DateTime.MinValue, "dd/MM/yyyy", true); Assert.AreEqual("", date, "MinValue w/ emptyIsMin=true"); date = Csla.SmartDate.DateToString(DateTime.MinValue, "dd/MM/yyyy", false); Assert.AreEqual(DateTime.MinValue.ToString("dd/MM/yyyy"), date, "MinValue w/ emptyIsMin=false"); date = Csla.SmartDate.DateToString(DateTime.MaxValue, "dd/MM/yyyy", true); Assert.AreEqual(DateTime.MaxValue.ToString("dd/MM/yyyy"), date, "MaxValue w/ emptyIsMin=true"); date = Csla.SmartDate.DateToString(DateTime.MaxValue, "dd/MM/yyyy", false); Assert.AreEqual("", date, "MaxValue w/ emptyIsMin=false"); } #endregion #if !WINDOWS_PHONE #region Add [TestMethod()] public void Add() { Csla.SmartDate d2 = new Csla.SmartDate(); Csla.SmartDate d3; d2.Date = new DateTime(2005, 1, 1); d3 = new Csla.SmartDate(d2.Add(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(DateAndTime.DateAdd(DateInterval.Day, 30, d2.Date), d3.Date, "Dates should be equal"); Assert.AreEqual(d3, d2 + new TimeSpan(30, 0, 0, 0, 0), "Dates should be equal"); } #endregion #region Subtract [TestMethod()] public void Subtract() { Csla.SmartDate d2 = new Csla.SmartDate(); Csla.SmartDate d3; d2.Date = new DateTime(2005, 1, 1); d3 = new Csla.SmartDate(d2.Subtract(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(DateAndTime.DateAdd(DateInterval.Day, -30, d2.Date), d3.Date, "Dates should be equal"); Assert.AreEqual(30, ((TimeSpan)(d2 - d3)).Days, "Should be 30 days different"); Assert.AreEqual(d3, d2 - new TimeSpan(30, 0, 0, 0, 0), "Should be equal"); } #endregion #endif #region Comparison [TestMethod()] public void Comparison() { Csla.SmartDate d2 = new Csla.SmartDate(true); Csla.SmartDate d3 = new Csla.SmartDate(false); Csla.SmartDate d4 = new Csla.SmartDate(Csla.SmartDate.EmptyValue.MinDate); Csla.SmartDate d5 = new Csla.SmartDate(Csla.SmartDate.EmptyValue.MaxDate); Assert.IsTrue(d2.Equals(d3), "Empty dates should be equal"); Assert.IsTrue(Csla.SmartDate.Equals(d2, d3), "Empty dates should be equal (shared)"); Assert.IsTrue(d2.Equals(d3), "Empty dates should be equal (unary)"); Assert.IsTrue(d2.Equals(""), "Should be equal to an empty string (d2)"); Assert.IsTrue(d3.Equals(""), "Should be equal to an empty string (d3)"); Assert.IsTrue(d2.Date.Equals(DateTime.MinValue), "Should be DateTime.MinValue"); Assert.IsTrue(d3.Date.Equals(DateTime.MaxValue), "Should be DateTime.MaxValue"); Assert.IsTrue(d4.Date.Equals(DateTime.MinValue), "Should be DateTime.MinValue (d4)"); Assert.IsTrue(d5.Date.Equals(DateTime.MaxValue), "Should be DateTime.MaxValue (d5)"); d2.Date = new DateTime(2005, 1, 1); d3 = new Csla.SmartDate(d2.Date, d2.EmptyIsMin); Assert.AreEqual(d2, d3, "Assigned dates should be equal"); d3.Date = new DateTime(2005, 2, 2); Assert.AreEqual(1, d3.CompareTo(d2), "Should be greater than"); Assert.AreEqual(-1, d2.CompareTo(d3), "Should be less than"); Assert.IsFalse(d2.CompareTo(d3) == 0, "should not be equal"); d3.Date = new DateTime(2005, 1, 1); Assert.IsFalse(1 == d2.CompareTo(d3), "should be equal"); Assert.IsFalse(-1 == d2.CompareTo(d3), "should be equal"); Assert.AreEqual(0, d2.CompareTo(d3), "should be equal"); Assert.IsTrue(d3.Equals("1/1/2005"), "Should be equal to string date"); Assert.IsTrue(d3.Equals(new DateTime(2005, 1, 1)), "should be equal to DateTime"); Assert.IsTrue(d3.Equals(d2.Date.ToString()), "Should be equal to any date time string"); Assert.IsTrue(d3.Equals(d2.Date.ToLongDateString()), "Should be equal to any date time string"); Assert.IsTrue(d3.Equals(d2.Date.ToShortDateString()), "Should be equal to any date time string"); Assert.IsFalse(d3.Equals(""), "Should not be equal to a blank string"); //DateTime can be compared using all sorts of formats but the SmartDate cannot. //DateTime dt = DateTime.Now; //long ldt = dt.ToBinary(); //Assert.IsTrue(dt.Equals(ldt), "Should be equal"); //Should smart date also be converted into these various types? } #endregion #region Empty [TestMethod()] public void Empty() { Csla.SmartDate d2 = new Csla.SmartDate(); Csla.SmartDate d3; d3 = new Csla.SmartDate(d2.Add(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(d2, d3, "Dates should be equal"); Assert.AreEqual("", d2.Text, "Text should be empty"); d3 = new Csla.SmartDate(d2.Subtract(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(d2, d3, "Dates should be equal"); Assert.AreEqual("", d2.Text, "Text should be empty"); d3 = new Csla.SmartDate(); Assert.AreEqual(0, d2.CompareTo(d3), "d2 and d3 should be the same"); Assert.IsTrue(d2.Equals(d3), "d2 and d3 should be the same"); Assert.IsTrue(Csla.SmartDate.Equals(d2, d3), "d2 and d3 should be the same"); d3.Date = DateTime.Now; Assert.AreEqual(-1, d2.CompareTo(d3), "d2 and d3 should not be the same"); Assert.AreEqual(1, d3.CompareTo(d2), "d2 and d3 should not be the same"); Assert.IsFalse(d2.Equals(d3), "d2 and d3 should not be the same"); Assert.IsFalse(Csla.SmartDate.Equals(d2, d3), "d2 and d3 should not be the same"); Assert.IsFalse(d3.Equals(d2), "d2 and d3 should not be the same"); Assert.IsFalse(Csla.SmartDate.Equals(d3, d2), "d2 and d3 should not be the same"); } [TestMethod] public void MaxDateMaxValue() { // test for maxDateValue Csla.SmartDate target = new Csla.SmartDate(Csla.SmartDate.EmptyValue.MaxDate); DateTime expected = DateTime.MaxValue; DateTime actual = target.Date; Assert.AreEqual(expected, actual); } #endregion #region Comparison Operators [TestMethod()] public void ComparisonOperators() { Csla.SmartDate d1 = new Csla.SmartDate(); Csla.SmartDate d2 = new Csla.SmartDate(); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 < d2, "d1 should be less than d2"); d1.Date = new DateTime(2005, 2, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 < d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 3, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 < d2, "d1 should be greater than d2"); d1.Date = new DateTime(2005, 3, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 > d2, "d1 should be greater than d2"); d1.Date = new DateTime(2005, 2, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 > d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 > d2, "d1 should be less than d2"); d1.Date = new DateTime(2005, 2, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 == d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 == d2, "d1 should not be equal to d2"); //#warning Smart date does not overload the <= or >= operators! //Assert.Fail("Missing <= and >= operators"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 <= d2, "d1 should be less than or equal to d2"); d1.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 <= d2, "d1 should be less than or equal to d2"); d1.Date = new DateTime(2005, 3, 1); Assert.IsFalse(d1 <= d2, "d1 should be greater than to d2"); d1.Date = new DateTime(2005, 3, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 >= d2, "d1 should be greater than or equal to d2"); d1.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 >= d2, "d1 should be greater than or equal to d2"); d1.Date = new DateTime(2005, 1, 1); Assert.IsFalse(d1 >= d2, "d1 should be less than to d2"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 != d2, "d1 should not be equal to d2"); d1.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 != d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 3, 1); Assert.IsTrue(d1 != d2, "d1 should be greater than d2"); } [TestMethod] public void TryParseTest() { Csla.SmartDate sd = new Csla.SmartDate(); if (Csla.SmartDate.TryParse("blah", ref sd)) Assert.AreEqual(true, false, "TryParse should have failed"); if (Csla.SmartDate.TryParse("t", ref sd)) Assert.AreEqual(DateTime.Now.Date, sd.Date.Date, "Date should have been now"); else Assert.AreEqual(true, false, "TryParse should have succeeded"); } #endregion #region Serialization [TestMethod()] public void SerializationTest() { Csla.SmartDate d2; d2 = new Csla.SmartDate(); Csla.SmartDate clone = (Csla.SmartDate)MobileFormatter.Deserialize(MobileFormatter.Serialize(d2)); Assert.AreEqual(d2, clone, "Dates should have ben the same"); d2 = new Csla.SmartDate(DateTime.Now, false); clone = (Csla.SmartDate)MobileFormatter.Deserialize(MobileFormatter.Serialize(d2)); Assert.AreEqual(d2, clone, "Dates should have ben the same"); d2 = new Csla.SmartDate(DateTime.Now.AddDays(10), false); d2.FormatString = "YYYY/DD/MM"; clone = (Csla.SmartDate)MobileFormatter.Deserialize(MobileFormatter.Serialize(d2)); Assert.AreEqual(d2, clone, "Dates should have ben the same"); cslalighttest.Serialization.PersonWIthSmartDateField person; person = cslalighttest.Serialization.PersonWIthSmartDateField.GetPersonWIthSmartDateField("Sergey", 2000); Assert.AreEqual(person.Birthdate, person.Clone().Birthdate, "Dates should have ben the same"); Csla.SmartDate expected = person.Birthdate; person.BeginEdit(); person.Birthdate = new Csla.SmartDate(expected.Date.AddDays(10)); // to guarantee it's a different value person.CancelEdit(); Csla.SmartDate actual = person.Birthdate; Assert.AreEqual(expected, actual); } #endregion [TestMethod] public void DefaultFormat() { var obj = new SDtest(); Assert.AreEqual("", obj.TextDate, "Should be empty"); var now = DateTime.Now; obj.TextDate = string.Format("{0:g}", now); Assert.AreEqual(string.Format("{0:g}", now), obj.TextDate, "Should be today"); } [TestMethod] public void CustomParserReturnsDateTime() { Csla.SmartDate.CustomParser = (s) => { if (s == "test") return DateTime.Now; return null; }; // uses custom parser var date = new Csla.SmartDate("test"); Assert.AreEqual(DateTime.Now.Date, date.Date.Date); // uses buildin parser var date2 = new Csla.SmartDate("t"); Assert.AreEqual(DateTime.Now.Date, date.Date.Date); } } [Serializable] public class SDtest : BusinessBase<SDtest> { public static PropertyInfo<Csla.SmartDate> TextDateProperty = RegisterProperty<Csla.SmartDate>(c => c.TextDate, null, new Csla.SmartDate { FormatString = "g" }); public string TextDate { get { return GetPropertyConvert<Csla.SmartDate, string>(TextDateProperty); } set { SetPropertyConvert<Csla.SmartDate, string>(TextDateProperty, value); } } public static PropertyInfo<Csla.SmartDate> MyDateProperty = RegisterProperty<Csla.SmartDate>(c => c.MyDate); public Csla.SmartDate MyDate { get { return GetProperty(MyDateProperty); } set { SetProperty(MyDateProperty, value); } } } }
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 nH.Web.Areas.HelpPage.ModelDescriptions; using nH.Web.Areas.HelpPage.Models; namespace nH.Web.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); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace Hjson { using JsonPair=KeyValuePair<string, JsonValue>; internal class HjsonReader : BaseReader { StringBuilder sb=new StringBuilder(); IEnumerable<IHjsonDsfProvider> dsfProviders=Enumerable.Empty<IHjsonDsfProvider>(); public HjsonReader(TextReader reader, IJsonReader jsonReader, HjsonOptions options) : base(reader, jsonReader) { if (options!=null) { ReadWsc=options.KeepWsc; dsfProviders=options.DsfProviders; } } public JsonValue Read() { // Braces for the root object are optional int c=SkipPeekChar(); switch (c) { case '[': case '{': return checkTrailing(ReadCore()); default: try { // assume we have a root object without braces return checkTrailing(ReadCore(true)); } catch (Exception) { // test if we are dealing with a single JSON value instead (true/false/null/num/"") Reset(); try { return checkTrailing(ReadCore()); } catch (Exception) { } throw; // throw original error } } } JsonValue checkTrailing(JsonValue v) { skipWhite2(); if (ReadChar()>=0) throw ParseError("Extra characters in input"); return v; } void skipWhite2() { while (PeekChar()>=0) { while (IsWhite((char)PeekChar())) ReadChar(); int p=PeekChar(); if (p=='#' || p=='/' && PeekChar(1)=='/') { for (; ; ) { var ch=PeekChar(); if (ch<0 || ch=='\n') break; ReadChar(); } } else if (p=='/' && PeekChar(1)=='*') { ReadChar(); ReadChar(); for (; ; ) { var ch=PeekChar(); if (ch<0 || ch=='*' && PeekChar(1)=='/') break; ReadChar(); } if (PeekChar()>=0) { ReadChar(); ReadChar(); } } else break; } } protected override string GetWhite() { var res=base.GetWhite(); int to=res.Length-1; if (to>=0) { // remove trailing whitespace for (; to>0 && res[to]<=' ' && res[to]!='\n'; to--) ; // but only up to EOL if (res[to]=='\n') to--; if (to>=0 && res[to]=='\r') to--; res=res.Substring(0, to+1); foreach (char c in res) if (c>' ') return res; } return ""; } public override int SkipPeekChar() { skipWhite2(); return PeekChar(); } JsonValue ReadCore(bool objectWithoutBraces=false) { int c=objectWithoutBraces?'{':SkipPeekChar(); if (c<0) throw ParseError("Incomplete input"); switch (c) { case '[': JsonArray list; WscJsonArray wscL=null; ReadChar(); ResetWhite(); if (ReadWsc) list=wscL=new WscJsonArray(); else list=new JsonArray(); SkipPeekChar(); if (ReadWsc) wscL.Comments.Add(GetWhite()); for (int i=0; ; i++) { if (SkipPeekChar()==']') { ReadChar(); break; } if (HasReader) Reader.Index(i); var value=ReadCore(); if (HasReader) Reader.Value(value); list.Add(value); ResetWhite(); if (SkipPeekChar()==',') { ReadChar(); ResetWhite(); SkipPeekChar(); } if (ReadWsc) wscL.Comments.Add(GetWhite()); } return list; case '{': JsonObject obj; WscJsonObject wsc=null; if (!objectWithoutBraces) { ReadChar(); ResetWhite(); } if (ReadWsc) obj=wsc=new WscJsonObject() { RootBraces=!objectWithoutBraces }; else obj=new JsonObject(); SkipPeekChar(); if (ReadWsc) wsc.Comments[""]=GetWhite(); for (; ; ) { if (objectWithoutBraces) { if (SkipPeekChar()<0) break; } else if (SkipPeekChar()=='}') { ReadChar(); break; } string name=readKeyName(); skipWhite2(); Expect(':'); skipWhite2(); if (HasReader) Reader.Key(name); var value=ReadCore(); if (HasReader) Reader.Value(value); obj.Add(new JsonPair(name, value)); ResetWhite(); if (SkipPeekChar()==',') { ReadChar(); ResetWhite(); SkipPeekChar(); } if (ReadWsc) { wsc.Comments[name]=GetWhite(); wsc.Order.Add(name); } } return obj; case '\'': case '"': return ReadStringLiteral(readMlString); default: return readTfnns(c); } } string readKeyName() { // quotes for keys are optional in Hjson // unless they include {}[],: or whitespace. int c=PeekChar(); if (c=='"' || c=='\'') return ReadStringLiteral(null); sb.Length=0; int space=-1; for (; ; ) { c=PeekChar(); if (c<0) throw ParseError("Name is not closed"); char ch=(char)c; if (ch==':') { if (sb.Length==0) throw ParseError("Found ':' but no key name (for an empty key name use quotes)"); else if (space>=0 && space!=sb.Length) throw ParseError("Found whitespace in your key name (use quotes to include)"); return sb.ToString(); } else if (IsWhite(ch)) { if (space<0) space=sb.Length; ReadChar(); } else if (HjsonValue.IsPunctuatorChar(ch)) throw ParseError("Found '"+ch+"' where a key name was expected (check your syntax or use quotes if the key name includes {}[],: or whitespace)"); else { ReadChar(); sb.Append(ch); } } } void skipIndent(int indent) { while (indent-->0) { char c=(char)PeekChar(); if (IsWhite(c) && c!='\n') ReadChar(); else break; } } string readMlString() { // Parse a multiline string value. int triple=0; sb.Length=0; // we are at ''' var indent=Column-3; // skip white/to (newline) for (; ; ) { char c=(char)PeekChar(); if (IsWhite(c) && c!='\n') ReadChar(); else break; } if (PeekChar()=='\n') { ReadChar(); skipIndent(indent); } // When parsing for string values, we must look for " and \ characters. while (true) { int ch=PeekChar(); if (ch<0) throw ParseError("Bad multiline string"); else if (ch=='\'') { triple++; ReadChar(); if (triple==3) { if (sb[sb.Length-1]=='\n') sb.Length--; return sb.ToString(); } else continue; } else { while (triple>0) { sb.Append('\''); triple--; } } if (ch=='\n') { sb.Append('\n'); ReadChar(); skipIndent(indent); } else { if (ch!='\r') sb.Append((char)ch); ReadChar(); } } } internal static bool TryParseNumericLiteral(string text, bool stopAtNext, out JsonValue value) { int c, leadingZeros=0, p=0; double val=0; bool negative=false, testLeading=true; text+='\0'; value=null; if (text[p]=='-') { negative=true; p++; if (text[p]==0) return false; } for (int x=0; ; x++) { c=text[p]; if (c<'0' || c>'9') break; if (testLeading) { if (c=='0') leadingZeros++; else testLeading=false; } val=val*10+(c-'0'); p++; } if (testLeading) leadingZeros--; // single 0 is allowed if (leadingZeros>0) return false; // fraction if (text[p]=='.') { if (leadingZeros<0) return false; int fdigits=0; double frac=0; p++; if (text[p]==0) return false; double d=10; for (; ; ) { c=text[p]; if (c<'0' || '9'<c) break; p++; frac+=(c-'0')/d; d*=10; fdigits++; } if (fdigits==0) return false; val+=frac; } c=text[p]; if (c=='e' || c=='E') { // exponent int exp=0, expSign=1; p++; if (text[p]==0) return false; c=text[p]; if (c=='-') { p++; expSign=-1; } else if (c=='+') p++; if (text[p]==0) return false; for (; ; ) { c=text[p]; if (c<'0' || c>'9') break; exp=exp*10+(c-'0'); p++; } if (exp!=0) val*=Math.Pow(10, exp*expSign); } while (p<text.Length && IsWhite(text[p])) p++; bool foundStop=false; if (p<text.Length && stopAtNext) { // end scan if we find a control character like ,}] or a comment char ch=text[p]; if (ch==',' || ch=='}' || ch==']' || ch=='#' || ch=='/' && (text.Length>p+1 && (text[p+1]=='/' || text[p+1]=='*'))) foundStop=true; } if (p+1!=text.Length && !foundStop) return false; if (negative) { if (val==0.0) { value=-0.0; return true; } val*=-1; } long lval=(long)val; if (lval==val) value=lval; else value=val; return true; } JsonValue readTfnns(int c) { if (HjsonValue.IsPunctuatorChar((char)c)) throw ParseError("Found a punctuator character '" + c + "' when expecting a quoteless string (check your syntax)"); sb.Length=0; for (; ; ) { bool isEol=c<0 || c=='\n'; if (isEol || c==',' || c=='}' || c==']' || c=='#' || c=='/' && (PeekChar(1)=='/' || PeekChar(1)=='*')) { if (sb.Length>0) { char ch=sb[0]; switch (ch) { case 'f': if (sb.ToString().Trim()=="false") return false; break; case 'n': if (sb.ToString().Trim()=="null") return null; break; case 't': if (sb.ToString().Trim()=="true") return true; break; default: if (ch=='-' || ch>='0' && ch<='9') { JsonValue res; if (TryParseNumericLiteral(sb.ToString(), false, out res)) return res; } break; } } if (isEol) { // remove any whitespace at the end (ignored in quoteless strings) return HjsonDsf.Parse(dsfProviders, sb.ToString().Trim()); } } ReadChar(); if (c!='\r') sb.Append((char)c); c=PeekChar(); } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Runtime.InteropServices; using System.IO; using System.Text; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; // To simplify the process of finding the toolbox bitmap resource: // #1 Create an internal class called "resfinder" outside of the root namespace. // #2 Use "resfinder" in the toolbox bitmap attribute instead of the control name. // #3 use the "<default namespace>.<resourcename>" string to locate the resource. // See: http://www.bobpowell.net/toolboxbitmap.htm internal class resfinder { } namespace WeifenLuo.WinFormsUI.Docking { [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")] public delegate IDockContent DeserializeDockContent(string persistString); [LocalizedDescription("DockPanel_Description")] [Designer("System.Windows.Forms.Design.ControlDesigner, System.Design")] [ToolboxBitmap(typeof(resfinder), "WeifenLuo.WinFormsUI.Docking.DockPanel.bmp")] [DefaultProperty("DocumentStyle")] [DefaultEvent("ActiveContentChanged")] public partial class DockPanel : Panel { private readonly FocusManagerImpl m_focusManager; private readonly DockPanelExtender m_extender; private readonly DockPaneCollection m_panes; private readonly FloatWindowCollection m_floatWindows; private AutoHideWindowControl m_autoHideWindow; private DockWindowCollection m_dockWindows; private readonly DockContent m_dummyContent; private readonly Control m_dummyControl; public DockPanel() { ShowAutoHideContentOnHover = true; m_focusManager = new FocusManagerImpl(this); m_extender = new DockPanelExtender(this); m_panes = new DockPaneCollection(); m_floatWindows = new FloatWindowCollection(); SuspendLayout(); m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this); m_autoHideWindow.Visible = false; m_autoHideWindow.ActiveContentChanged += m_autoHideWindow_ActiveContentChanged; SetAutoHideWindowParent(); m_dummyControl = new DummyControl(); m_dummyControl.Bounds = new Rectangle(0, 0, 1, 1); Controls.Add(m_dummyControl); LoadDockWindows(); m_dummyContent = new DockContent(); if (m_dockPanelTheme != null) m_dockPanelTheme.Apply(this); // needed for VS2012LightTheme ResumeLayout(); } private Color m_BackColor; /// <summary> /// Determines the color with which the client rectangle will be drawn. /// If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane). /// The BackColor property changes the borders of surrounding controls (DockPane). /// Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle). /// For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control) /// </summary> [Description("Determines the color with which the client rectangle will be drawn.\r\n" + "If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).\r\n" + "The BackColor property changes the borders of surrounding controls (DockPane).\r\n" + "Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).\r\n" + "For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control).")] public Color DockBackColor { get { return !m_BackColor.IsEmpty ? m_BackColor : base.BackColor; } set { if (m_BackColor != value) { m_BackColor = value; this.Refresh(); } } } private bool ShouldSerializeDockBackColor() { return !m_BackColor.IsEmpty; } private void ResetDockBackColor() { DockBackColor = Color.Empty; } private AutoHideStripBase m_autoHideStripControl = null; internal AutoHideStripBase AutoHideStripControl { get { if (m_autoHideStripControl == null) { m_autoHideStripControl = AutoHideStripFactory.CreateAutoHideStrip(this); Controls.Add(m_autoHideStripControl); } return m_autoHideStripControl; } } internal void ResetAutoHideStripControl() { if (m_autoHideStripControl != null) m_autoHideStripControl.Dispose(); m_autoHideStripControl = null; } private void MdiClientHandleAssigned(object sender, EventArgs e) { SetMdiClient(); PerformLayout(); } private void MdiClient_Layout(object sender, LayoutEventArgs e) { if (DocumentStyle != DocumentStyle.DockingMdi) return; foreach (DockPane pane in Panes) if (pane.DockState == DockState.Document) pane.SetContentBounds(); InvalidateWindowRegion(); } private bool m_disposed = false; protected override void Dispose(bool disposing) { if (!m_disposed && disposing) { m_focusManager.Dispose(); if (m_mdiClientController != null) { m_mdiClientController.HandleAssigned -= new EventHandler(MdiClientHandleAssigned); m_mdiClientController.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate); m_mdiClientController.Layout -= new LayoutEventHandler(MdiClient_Layout); m_mdiClientController.Dispose(); } FloatWindows.Dispose(); Panes.Dispose(); DummyContent.Dispose(); m_disposed = true; } base.Dispose(disposing); } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IDockContent ActiveAutoHideContent { get { return AutoHideWindow.ActiveContent; } set { AutoHideWindow.ActiveContent = value; } } private bool m_allowEndUserDocking = !Win32Helper.IsRunningOnMono; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_AllowEndUserDocking_Description")] [DefaultValue(true)] public bool AllowEndUserDocking { get { if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking) m_allowEndUserDocking = false; return m_allowEndUserDocking; } set { if (Win32Helper.IsRunningOnMono && value) throw new InvalidOperationException("AllowEndUserDocking can only be false if running on Mono"); m_allowEndUserDocking = value; } } private bool m_allowEndUserNestedDocking = !Win32Helper.IsRunningOnMono; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_AllowEndUserNestedDocking_Description")] [DefaultValue(true)] public bool AllowEndUserNestedDocking { get { if (Win32Helper.IsRunningOnMono && m_allowEndUserDocking) m_allowEndUserDocking = false; return m_allowEndUserNestedDocking; } set { if (Win32Helper.IsRunningOnMono && value) throw new InvalidOperationException("AllowEndUserNestedDocking can only be false if running on Mono"); m_allowEndUserNestedDocking = value; } } private DockContentCollection m_contents = new DockContentCollection(); [Browsable(false)] public DockContentCollection Contents { get { return m_contents; } } internal DockContent DummyContent { get { return m_dummyContent; } } private bool m_rightToLeftLayout = false; [DefaultValue(false)] [LocalizedCategory("Appearance")] [LocalizedDescription("DockPanel_RightToLeftLayout_Description")] public bool RightToLeftLayout { get { return m_rightToLeftLayout; } set { if (m_rightToLeftLayout == value) return; m_rightToLeftLayout = value; foreach (FloatWindow floatWindow in FloatWindows) floatWindow.RightToLeftLayout = value; } } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); foreach (FloatWindow floatWindow in FloatWindows) { if (floatWindow.RightToLeft != RightToLeft) floatWindow.RightToLeft = RightToLeft; } } private bool m_showDocumentIcon = false; [DefaultValue(false)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_ShowDocumentIcon_Description")] public bool ShowDocumentIcon { get { return m_showDocumentIcon; } set { if (m_showDocumentIcon == value) return; m_showDocumentIcon = value; Refresh(); } } private DocumentTabStripLocation m_documentTabStripLocation = DocumentTabStripLocation.Top; [DefaultValue(DocumentTabStripLocation.Top)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DocumentTabStripLocation")] public DocumentTabStripLocation DocumentTabStripLocation { get { return m_documentTabStripLocation; } set { m_documentTabStripLocation = value; } } [Browsable(false)] public DockPanelExtender Extender { get { return m_extender; } } [Browsable(false)] public DockPanelExtender.IDockPaneFactory DockPaneFactory { get { return Extender.DockPaneFactory; } } [Browsable(false)] public DockPanelExtender.IFloatWindowFactory FloatWindowFactory { get { return Extender.FloatWindowFactory; } } [Browsable(false)] public DockPanelExtender.IDockWindowFactory DockWindowFactory { get { return Extender.DockWindowFactory; } } internal DockPanelExtender.IDockPaneCaptionFactory DockPaneCaptionFactory { get { return Extender.DockPaneCaptionFactory; } } internal DockPanelExtender.IDockPaneStripFactory DockPaneStripFactory { get { return Extender.DockPaneStripFactory; } } internal DockPanelExtender.IAutoHideStripFactory AutoHideStripFactory { get { return Extender.AutoHideStripFactory; } } [Browsable(false)] public DockPaneCollection Panes { get { return m_panes; } } internal Rectangle DockArea { get { return new Rectangle(DockPadding.Left, DockPadding.Top, ClientRectangle.Width - DockPadding.Left - DockPadding.Right, ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom); } } private double m_dockBottomPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockBottomPortion_Description")] [DefaultValue(0.25)] public double DockBottomPortion { get { return m_dockBottomPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockBottomPortion) return; m_dockBottomPortion = value; if (m_dockBottomPortion < 1 && m_dockTopPortion < 1) { if (m_dockTopPortion + m_dockBottomPortion > 1) m_dockTopPortion = 1 - m_dockBottomPortion; } PerformLayout(); } } private double m_dockLeftPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockLeftPortion_Description")] [DefaultValue(0.25)] public double DockLeftPortion { get { return m_dockLeftPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockLeftPortion) return; m_dockLeftPortion = value; if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) { if (m_dockLeftPortion + m_dockRightPortion > 1) m_dockRightPortion = 1 - m_dockLeftPortion; } PerformLayout(); } } private double m_dockRightPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockRightPortion_Description")] [DefaultValue(0.25)] public double DockRightPortion { get { return m_dockRightPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockRightPortion) return; m_dockRightPortion = value; if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) { if (m_dockLeftPortion + m_dockRightPortion > 1) m_dockLeftPortion = 1 - m_dockRightPortion; } PerformLayout(); } } private double m_dockTopPortion = 0.25; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DockTopPortion_Description")] [DefaultValue(0.25)] public double DockTopPortion { get { return m_dockTopPortion; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); if (value == m_dockTopPortion) return; m_dockTopPortion = value; if (m_dockTopPortion < 1 && m_dockBottomPortion < 1) { if (m_dockTopPortion + m_dockBottomPortion > 1) m_dockBottomPortion = 1 - m_dockTopPortion; } PerformLayout(); } } [Browsable(false)] public DockWindowCollection DockWindows { get { return m_dockWindows; } } public void UpdateDockWindowZOrder(DockStyle dockStyle, bool fullPanelEdge) { if (dockStyle == DockStyle.Left) { if (fullPanelEdge) DockWindows[DockState.DockLeft].SendToBack(); else DockWindows[DockState.DockLeft].BringToFront(); } else if (dockStyle == DockStyle.Right) { if (fullPanelEdge) DockWindows[DockState.DockRight].SendToBack(); else DockWindows[DockState.DockRight].BringToFront(); } else if (dockStyle == DockStyle.Top) { if (fullPanelEdge) DockWindows[DockState.DockTop].SendToBack(); else DockWindows[DockState.DockTop].BringToFront(); } else if (dockStyle == DockStyle.Bottom) { if (fullPanelEdge) DockWindows[DockState.DockBottom].SendToBack(); else DockWindows[DockState.DockBottom].BringToFront(); } } [Browsable(false)] public int DocumentsCount { get { int count = 0; foreach (IDockContent content in Documents) count++; return count; } } public IDockContent[] DocumentsToArray() { int count = DocumentsCount; IDockContent[] documents = new IDockContent[count]; int i = 0; foreach (IDockContent content in Documents) { documents[i] = content; i++; } return documents; } [Browsable(false)] public IEnumerable<IDockContent> Documents { get { foreach (IDockContent content in Contents) { if (content.DockHandler.DockState == DockState.Document) yield return content; } } } private Control DummyControl { get { return m_dummyControl; } } [Browsable(false)] public FloatWindowCollection FloatWindows { get { return m_floatWindows; } } private Size m_defaultFloatWindowSize = new Size(300, 300); [Category("Layout")] [LocalizedDescription("DockPanel_DefaultFloatWindowSize_Description")] public Size DefaultFloatWindowSize { get { return m_defaultFloatWindowSize; } set { m_defaultFloatWindowSize = value; } } private bool ShouldSerializeDefaultFloatWindowSize() { return DefaultFloatWindowSize != new Size(300, 300); } private void ResetDefaultFloatWindowSize() { DefaultFloatWindowSize = new Size(300, 300); } private DocumentStyle m_documentStyle = DocumentStyle.DockingMdi; [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_DocumentStyle_Description")] [DefaultValue(DocumentStyle.DockingMdi)] public DocumentStyle DocumentStyle { get { return m_documentStyle; } set { if (value == m_documentStyle) return; if (!Enum.IsDefined(typeof(DocumentStyle), value)) throw new InvalidEnumArgumentException(); if (value == DocumentStyle.SystemMdi && DockWindows[DockState.Document].VisibleNestedPanes.Count > 0) throw new InvalidEnumArgumentException(); m_documentStyle = value; SuspendLayout(true); SetAutoHideWindowParent(); SetMdiClient(); InvalidateWindowRegion(); foreach (IDockContent content in Contents) { if (content.DockHandler.DockState == DockState.Document) content.DockHandler.SetPaneAndVisible(content.DockHandler.Pane); } PerformMdiClientLayout(); ResumeLayout(true, true); } } private bool _supprtDeeplyNestedContent = false; [LocalizedCategory("Category_Performance")] [LocalizedDescription("DockPanel_SupportDeeplyNestedContent_Description")] [DefaultValue(false)] public bool SupportDeeplyNestedContent { get { return _supprtDeeplyNestedContent; } set { _supprtDeeplyNestedContent = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockPanel_ShowAutoHideContentOnHover_Description")] [DefaultValue(true)] public bool ShowAutoHideContentOnHover { get; set; } public int GetDockWindowSize(DockState dockState) { if (dockState == DockState.DockLeft || dockState == DockState.DockRight) { int width = ClientRectangle.Width - DockPadding.Left - DockPadding.Right; int dockLeftSize = m_dockLeftPortion >= 1 ? (int)m_dockLeftPortion : (int)(width * m_dockLeftPortion); int dockRightSize = m_dockRightPortion >= 1 ? (int)m_dockRightPortion : (int)(width * m_dockRightPortion); if (dockLeftSize < MeasurePane.MinSize) dockLeftSize = MeasurePane.MinSize; if (dockRightSize < MeasurePane.MinSize) dockRightSize = MeasurePane.MinSize; if (dockLeftSize + dockRightSize > width - MeasurePane.MinSize) { int adjust = (dockLeftSize + dockRightSize) - (width - MeasurePane.MinSize); dockLeftSize -= adjust / 2; dockRightSize -= adjust / 2; } return dockState == DockState.DockLeft ? dockLeftSize : dockRightSize; } else if (dockState == DockState.DockTop || dockState == DockState.DockBottom) { int height = ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom; int dockTopSize = m_dockTopPortion >= 1 ? (int)m_dockTopPortion : (int)(height * m_dockTopPortion); int dockBottomSize = m_dockBottomPortion >= 1 ? (int)m_dockBottomPortion : (int)(height * m_dockBottomPortion); if (dockTopSize < MeasurePane.MinSize) dockTopSize = MeasurePane.MinSize; if (dockBottomSize < MeasurePane.MinSize) dockBottomSize = MeasurePane.MinSize; if (dockTopSize + dockBottomSize > height - MeasurePane.MinSize) { int adjust = (dockTopSize + dockBottomSize) - (height - MeasurePane.MinSize); dockTopSize -= adjust / 2; dockBottomSize -= adjust / 2; } return dockState == DockState.DockTop ? dockTopSize : dockBottomSize; } else return 0; } protected override void OnLayout(LayoutEventArgs levent) { SuspendLayout(true); AutoHideStripControl.Bounds = ClientRectangle; CalculateDockPadding(); DockWindows[DockState.DockLeft].Width = GetDockWindowSize(DockState.DockLeft); DockWindows[DockState.DockRight].Width = GetDockWindowSize(DockState.DockRight); DockWindows[DockState.DockTop].Height = GetDockWindowSize(DockState.DockTop); DockWindows[DockState.DockBottom].Height = GetDockWindowSize(DockState.DockBottom); AutoHideWindow.Bounds = GetAutoHideWindowBounds(AutoHideWindowRectangle); DockWindows[DockState.Document].BringToFront(); AutoHideWindow.BringToFront(); base.OnLayout(levent); if (DocumentStyle == DocumentStyle.SystemMdi && MdiClientExists) { SetMdiClientBounds(SystemMdiClientBounds); InvalidateWindowRegion(); } else if (DocumentStyle == DocumentStyle.DockingMdi) InvalidateWindowRegion(); ResumeLayout(true, true); } internal Rectangle GetTabStripRectangle(DockState dockState) { return AutoHideStripControl.GetTabStripRectangle(dockState); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (DockBackColor == BackColor) return; Graphics g = e.Graphics; SolidBrush bgBrush = new SolidBrush(DockBackColor); g.FillRectangle(bgBrush, ClientRectangle); } internal void AddContent(IDockContent content) { if (content == null) throw(new ArgumentNullException()); if (!Contents.Contains(content)) { Contents.Add(content); OnContentAdded(new DockContentEventArgs(content)); } } internal void AddPane(DockPane pane) { if (Panes.Contains(pane)) return; Panes.Add(pane); } internal void AddFloatWindow(FloatWindow floatWindow) { if (FloatWindows.Contains(floatWindow)) return; FloatWindows.Add(floatWindow); } private void CalculateDockPadding() { DockPadding.All = 0; int height = AutoHideStripControl.MeasureHeight(); if (AutoHideStripControl.GetNumberOfPanes(DockState.DockLeftAutoHide) > 0) DockPadding.Left = height; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockRightAutoHide) > 0) DockPadding.Right = height; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockTopAutoHide) > 0) DockPadding.Top = height; if (AutoHideStripControl.GetNumberOfPanes(DockState.DockBottomAutoHide) > 0) DockPadding.Bottom = height; } internal void RemoveContent(IDockContent content) { if (content == null) throw(new ArgumentNullException()); if (Contents.Contains(content)) { Contents.Remove(content); OnContentRemoved(new DockContentEventArgs(content)); } } internal void RemovePane(DockPane pane) { if (!Panes.Contains(pane)) return; Panes.Remove(pane); } internal void RemoveFloatWindow(FloatWindow floatWindow) { if (!FloatWindows.Contains(floatWindow)) return; FloatWindows.Remove(floatWindow); if (FloatWindows.Count != 0) return; if (ParentForm == null) return; ParentForm.Focus(); } public void SetPaneIndex(DockPane pane, int index) { int oldIndex = Panes.IndexOf(pane); if (oldIndex == -1) throw(new ArgumentException(Strings.DockPanel_SetPaneIndex_InvalidPane)); if (index < 0 || index > Panes.Count - 1) if (index != -1) throw(new ArgumentOutOfRangeException(Strings.DockPanel_SetPaneIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Panes.Count - 1 && index == -1) return; Panes.Remove(pane); if (index == -1) Panes.Add(pane); else if (oldIndex < index) Panes.AddAt(pane, index - 1); else Panes.AddAt(pane, index); } public void SuspendLayout(bool allWindows) { FocusManager.SuspendFocusTracking(); SuspendLayout(); if (allWindows) SuspendMdiClientLayout(); } public void ResumeLayout(bool performLayout, bool allWindows) { FocusManager.ResumeFocusTracking(); ResumeLayout(performLayout); if (allWindows) ResumeMdiClientLayout(performLayout); } internal Form ParentForm { get { if (!IsParentFormValid()) throw new InvalidOperationException(Strings.DockPanel_ParentForm_Invalid); return GetMdiClientController().ParentForm; } } private bool IsParentFormValid() { if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow) return true; if (!MdiClientExists) GetMdiClientController().RenewMdiClient(); return (MdiClientExists); } protected override void OnParentChanged(EventArgs e) { SetAutoHideWindowParent(); GetMdiClientController().ParentForm = (this.Parent as Form); base.OnParentChanged (e); } private void SetAutoHideWindowParent() { Control parent; if (DocumentStyle == DocumentStyle.DockingMdi || DocumentStyle == DocumentStyle.SystemMdi) parent = this.Parent; else parent = this; if (AutoHideWindow.Parent != parent) { AutoHideWindow.Parent = parent; AutoHideWindow.BringToFront(); } } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged (e); if (Visible) SetMdiClient(); } private Rectangle SystemMdiClientBounds { get { if (!IsParentFormValid() || !Visible) return Rectangle.Empty; Rectangle rect = ParentForm.RectangleToClient(RectangleToScreen(DocumentWindowBounds)); return rect; } } internal Rectangle DocumentWindowBounds { get { Rectangle rectDocumentBounds = DisplayRectangle; if (DockWindows[DockState.DockLeft].Visible) { rectDocumentBounds.X += DockWindows[DockState.DockLeft].Width; rectDocumentBounds.Width -= DockWindows[DockState.DockLeft].Width; } if (DockWindows[DockState.DockRight].Visible) rectDocumentBounds.Width -= DockWindows[DockState.DockRight].Width; if (DockWindows[DockState.DockTop].Visible) { rectDocumentBounds.Y += DockWindows[DockState.DockTop].Height; rectDocumentBounds.Height -= DockWindows[DockState.DockTop].Height; } if (DockWindows[DockState.DockBottom].Visible) rectDocumentBounds.Height -= DockWindows[DockState.DockBottom].Height; return rectDocumentBounds; } } private PaintEventHandler m_dummyControlPaintEventHandler = null; private void InvalidateWindowRegion() { if (DesignMode) return; if (m_dummyControlPaintEventHandler == null) m_dummyControlPaintEventHandler = new PaintEventHandler(DummyControl_Paint); DummyControl.Paint += m_dummyControlPaintEventHandler; DummyControl.Invalidate(); } void DummyControl_Paint(object sender, PaintEventArgs e) { DummyControl.Paint -= m_dummyControlPaintEventHandler; UpdateWindowRegion(); } private void UpdateWindowRegion() { if (this.DocumentStyle == DocumentStyle.DockingMdi) UpdateWindowRegion_ClipContent(); else if (this.DocumentStyle == DocumentStyle.DockingSdi || this.DocumentStyle == DocumentStyle.DockingWindow) UpdateWindowRegion_FullDocumentArea(); else if (this.DocumentStyle == DocumentStyle.SystemMdi) UpdateWindowRegion_EmptyDocumentArea(); } private void UpdateWindowRegion_FullDocumentArea() { SetRegion(null); } private void UpdateWindowRegion_EmptyDocumentArea() { Rectangle rect = DocumentWindowBounds; SetRegion(new Rectangle[] { rect }); } private void UpdateWindowRegion_ClipContent() { int count = 0; foreach (DockPane pane in this.Panes) { if (!pane.Visible || pane.DockState != DockState.Document) continue; count ++; } if (count == 0) { SetRegion(null); return; } Rectangle[] rects = new Rectangle[count]; int i = 0; foreach (DockPane pane in this.Panes) { if (!pane.Visible || pane.DockState != DockState.Document) continue; rects[i] = RectangleToClient(pane.RectangleToScreen(pane.ContentRectangle)); i++; } SetRegion(rects); } private Rectangle[] m_clipRects = null; private void SetRegion(Rectangle[] clipRects) { if (!IsClipRectsChanged(clipRects)) return; m_clipRects = clipRects; if (m_clipRects == null || m_clipRects.GetLength(0) == 0) Region = null; else { Region region = new Region(new Rectangle(0, 0, this.Width, this.Height)); foreach (Rectangle rect in m_clipRects) region.Exclude(rect); if (Region != null) { Region.Dispose(); } Region = region; } } private bool IsClipRectsChanged(Rectangle[] clipRects) { if (clipRects == null && m_clipRects == null) return false; else if ((clipRects == null) != (m_clipRects == null)) return true; foreach (Rectangle rect in clipRects) { bool matched = false; foreach (Rectangle rect2 in m_clipRects) { if (rect == rect2) { matched = true; break; } } if (!matched) return true; } foreach (Rectangle rect2 in m_clipRects) { bool matched = false; foreach (Rectangle rect in clipRects) { if (rect == rect2) { matched = true; break; } } if (!matched) return true; } return false; } private static readonly object ActiveAutoHideContentChangedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ActiveAutoHideContentChanged_Description")] public event EventHandler ActiveAutoHideContentChanged { add { Events.AddHandler(ActiveAutoHideContentChangedEvent, value); } remove { Events.RemoveHandler(ActiveAutoHideContentChangedEvent, value); } } protected virtual void OnActiveAutoHideContentChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActiveAutoHideContentChangedEvent]; if (handler != null) handler(this, e); } private void m_autoHideWindow_ActiveContentChanged(object sender, EventArgs e) { OnActiveAutoHideContentChanged(e); } private static readonly object ContentAddedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ContentAdded_Description")] public event EventHandler<DockContentEventArgs> ContentAdded { add { Events.AddHandler(ContentAddedEvent, value); } remove { Events.RemoveHandler(ContentAddedEvent, value); } } protected virtual void OnContentAdded(DockContentEventArgs e) { EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentAddedEvent]; if (handler != null) handler(this, e); } private static readonly object ContentRemovedEvent = new object(); [LocalizedCategory("Category_DockingNotification")] [LocalizedDescription("DockPanel_ContentRemoved_Description")] public event EventHandler<DockContentEventArgs> ContentRemoved { add { Events.AddHandler(ContentRemovedEvent, value); } remove { Events.RemoveHandler(ContentRemovedEvent, value); } } protected virtual void OnContentRemoved(DockContentEventArgs e) { EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentRemovedEvent]; if (handler != null) handler(this, e); } internal void ReloadDockWindows() { var old = m_dockWindows; LoadDockWindows(); foreach (var dockWindow in old) { Controls.Remove(dockWindow); dockWindow.Dispose(); } } internal void LoadDockWindows() { m_dockWindows = new DockWindowCollection(this); foreach (var dockWindow in DockWindows) { Controls.Add(dockWindow); } } public void ResetAutoHideStripWindow() { var old = m_autoHideWindow; m_autoHideWindow = Extender.AutoHideWindowFactory.CreateAutoHideWindow(this); m_autoHideWindow.Visible = false; SetAutoHideWindowParent(); old.Visible = false; old.Parent = null; old.Dispose(); } } }
using System; using Xamarin.Forms; using System.Collections.Generic; namespace GlowingBrain.DataCapture.Views { public class Option : ContentView { const int UnselectedImageIndex = 0; const int SelectedImageIndex = 1; public event EventHandler<EventArgs<bool>> IsSelectedChanged; Label Label { get; set; } PagePanel PagePanel { get; set; } public static readonly BindableProperty TextProperty = BindableProperty.Create<Option, string> ( p => p.Text, "Option", BindingMode.OneWay, propertyChanged: OnTextChanged); public static readonly BindableProperty TextColorProperty = BindableProperty.Create<Option, Color> ( p => p.TextColor, Color.Black, BindingMode.OneWay, propertyChanged: OnTextColorChanged); public static readonly BindableProperty FontFamilyProperty = BindableProperty.Create<Option, string> ( p => p.FontFamily, String.Empty, BindingMode.OneWay, propertyChanged: OnFontFamilyChanged); public static readonly BindableProperty FontSizeProperty = BindableProperty.Create<Option, double> ( p => p.FontSize, -1, BindingMode.OneWay, propertyChanged: OnFontSizeChanged); public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create<Option, bool> ( p => p.IsSelected, false, BindingMode.TwoWay, propertyChanged: OnIsSelectedChanged); public static readonly BindableProperty SelectedSourceProperty = BindableProperty.Create<Option, ImageSource> ( p => p.SelectedSource, null, BindingMode.OneWay, propertyChanged: OnSelectedSourceChanged); public static readonly BindableProperty UnselectedSourceProperty = BindableProperty.Create<Option, ImageSource> ( p => p.UnselectedSource, null, BindingMode.OneWay, propertyChanged: OnUnselectedSourceChanged); public Option () { Label = new Label { Text = "Option", HorizontalOptions = LayoutOptions.StartAndExpand, VerticalOptions = LayoutOptions.Center }; PagePanel = new PagePanel { HorizontalOptions = LayoutOptions.End, Pages = new List<View> { new Image (), new Image () } }; var layout = new StackLayout { Orientation = StackOrientation.Horizontal, Children = { Label, PagePanel } }; var tapGestureRecognizer = new TapGestureRecognizer (); tapGestureRecognizer.Tapped += (sender, e) => OnTapped (); GestureRecognizers.Add (tapGestureRecognizer); Content = layout; SetImageState (); SetLabelState (); } public bool IsSelected { get { return (bool)GetValue (IsSelectedProperty); } set { SetValue (IsSelectedProperty, value); } } public string Text { get { return (string)GetValue (TextProperty); } set { SetValue (TextProperty, value); } } public Color TextColor { get { return (Color)GetValue (TextColorProperty); } set { SetValue (TextColorProperty, value); } } public string FontFamily { get { return (string)GetValue (FontFamilyProperty); } set { SetValue (FontFamilyProperty, value); } } public double FontSize { get { return (double)GetValue (FontSizeProperty); } set { SetValue (FontSizeProperty, value); } } public ImageSource SelectedSource { get { return (ImageSource)GetValue (SelectedSourceProperty); } set { SetValue (SelectedSourceProperty, value); } } public ImageSource UnselectedSource { get { return (ImageSource)GetValue (UnselectedSourceProperty); } set { SetValue (UnselectedSourceProperty, value); } } protected virtual void OnTapped () { IsSelected = true; } protected virtual void RaiseOnIsSelectedChanged () { var handler = IsSelectedChanged; if (handler != null) { handler (this, new EventArgs<bool> (IsSelected)); } } protected virtual void OnTextChanged (string oldValue, string newValue) { SetLabelState (); } protected virtual void OnTextColorChanged (Color oldValue, Color newValue) { SetLabelState (); } protected virtual void OnFontFamilyChanged (string oldValue, string newValue) { SetLabelState (); } protected virtual void OnFontSizeChanged (double oldValue, double newValue) { SetLabelState (); } protected virtual void OnIsSelectedChanged (bool oldValue, bool newValue) { SetImageState (); RaiseOnIsSelectedChanged (); } protected virtual void OnSelectedSourceChanged (ImageSource oldValue, ImageSource newValue) { ((Image)PagePanel.Pages [SelectedImageIndex]).Source = newValue; } protected virtual void OnUnselectedSourceChanged (ImageSource oldValue, ImageSource newValue) { ((Image)PagePanel.Pages [UnselectedImageIndex]).Source = newValue; } protected virtual void SetImageState () { PagePanel.SelectedPage = PagePanel.Pages [IsSelected ? SelectedImageIndex : UnselectedImageIndex]; } protected virtual void SetLabelState () { Label.Text = Text; Label.TextColor = TextColor; if (!String.IsNullOrEmpty (FontFamily)) { Label.FontFamily = FontFamily; } if (FontSize > 0) { Label.FontSize = FontSize; } } static void OnTextChanged (BindableObject bindable, string oldValue, string newValue) { ((Option)bindable).OnTextChanged (oldValue, newValue); } static void OnTextColorChanged (BindableObject bindable, Color oldValue, Color newValue) { ((Option)bindable).OnTextColorChanged (oldValue, newValue); } static void OnFontFamilyChanged (BindableObject bindable, string oldValue, string newValue) { ((Option)bindable).OnFontFamilyChanged (oldValue, newValue); } static void OnFontSizeChanged (BindableObject bindable, double oldValue, double newValue) { ((Option)bindable).OnFontSizeChanged (oldValue, newValue); } static void OnIsSelectedChanged (BindableObject bindable, bool oldValue, bool newValue) { ((Option)bindable).OnIsSelectedChanged (oldValue, newValue); } static void OnSelectedSourceChanged (BindableObject bindable, ImageSource oldValue, ImageSource newValue) { ((Option)bindable).OnSelectedSourceChanged (oldValue, newValue); } static void OnUnselectedSourceChanged (BindableObject bindable, ImageSource oldValue, ImageSource newValue) { ((Option)bindable).OnUnselectedSourceChanged (oldValue, newValue); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Tarif_ListTM : System.Web.UI.Page { public int NoKe = 0; protected string dsReportSessionName = "dsTarifTM"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["TarifManagement"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } if (Session["AddTarif"] != null) { btnNew.Visible = true; btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddTarif"); } else btnNew.Visible = false; btnSearch.Text = Resources.GetString("", "Search"); ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif"; ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif"; ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif"; ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif"; GetListKelompokLayanan(); UpdateDataView(true); } } public void GetListKelompokLayanan() { string KelompokLayananId = ""; SIMRS.DataAccess.RS_KelompokLayanan myObj = new SIMRS.DataAccess.RS_KelompokLayanan(); DataTable dt = myObj.GetList(); cmbKelompokLayanan.Items.Clear(); int i = 0; cmbKelompokLayanan.Items.Add(""); cmbKelompokLayanan.Items[i].Text = ""; cmbKelompokLayanan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbKelompokLayanan.Items.Add(""); cmbKelompokLayanan.Items[i].Text = dr["Nama"].ToString(); cmbKelompokLayanan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == KelompokLayananId) cmbKelompokLayanan.SelectedIndex = i; i++; } } //public void GetListJenisLayanan() //{ // string JenisLayananId = ""; // SIMRS.DataAccess.RS_JenisLayanan myObj = new SIMRS.DataAccess.RS_JenisLayanan(); // DataTable dt = myObj.GetList(); // cmbJenisLayanan.Items.Clear(); // int i = 0; // cmbJenisLayanan.Items.Add(""); // cmbJenisLayanan.Items[i].Text = ""; // cmbJenisLayanan.Items[i].Value = ""; // i++; // foreach (DataRow dr in dt.Rows) // { // cmbJenisLayanan.Items.Add(""); // cmbJenisLayanan.Items[i].Text = dr["Nama"].ToString(); // cmbJenisLayanan.Items[i].Value = dr["Id"].ToString(); // if (dr["Id"].ToString() == JenisLayananId) // cmbJenisLayanan.SelectedIndex = i; // i++; // } //} #region .Update View Data ////////////////////////////////////////////////////////////////////// // PhysicalDataRead // ------------------------------------------------------------------ /// <summary> /// This function is responsible for loading data from database. /// </summary> /// <returns>DataSet</returns> public DataSet PhysicalDataRead() { // Local variables DataSet oDS = new DataSet(); // Get Data SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); myObj.JenisLayananId = 4;//Tindakan Medis DataTable myData = myObj.SelectAllWJenisLayananIdLogic(); oDS.Tables.Add(myData); return oDS; } /// <summary> /// This function is responsible for binding data to Datagrid. /// </summary> /// <param name="dv"></param> private void BindData(DataView dv) { // Sets the sorting order dv.Sort = DataGridList.Attributes["SortField"]; if (DataGridList.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { DataGridList.ShowFooter = false; int intRowCount = dv.Count; int intPageSaze = DataGridList.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (DataGridList.CurrentPageIndex >= intPageCount) DataGridList.CurrentPageIndex = intPageCount - 1; } else { DataGridList.ShowFooter = true; DataGridList.CurrentPageIndex = 0; } // Re-binds the grid NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex; DataGridList.DataSource = dv; DataGridList.DataBind(); int CurrentPage = DataGridList.CurrentPageIndex + 1; lblCurrentPage.Text = CurrentPage.ToString(); lblTotalPage.Text = DataGridList.PageCount.ToString(); lblTotalRecord.Text = dv.Count.ToString(); } /// <summary> /// This function is responsible for loading data from database and store to Session. /// </summary> /// <param name="strDataSessionName"></param> public void DataFromSourceToMemory(String strDataSessionName) { // Gets rows from the data source DataSet oDS = PhysicalDataRead(); // Stores it in the session cache Session[strDataSessionName] = oDS; } /// <summary> /// This function is responsible for update data view from datagrid. /// </summary> /// <param name="requery">true = get data from database, false= get data from session</param> public void UpdateDataView(bool requery) { // Retrieves the data if ((Session[dsReportSessionName] == null) || (requery)) { if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString()); DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } public void UpdateDataView() { // Retrieves the data if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } #endregion #region .Event DataGridList ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // HANDLERs // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageChanged(Object sender, DataGridPageChangedEventArgs e) { DataGridList.CurrentPageIndex = e.NewPageIndex; DataGridList.SelectedIndex = -1; UpdateDataView(); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="nPageIndex"></param> public void GoToPage(Object sender, int nPageIndex) { DataGridPageChangedEventArgs evPage; evPage = new DataGridPageChangedEventArgs(sender, nPageIndex); PageChanged(sender, evPage); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToFirst(Object sender, ImageClickEventArgs e) { GoToPage(sender, 0); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a previous page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToPrev(Object sender, ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex > 0) { GoToPage(sender, DataGridList.CurrentPageIndex - 1); } else { GoToPage(sender, 0); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a next page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1)) { GoToPage(sender, DataGridList.CurrentPageIndex + 1); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a last page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToLast(Object sender, ImageClickEventArgs e) { GoToPage(sender, DataGridList.PageCount - 1); } /// <summary> /// This function is invoked when you click on a column's header to /// sort by that. It just saves the current sort field name and /// refreshes the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SortByColumn(Object sender, DataGridSortCommandEventArgs e) { String strSortBy = DataGridList.Attributes["SortField"]; String strSortAscending = DataGridList.Attributes["SortAscending"]; // Sets the new sorting field DataGridList.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. DataGridList.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view OnClearSelection(null, null); UpdateDataView(); } /// <summary> /// The function gets invoked when a new item is being created in /// the datagrid. This applies to pager, header, footer, regular /// and alternating items. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageItemCreated(Object sender, DataGridItemEventArgs e) { // Get the newly created item ListItemType itemType = e.Item.ItemType; ////////////////////////////////////////////////////////// // Is it the HEADER? if (itemType == ListItemType.Header) { for (int i = 0; i < DataGridList.Columns.Count; i++) { // draw to reflect sorting if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression) { ////////////////////////////////////////////// // Should be much easier this way: // ------------------------------------------ // TableCell cell = e.Item.Cells[i]; // Label lblSorted = new Label(); // lblSorted.Font = "webdings"; // lblSorted.Text = strOrder; // cell.Controls.Add(lblSorted); // // but it seems it doesn't work <g> ////////////////////////////////////////////// // Add a non-clickable triangle to mean desc or asc. // The </a> ensures that what follows is non-clickable TableCell cell = e.Item.Cells[i]; LinkButton lb = (LinkButton)cell.Controls[0]; //lb.Text += "</a>&nbsp;<span style=font-family:webdings;>" + GetOrderSymbol() + "</span>"; lb.Text += "</a>&nbsp;<img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >"; } } } ////////////////////////////////////////////////////////// // Is it the PAGER? if (itemType == ListItemType.Pager) { // There's just one control in the list... TableCell pager = (TableCell)e.Item.Controls[0]; // Enumerates all the items in the pager... for (int i = 0; i < pager.Controls.Count; i += 2) { // It can be either a Label or a Link button try { Label l = (Label)pager.Controls[i]; l.Text = "Hal " + l.Text; l.CssClass = "CurrentPage"; } catch { LinkButton h = (LinkButton)pager.Controls[i]; h.Text = "[ " + h.Text + " ]"; h.CssClass = "HotLink"; } } } } /// <summary> /// Verifies whether the current sort is ascending or descending and /// returns an appropriate display text (i.e., a webding) /// </summary> /// <returns></returns> private String GetOrderSymbol() { bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no"); //return (bDescending ? " 6" : " 5"); return (bDescending ? "downbr.gif" : "upbr.gif"); } /// <summary> /// When clicked clears the current selection if any /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnClearSelection(Object sender, EventArgs e) { DataGridList.SelectedIndex = -1; } #endregion #region .Event Button /// <summary> /// When clicked, redirect to form add for inserts a new record to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnNewRecord(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("AddTM.aspx?CurrentPage=" + CurrentPage); } /// <summary> /// When clicked, filter data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnSearch(Object sender, System.EventArgs e) { if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; string filter = ""; if (cmbKelompokLayanan.SelectedIndex > 0) { filter += filter != "" ? " AND " : ""; filter += " KelompokLayananId = " + cmbKelompokLayanan.SelectedItem.Value; } dv.RowFilter = filter; BindData(dv); } #endregion #region .Update Link Item Butom /// <summary> /// The function is responsible for get link button form. /// </summary> /// <param name="szId"></param> /// <param name="CurrentPage"></param> /// <returns></returns> public string GetLinkButton(string Id, string Nama, string CurrentPage) { string szResult = ""; if (Session["EditTarif"] != null) { szResult += "<a class=\"toolbar\" href=\"EditTM.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Edit") + "</a>"; } if (Session["DeleteTarif"] != null) { szResult += "<a class=\"toolbar\" href=\"DeleteTM.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Delete") + "</a>"; } return szResult; } #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ActionBlock.cs // // // A target block that executes an action for each message. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading.Tasks.Dataflow.Internal; namespace System.Threading.Tasks.Dataflow { /// <summary>Provides a dataflow block that invokes a provided <see cref="System.Action{T}"/> delegate for every data element received.</summary> /// <typeparam name="TInput">Specifies the type of data operated on by this <see cref="ActionBlock{T}"/>.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(ActionBlock<>.DebugView))] public sealed class ActionBlock<TInput> : ITargetBlock<TInput>, IDebuggerDisplay { /// <summary>The core implementation of this message block when in default mode.</summary> private readonly TargetCore<TInput> _defaultTarget; /// <summary>The core implementation of this message block when in SPSC mode.</summary> private readonly SpscTargetCore<TInput> _spscTarget; /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Action{T}"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Action<TInput> action) : this((Delegate)action, ExecutionDataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Action{T}"/> and <see cref="ExecutionDataflowBlockOptions"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="ActionBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Action<TInput> action, ExecutionDataflowBlockOptions dataflowBlockOptions) : this((Delegate)action, dataflowBlockOptions) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Func{T,Task}"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Func<TInput, Task> action) : this((Delegate)action, ExecutionDataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Func{T,Task}"/> and <see cref="ExecutionDataflowBlockOptions"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="ActionBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Func<TInput, Task> action, ExecutionDataflowBlockOptions dataflowBlockOptions) : this((Delegate)action, dataflowBlockOptions) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified delegate and options.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="ActionBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> private ActionBlock(Delegate action, ExecutionDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (action == null) throw new ArgumentNullException(nameof(action)); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Based on the mode, initialize the target. If the user specifies SingleProducerConstrained, // we'll try to employ an optimized mode under a limited set of circumstances. var syncAction = action as Action<TInput>; if (syncAction != null && dataflowBlockOptions.SingleProducerConstrained && dataflowBlockOptions.MaxDegreeOfParallelism == 1 && !dataflowBlockOptions.CancellationToken.CanBeCanceled && dataflowBlockOptions.BoundedCapacity == DataflowBlockOptions.Unbounded) { // Initialize the SPSC fast target to handle the bulk of the processing. // The SpscTargetCore is only supported when BoundedCapacity, CancellationToken, // and MaxDOP are all their default values. It's also only supported for sync // delegates and not for async delegates. _spscTarget = new SpscTargetCore<TInput>(this, syncAction, dataflowBlockOptions); } else { // Initialize the TargetCore which handles the bulk of the processing. // The default target core can handle all options and delegate flavors. if (syncAction != null) // sync { _defaultTarget = new TargetCore<TInput>(this, messageWithId => ProcessMessage(syncAction, messageWithId), null, dataflowBlockOptions, TargetCoreOptions.RepresentsBlockCompletion); } else // async { var asyncAction = action as Func<TInput, Task>; Debug.Assert(asyncAction != null, "action is of incorrect delegate type"); _defaultTarget = new TargetCore<TInput>(this, messageWithId => ProcessMessageWithTask(asyncAction, messageWithId), null, dataflowBlockOptions, TargetCoreOptions.RepresentsBlockCompletion | TargetCoreOptions.UsesAsyncCompletion); } // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, Completion, state => ((TargetCore<TInput>)state).Complete(exception: null, dropPendingMessages: true), _defaultTarget); } #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif Debug.Assert((_spscTarget != null) ^ (_defaultTarget != null), "One and only one of the two targets must be non-null after construction"); } /// <summary>Processes the message with a user-provided action.</summary> /// <param name="action">The action to use to process the message.</param> /// <param name="messageWithId">The message to be processed.</param> private void ProcessMessage(Action<TInput> action, KeyValuePair<TInput, long> messageWithId) { try { action(messageWithId.Key); } catch (Exception exc) { // If this exception represents cancellation, swallow it rather than shutting down the block. if (!Common.IsCooperativeCancellation(exc)) throw; } finally { // We're done synchronously processing an element, so reduce the bounding count // that was incrementing when this element was enqueued. if (_defaultTarget.IsBounded) _defaultTarget.ChangeBoundingCount(-1); } } /// <summary>Processes the message with a user-provided action that returns a task.</summary> /// <param name="action">The action to use to process the message.</param> /// <param name="messageWithId">The message to be processed.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ProcessMessageWithTask(Func<TInput, Task> action, KeyValuePair<TInput, long> messageWithId) { Debug.Assert(action != null, "action needed for processing"); // Run the action to get the task that represents the operation's completion Task task = null; Exception caughtException = null; try { task = action(messageWithId.Key); } catch (Exception exc) { caughtException = exc; } // If no task is available, we're done. if (task == null) { // If we didn't get a task because an exception occurred, // store it (if the exception was cancellation, just ignore it). if (caughtException != null && !Common.IsCooperativeCancellation(caughtException)) { Common.StoreDataflowMessageValueIntoExceptionData(caughtException, messageWithId.Key); _defaultTarget.Complete(caughtException, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false); } // Signal that we're done this async operation. _defaultTarget.SignalOneAsyncMessageCompleted(boundingCountChange: -1); return; } else if (task.IsCompleted) { AsyncCompleteProcessMessageWithTask(task); } else { // Otherwise, join with the asynchronous operation when it completes. task.ContinueWith((completed, state) => { ((ActionBlock<TInput>)state).AsyncCompleteProcessMessageWithTask(completed); }, this, CancellationToken.None, Common.GetContinuationOptions(TaskContinuationOptions.ExecuteSynchronously), TaskScheduler.Default); } } /// <summary>Completes the processing of an asynchronous message.</summary> /// <param name="completed">The completed task.</param> private void AsyncCompleteProcessMessageWithTask(Task completed) { Debug.Assert(completed != null, "Need completed task for processing"); Debug.Assert(completed.IsCompleted, "The task to be processed must be completed by now."); // If the task faulted, store its errors. We must add the exception before declining // and signaling completion, as the exception is part of the operation, and the completion conditions // depend on this. if (completed.IsFaulted) { _defaultTarget.Complete(completed.Exception, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: true); } // Regardless of faults, note that we're done processing. There are // no outputs to keep track of for action block, so we always decrement // the bounding count here (the callee will handle checking whether // we're actually in a bounded mode). _defaultTarget.SignalOneAsyncMessageCompleted(boundingCountChange: -1); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { if (_defaultTarget != null) { _defaultTarget.Complete(exception: null, dropPendingMessages: false); } else { _spscTarget.Complete(exception: null); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); if (_defaultTarget != null) { _defaultTarget.Complete(exception, dropPendingMessages: true); } else { _spscTarget.Complete(exception); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _defaultTarget != null ? _defaultTarget.Completion : _spscTarget.Completion; } } /// <summary>Posts an item to the <see cref="T:System.Threading.Tasks.Dataflow.ITargetBlock`1"/>.</summary> /// <param name="item">The item being offered to the target.</param> /// <returns>true if the item was accepted by the target block; otherwise, false.</returns> /// <remarks> /// This method will return once the target block has decided to accept or decline the item, /// but unless otherwise dictated by special semantics of the target block, it does not wait /// for the item to actually be processed (for example, <see cref="T:System.Threading.Tasks.Dataflow.ActionBlock`1"/> /// will return from Post as soon as it has stored the posted item into its input queue). From the perspective /// of the block's processing, Post is asynchronous. For target blocks that support postponing offered messages, /// or for blocks that may do more processing in their Post implementation, consider using /// <see cref="T:System.Threading.Tasks.Dataflow.DataflowBlock.SendAsync">SendAsync</see>, /// which will return immediately and will enable the target to postpone the posted message and later consume it /// after SendAsync returns. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Post(TInput item) { // Even though this method is available with the exact same functionality as an extension method // on ITargetBlock, using that extension method goes through an interface call on ITargetBlock, // which for very high-throughput scenarios shows up as noticeable overhead on certain architectures. // We can eliminate that call for direct ActionBlock usage by providing the same method as an instance method. return _defaultTarget != null ? _defaultTarget.OfferMessage(Common.SingleMessageHeader, item, null, false) == DataflowMessageStatus.Accepted : _spscTarget.Post(item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept) { return _defaultTarget != null ? _defaultTarget.OfferMessage(messageHeader, messageValue, source, consumeToAccept) : _spscTarget.OfferMessage(messageHeader, messageValue, source, consumeToAccept); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="InputCount"]/*' /> public int InputCount { get { return _defaultTarget != null ? _defaultTarget.InputCount : _spscTarget.InputCount; } } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger.</summary> private int InputCountForDebugger { get { return _defaultTarget != null ? _defaultTarget.GetDebuggingInformation().InputCount : _spscTarget.InputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _defaultTarget != null ? _defaultTarget.DataflowBlockOptions : _spscTarget.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, InputCount={1}", Common.GetNameForDebugger(this, _defaultTarget != null ? _defaultTarget.DataflowBlockOptions : _spscTarget.DataflowBlockOptions), InputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Call.</summary> private sealed class DebugView { /// <summary>The action block being viewed.</summary> private readonly ActionBlock<TInput> _actionBlock; /// <summary>The action block's default target being viewed.</summary> private readonly TargetCore<TInput>.DebuggingInformation _defaultDebugInfo; /// <summary>The action block's SPSC target being viewed.</summary> private readonly SpscTargetCore<TInput>.DebuggingInformation _spscDebugInfo; /// <summary>Initializes the debug view.</summary> /// <param name="actionBlock">The target being debugged.</param> public DebugView(ActionBlock<TInput> actionBlock) { Debug.Assert(actionBlock != null, "Need a block with which to construct the debug view."); _actionBlock = actionBlock; if (_actionBlock._defaultTarget != null) { _defaultDebugInfo = actionBlock._defaultTarget.GetDebuggingInformation(); } else { _spscDebugInfo = actionBlock._spscTarget.GetDebuggingInformation(); } } /// <summary>Gets the messages waiting to be processed.</summary> public IEnumerable<TInput> InputQueue { get { return _defaultDebugInfo != null ? _defaultDebugInfo.InputQueue : _spscDebugInfo.InputQueue; } } /// <summary>Gets any postponed messages.</summary> public QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages { get { return _defaultDebugInfo != null ? _defaultDebugInfo.PostponedMessages : null; } } /// <summary>Gets the number of outstanding input operations.</summary> public int CurrentDegreeOfParallelism { get { return _defaultDebugInfo != null ? _defaultDebugInfo.CurrentDegreeOfParallelism : _spscDebugInfo.CurrentDegreeOfParallelism; } } /// <summary>Gets the ExecutionDataflowBlockOptions used to configure this block.</summary> public ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _defaultDebugInfo != null ? _defaultDebugInfo.DataflowBlockOptions : _spscDebugInfo.DataflowBlockOptions; } } /// <summary>Gets whether the block is declining further messages.</summary> public bool IsDecliningPermanently { get { return _defaultDebugInfo != null ? _defaultDebugInfo.IsDecliningPermanently : _spscDebugInfo.IsDecliningPermanently; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _defaultDebugInfo != null ? _defaultDebugInfo.IsCompleted : _spscDebugInfo.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_actionBlock); } } } } }
// 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.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; using System.Security.Cryptography.Pkcs.Tests; namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests { public static partial class EdgeCasesTests { public static bool SupportsRc4 { get; } = ContentEncryptionAlgorithmTests.SupportsRc4; [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCase() { // // Pfx's imported into a certificate collection propagate their "delete on Dispose" behavior to its cloned instances: // a subtle difference from Pfx's created using the X509Certificate2 constructor that can lead to premature or // double key deletion. Since EnvelopeCms.Decrypt() has no legitimate reason to clone the extraStore certs, this shouldn't // be a problem, but this test will verify that it isn't. // byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(expectedContent, contentInfo.Content); } } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCaseSki() { byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(new byte[] { 1, 2, 3 }, contentInfo.Content); Assert.Equal<byte>(expectedContent, contentInfo.Content); } } private static X509Certificate2 LoadPfxUsingCollectionImport(this CertLoader certLoader) { byte[] pfxData = certLoader.PfxData; string password = certLoader.Password; X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Import(pfxData, password, X509KeyStorageFlags.DefaultKeySet); Assert.Equal(1, collection.Count); return collection[0]; } [Fact] public static void ZeroLengthContextUntagged_FixedValue() { // This test ensures that we can handle when the enveloped message has no content inside. This test differs // from "ZeroLengthContent_FixedValue" in that it doesn't have a context specific [0] in the EncryptedContentInfo // section of the DER encoding of the message. // EncryptedContentInfo ::= SEQUENCE { // contentType ContentType, // contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, // encryptedContent[0] IMPLICIT EncryptedContent OPTIONAL } // The input was created with ASN1 editor and verified with .NET framework. It's an enveloped message, version 0, // with one Key Transport recipient and holds data encrypted with 3DES. byte[] content = ("3082010206092A864886F70D010703A081F43081F10201003181C83081C5020100302E301A311830160603550403130F" + "5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A864886F70D0101010500" + "04818009C16B674495C2C3D4763189C3274CF7A9142FBEEC8902ABDC9CE29910D541DF910E029A31443DC9A9F3B05F02" + "DA1C38478C400261C734D6789C4197C20143C4312CEAA99ECB1849718326D4FC3B7FBB2D1D23281E31584A63E99F2C17" + "132BCD8EDDB632967125CD0A4BAA1EFA8CE4C855F7C093339211BDF990CEF5CCE6CD74302106092A864886F70D010701" + "301406082A864886F70D03070408779B3DE045826B18").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(content); int expected = PlatformDetection.IsFullFramework ? 6 : 0; // Desktop bug gives 6 Assert.Equal(expected, ecms.ContentInfo.Content.Length); Assert.Equal(Oids.Pkcs7Data, ecms.ContentInfo.ContentType.Value); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop rejects zero length content: corefx#18724")] public static void ZeroLengthContent_RoundTrip() { ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>()); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ValidateZeroLengthContent(encodedMessage); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ZeroLengthContent_FixedValue() { byte[] encodedMessage = ("3082010406092a864886f70d010703a081f63081f30201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818009" + "c16b674495c2c3d4763189c3274cf7a9142fbeec8902abdc9ce29910d541df910e029a31443dc9a9f3b05f02da1c38478c40" + "0261c734d6789c4197c20143c4312ceaa99ecb1849718326d4fc3b7fbb2d1d23281e31584a63e99f2c17132bcd8eddb63296" + "7125cd0a4baa1efa8ce4c855f7c093339211bdf990cef5cce6cd74302306092a864886f70d010701301406082a864886f70d" + "03070408779b3de045826b188000").HexToByteArray(); ValidateZeroLengthContent(encodedMessage); } [ConditionalFact(nameof(SupportsRc4))] [OuterLoop(/* Leaks key on disk if interrupted */)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "RC4 isn't available via CNG, and CNG is the only library available to UWP")] public static void Rc4AndCngWrappersDontMixTest() { // // Combination of RC4 over a CAPI certificate. // // This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG), // the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG. // byte[] content = { 6, 3, 128, 33, 44 }; AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4)); EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4); CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate())); ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // In order to actually use the CAPI version of the key, perphemeral loading must be specified. using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.CloneAsPerphemeralLoader().TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); } private static void ValidateZeroLengthContent(byte[] encodedMessage) { EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); ContentInfo contentInfo = ecms.ContentInfo; byte[] content = contentInfo.Content; int expected = PlatformDetection.IsFullFramework ? 6 : 0; // Desktop bug gives 6 Assert.Equal(expected, content.Length); } } [Fact] public static void ReuseEnvelopeCmsEncodeThenDecode() { // Test ability to encrypt, encode and decode all in one EnvelopedCms instance. ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void ReuseEnvelopeCmsDecodeThenEncode() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void EnvelopedCmsNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null)); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null, new AlgorithmIdentifier(new Oid(Oids.TripleDesCbc)))); } [Fact] public static void EnvelopedCmsNullAlgorithm() { object ignore; ContentInfo contentInfo = new ContentInfo(new byte[3]); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(contentInfo, null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipient() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipient)null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipientCollection)null)); } [Fact] // On the desktop, this throws up a UI for the user to select a recipient. We don't support that. [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void EnvelopedCmsEncryptWithZeroRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<PlatformNotSupportedException>(() => ecms.Encrypt(new CmsRecipientCollection())); } [Fact] public static void EnvelopedCmsNullDecode() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<ArgumentNullException>(() => ecms.Decode(null)); } [Fact] public static void EnvelopedCmsDecryptNullary() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt()); } [Fact] public static void EnvelopedCmsDecryptNullRecipient() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = null; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void EnvelopedCmsDecryptNullExtraStore() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = null; Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(extraStore)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCert() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCertSki() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void AlgorithmIdentifierNullaryCtor() { AlgorithmIdentifier a = new AlgorithmIdentifier(); Assert.Equal(Oids.TripleDesCbc, a.Oid.Value); Assert.Equal(0, a.KeyLength); } [Fact] public static void CmsRecipient1AryCtor() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassUnknown() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(SubjectIdentifierType.Unknown, cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassNullCertificate() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(null)); Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, null)); } [Fact] public static void ContentInfoNullOid() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, new byte[3])); } [Fact] public static void ContentInfoNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null)); Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, null)); } [Fact] public static void ContentInfoGetContentTypeNull() { Assert.Throws<ArgumentNullException>(() => ContentInfo.GetContentType(null)); } [Fact] public static void ContentInfoGetContentTypeUnknown() { byte[] encodedMessage = ("301A06092A864886F70D010700A00D040B48656C6C6F202E4E455421").HexToByteArray(); Assert.ThrowsAny<CryptographicException>(() => ContentInfo.GetContentType(encodedMessage)); } [Fact] public static void CryptographicAttributeObjectOidCtor() { Oid oid = new Oid(Oids.DocumentDescription); CryptographicAttributeObject cao = new CryptographicAttributeObject(oid); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectPassNullValuesToCtor() { Oid oid = new Oid(Oids.DocumentDescription); // This is legal and equivalent to passing a zero-length AsnEncodedDataCollection. CryptographicAttributeObject cao = new CryptographicAttributeObject(oid, null); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectMismatch() { Oid oid = new Oid(Oids.DocumentDescription); Oid wrongOid = new Oid(Oids.DocumentName); AsnEncodedDataCollection col = new AsnEncodedDataCollection(); col.Add(new AsnEncodedData(oid, new byte[3])); object ignore; Assert.Throws<InvalidOperationException>(() => ignore = new CryptographicAttributeObject(wrongOid, col)); } [Fact] public static void EncryptEnvelopedOctetStringWithIncompleteContent() { byte[] content = "04040203".HexToByteArray(); ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content); using (X509Certificate2 certificate = Certificates.RSAKeyTransferCapi1.GetCertificate()) { string certSubjectName = certificate.Subject; AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(Oids.Aes256)); EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg); CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate); Assert.ThrowsAny<CryptographicException>(() => ecms.Encrypt(cmsRecipient)); } } [Fact] public static void EncryptEnvelopedOneByteArray() { byte[] content = "04".HexToByteArray(); ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content); using (X509Certificate2 certificate = Certificates.RSAKeyTransferCapi1.GetCertificate()) { string certSubjectName = certificate.Subject; AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(Oids.Aes256)); EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg); CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate); Assert.ThrowsAny<CryptographicException>(() => ecms.Encrypt(cmsRecipient)); } } } }
// 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.Cloud.Bigtable.V2; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Bigtable.V2.Snippets { /// <summary>Generated snippets</summary> public class GeneratedBigtableClientSnippets { /// <summary>Snippet for ReadRows</summary> public async Task ReadRows() { // Snippet: ReadRows(ReadRowsRequest,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument ReadRowsRequest request = new ReadRowsRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), }; // Make the request, returning a streaming response BigtableClient.ReadRowsStream streamingResponse = bigtableClient.ReadRows(request); // Read streaming responses from server until complete IAsyncEnumerator<ReadRowsResponse> responseStream = streamingResponse.ResponseStream; while (await responseStream.MoveNext()) { ReadRowsResponse response = responseStream.Current; // Do something with streamed response } // The response stream has completed // End snippet } /// <summary>Snippet for SampleRowKeys</summary> public async Task SampleRowKeys() { // Snippet: SampleRowKeys(SampleRowKeysRequest,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument SampleRowKeysRequest request = new SampleRowKeysRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), }; // Make the request, returning a streaming response BigtableClient.SampleRowKeysStream streamingResponse = bigtableClient.SampleRowKeys(request); // Read streaming responses from server until complete IAsyncEnumerator<SampleRowKeysResponse> responseStream = streamingResponse.ResponseStream; while (await responseStream.MoveNext()) { SampleRowKeysResponse response = responseStream.Current; // Do something with streamed response } // The response stream has completed // End snippet } /// <summary>Snippet for MutateRowAsync</summary> public async Task MutateRowAsync() { // Snippet: MutateRowAsync(TableName,ByteString,IEnumerable<Mutation>,CallSettings) // Additional: MutateRowAsync(TableName,ByteString,IEnumerable<Mutation>,CancellationToken) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.CopyFromUtf8(""); IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request MutateRowResponse response = await bigtableClient.MutateRowAsync(tableName, rowKey, mutations); // End snippet } /// <summary>Snippet for MutateRow</summary> public void MutateRow() { // Snippet: MutateRow(TableName,ByteString,IEnumerable<Mutation>,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument(s) TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.CopyFromUtf8(""); IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request MutateRowResponse response = bigtableClient.MutateRow(tableName, rowKey, mutations); // End snippet } /// <summary>Snippet for MutateRowAsync</summary> public async Task MutateRowAsync_RequestObject() { // Snippet: MutateRowAsync(MutateRowRequest,CallSettings) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) MutateRowRequest request = new MutateRowRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), RowKey = ByteString.CopyFromUtf8(""), Mutations = { }, }; // Make the request MutateRowResponse response = await bigtableClient.MutateRowAsync(request); // End snippet } /// <summary>Snippet for MutateRow</summary> public void MutateRow_RequestObject() { // Snippet: MutateRow(MutateRowRequest,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument(s) MutateRowRequest request = new MutateRowRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), RowKey = ByteString.CopyFromUtf8(""), Mutations = { }, }; // Make the request MutateRowResponse response = bigtableClient.MutateRow(request); // End snippet } /// <summary>Snippet for MutateRows</summary> public async Task MutateRows() { // Snippet: MutateRows(MutateRowsRequest,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument MutateRowsRequest request = new MutateRowsRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), Entries = { }, }; // Make the request, returning a streaming response BigtableClient.MutateRowsStream streamingResponse = bigtableClient.MutateRows(request); // Read streaming responses from server until complete IAsyncEnumerator<MutateRowsResponse> responseStream = streamingResponse.ResponseStream; while (await responseStream.MoveNext()) { MutateRowsResponse response = responseStream.Current; // Do something with streamed response } // The response stream has completed // End snippet } /// <summary>Snippet for CheckAndMutateRowAsync</summary> public async Task CheckAndMutateRowAsync() { // Snippet: CheckAndMutateRowAsync(TableName,ByteString,RowFilter,IEnumerable<Mutation>,IEnumerable<Mutation>,CallSettings) // Additional: CheckAndMutateRowAsync(TableName,ByteString,RowFilter,IEnumerable<Mutation>,IEnumerable<Mutation>,CancellationToken) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.CopyFromUtf8(""); RowFilter predicateFilter = new RowFilter(); IEnumerable<Mutation> trueMutations = new List<Mutation>(); IEnumerable<Mutation> falseMutations = new List<Mutation>(); // Make the request CheckAndMutateRowResponse response = await bigtableClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations); // End snippet } /// <summary>Snippet for CheckAndMutateRow</summary> public void CheckAndMutateRow() { // Snippet: CheckAndMutateRow(TableName,ByteString,RowFilter,IEnumerable<Mutation>,IEnumerable<Mutation>,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument(s) TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.CopyFromUtf8(""); RowFilter predicateFilter = new RowFilter(); IEnumerable<Mutation> trueMutations = new List<Mutation>(); IEnumerable<Mutation> falseMutations = new List<Mutation>(); // Make the request CheckAndMutateRowResponse response = bigtableClient.CheckAndMutateRow(tableName, rowKey, predicateFilter, trueMutations, falseMutations); // End snippet } /// <summary>Snippet for CheckAndMutateRowAsync</summary> public async Task CheckAndMutateRowAsync_RequestObject() { // Snippet: CheckAndMutateRowAsync(CheckAndMutateRowRequest,CallSettings) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) CheckAndMutateRowRequest request = new CheckAndMutateRowRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), RowKey = ByteString.CopyFromUtf8(""), }; // Make the request CheckAndMutateRowResponse response = await bigtableClient.CheckAndMutateRowAsync(request); // End snippet } /// <summary>Snippet for CheckAndMutateRow</summary> public void CheckAndMutateRow_RequestObject() { // Snippet: CheckAndMutateRow(CheckAndMutateRowRequest,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument(s) CheckAndMutateRowRequest request = new CheckAndMutateRowRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), RowKey = ByteString.CopyFromUtf8(""), }; // Make the request CheckAndMutateRowResponse response = bigtableClient.CheckAndMutateRow(request); // End snippet } /// <summary>Snippet for ReadModifyWriteRowAsync</summary> public async Task ReadModifyWriteRowAsync() { // Snippet: ReadModifyWriteRowAsync(TableName,ByteString,IEnumerable<ReadModifyWriteRule>,CallSettings) // Additional: ReadModifyWriteRowAsync(TableName,ByteString,IEnumerable<ReadModifyWriteRule>,CancellationToken) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.CopyFromUtf8(""); IEnumerable<ReadModifyWriteRule> rules = new List<ReadModifyWriteRule>(); // Make the request ReadModifyWriteRowResponse response = await bigtableClient.ReadModifyWriteRowAsync(tableName, rowKey, rules); // End snippet } /// <summary>Snippet for ReadModifyWriteRow</summary> public void ReadModifyWriteRow() { // Snippet: ReadModifyWriteRow(TableName,ByteString,IEnumerable<ReadModifyWriteRule>,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument(s) TableName tableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.CopyFromUtf8(""); IEnumerable<ReadModifyWriteRule> rules = new List<ReadModifyWriteRule>(); // Make the request ReadModifyWriteRowResponse response = bigtableClient.ReadModifyWriteRow(tableName, rowKey, rules); // End snippet } /// <summary>Snippet for ReadModifyWriteRowAsync</summary> public async Task ReadModifyWriteRowAsync_RequestObject() { // Snippet: ReadModifyWriteRowAsync(ReadModifyWriteRowRequest,CallSettings) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) ReadModifyWriteRowRequest request = new ReadModifyWriteRowRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), RowKey = ByteString.CopyFromUtf8(""), Rules = { }, }; // Make the request ReadModifyWriteRowResponse response = await bigtableClient.ReadModifyWriteRowAsync(request); // End snippet } /// <summary>Snippet for ReadModifyWriteRow</summary> public void ReadModifyWriteRow_RequestObject() { // Snippet: ReadModifyWriteRow(ReadModifyWriteRowRequest,CallSettings) // Create client BigtableClient bigtableClient = BigtableClient.Create(); // Initialize request argument(s) ReadModifyWriteRowRequest request = new ReadModifyWriteRowRequest { TableNameAsTableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"), RowKey = ByteString.CopyFromUtf8(""), Rules = { }, }; // Make the request ReadModifyWriteRowResponse response = bigtableClient.ReadModifyWriteRow(request); // End snippet } } }
#region Apache Notice /***************************************************************************** * $Revision: 575902 $ * $LastChangedDate: 2007-09-15 12:40:19 +0200 (sam., 15 sept. 2007) $ * $LastChangedBy: gbayon $ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; using System.Collections; using System.Data; using System.Xml.Serialization; using IBatisNet.Common.Exceptions; using IBatisNet.Common.Utilities; using IBatisNet.Common.Utilities.Objects; using IBatisNet.Common.Utilities.Objects.Members; using IBatisNet.DataMapper.Scope; using IBatisNet.DataMapper.TypeHandlers; namespace IBatisNet.DataMapper.Configuration.ParameterMapping { /// <summary> /// ParameterProperty. /// </summary> [Serializable] [XmlRoot("parameter", Namespace = "http://ibatis.apache.org/mapping")] public class ParameterProperty { #region Fields [NonSerialized] private string _nullValue = null;//string.Empty;//null; [NonSerialized] private string _propertyName = string.Empty; [NonSerialized] private ParameterDirection _direction = ParameterDirection.Input; [NonSerialized] private string _directionAttribute = string.Empty; [NonSerialized] private string _dbType = null; [NonSerialized] private int _size = -1; [NonSerialized] private byte _scale = 0; [NonSerialized] private byte _precision = 0; [NonSerialized] private string _columnName = string.Empty; // used only for store procedure [NonSerialized] private ITypeHandler _typeHandler = null; [NonSerialized] private string _clrType = string.Empty; [NonSerialized] private string _callBackName = string.Empty; [NonSerialized] private IGetAccessor _getAccessor = null; [NonSerialized] private bool _isComplexMemberName = false; #endregion #region Properties /// <summary> /// Indicate if we have a complex member name as [avouriteLineItem.Id] /// </summary> public bool IsComplexMemberName { get { return _isComplexMemberName; } } /// <summary> /// Specify the custom type handlers to used. /// </summary> /// <remarks>Will be an alias to a class wchic implement ITypeHandlerCallback</remarks> [XmlAttribute("typeHandler")] public string CallBackName { get { return _callBackName; } set { _callBackName = value; } } /// <summary> /// Specify the CLR type of the parameter. /// </summary> /// <remarks> /// The type attribute is used to explicitly specify the property type to be read. /// Normally this can be derived from a property through reflection, but certain mappings such as /// HashTable cannot provide the type to the framework. /// </remarks> [XmlAttribute("type")] public string CLRType { get { return _clrType; } set { _clrType = value; } } /// <summary> /// The typeHandler used to work with the parameter. /// </summary> [XmlIgnore] public ITypeHandler TypeHandler { get { return _typeHandler; } set { _typeHandler = value; } } /// <summary> /// Column Name for output parameter /// in store proccedure. /// </summary> [XmlAttribute("column")] public string ColumnName { get { return _columnName; } set { _columnName = value; } } /// <summary> /// Column size. /// </summary> [XmlAttribute("size")] public int Size { get { return _size; } set { _size = value; } } /// <summary> /// Column Scale. /// </summary> [XmlAttribute("scale")] public byte Scale { get { return _scale; } set { _scale = value; } } /// <summary> /// Column Precision. /// </summary> [XmlAttribute("precision")] public byte Precision { get { return _precision; } set { _precision = value; } } /// <summary> /// Give an entry in the 'DbType' enumeration /// </summary> /// <example > /// For Sql Server, give an entry of SqlDbType : Bit, Decimal, Money... /// <br/> /// For Oracle, give an OracleType Enumeration : Byte, Int16, Number... /// </example> [XmlAttribute("dbType")] public string DbType { get { return _dbType; } set { _dbType = value; } } /// <summary> /// The direction attribute of the XML parameter. /// </summary> /// <example> Input, Output, InputOutput</example> [XmlAttribute("direction")] public string DirectionAttribute { get { return _directionAttribute; } set { _directionAttribute = value; } } /// <summary> /// Indicate the direction of the parameter. /// </summary> /// <example> Input, Output, InputOutput</example> [XmlIgnore] public ParameterDirection Direction { get { return _direction; } set { _direction = value; _directionAttribute = _direction.ToString(); } } /// <summary> /// Property name used to identify the property amongst the others. /// </summary> /// <example>EmailAddress</example> [XmlAttribute("property")] public string PropertyName { get { return _propertyName; } set { if ((value == null) || (value.Length < 1)) throw new ArgumentNullException("The property attribute is mandatory in a paremeter property."); _propertyName = value; if (_propertyName.IndexOf('.') < 0) { _isComplexMemberName = false; } else // complex member name FavouriteLineItem.Id { _isComplexMemberName = true; } } } /// <summary> /// Tell if a nullValue is defined._nullValue!=null /// </summary> [XmlIgnore] public bool HasNullValue { get { return (_nullValue != null); } } /// <summary> /// Null value replacement. /// </summary> /// <example>"[email protected]"</example> [XmlAttribute("nullValue")] public string NullValue { get { return _nullValue; } set { _nullValue = value; } } /// <summary> /// Defines a field/property get accessor /// </summary> [XmlIgnore] public IGetAccessor GetAccessor { get { return _getAccessor; } } #endregion #region Methods /// <summary> /// Initializes the parameter property /// </summary> /// <param name="scope">The scope.</param> /// <param name="parameterClass">The parameter class.</param> public void Initialize(IScope scope, Type parameterClass) { if (_directionAttribute.Length > 0) { _direction = (ParameterDirection)Enum.Parse(typeof(ParameterDirection), _directionAttribute, true); } if (!typeof(IDictionary).IsAssignableFrom(parameterClass) // Hashtable parameter map && parameterClass != null // value property && !scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(parameterClass)) // value property { if (!_isComplexMemberName) { IGetAccessorFactory getAccessorFactory = scope.DataExchangeFactory.AccessorFactory.GetAccessorFactory; _getAccessor = getAccessorFactory.CreateGetAccessor(parameterClass, _propertyName); } else // complex member name FavouriteLineItem.Id { string memberName = _propertyName.Substring(_propertyName.LastIndexOf('.') + 1); string parentName = _propertyName.Substring(0, _propertyName.LastIndexOf('.')); Type parentType = ObjectProbe.GetMemberTypeForGetter(parameterClass, parentName); IGetAccessorFactory getAccessorFactory = scope.DataExchangeFactory.AccessorFactory.GetAccessorFactory; _getAccessor = getAccessorFactory.CreateGetAccessor(parentType, memberName); } } scope.ErrorContext.MoreInfo = "Check the parameter mapping typeHandler attribute '" + this.CallBackName + "' (must be a ITypeHandlerCallback implementation)."; if (this.CallBackName.Length > 0) { try { Type type = scope.DataExchangeFactory.TypeHandlerFactory.GetType(this.CallBackName); ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback)Activator.CreateInstance(type); _typeHandler = new CustomTypeHandler(typeHandlerCallback); } catch (Exception e) { throw new ConfigurationException("Error occurred during custom type handler configuration. Cause: " + e.Message, e); } } else { if (this.CLRType.Length == 0) // Unknown { if (_getAccessor != null && scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(_getAccessor.MemberType)) { // Primitive _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(_getAccessor.MemberType, _dbType); } else { _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler(); } } else // If we specify a CLR type, use it { Type type = TypeUtils.ResolveType(this.CLRType); if (scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(type)) { // Primitive _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, _dbType); } else { // .NET object type = ObjectProbe.GetMemberTypeForGetter(type, this.PropertyName); _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, _dbType); } } } } /// <summary> /// Determines whether the specified <see cref="System.Object"></see> is equal to the current <see cref="System.Object"></see>. /// </summary> /// <param name="obj">The <see cref="System.Object"></see> to compare with the current <see cref="System.Object"></see>.</param> /// <returns> /// true if the specified <see cref="System.Object"></see> is equal to the current <see cref="System.Object"></see>; otherwise, false. /// </returns> public override bool Equals(object obj) { //Check for null and compare run-time types. if (obj == null || GetType() != obj.GetType()) return false; ParameterProperty p = (ParameterProperty)obj; return (this.PropertyName == p.PropertyName); } /// <summary> /// Serves as a hash function for a particular type. <see cref="System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table. /// </summary> /// <returns> /// A hash code for the current <see cref="System.Object"></see>. /// </returns> public override int GetHashCode() { return _propertyName.GetHashCode(); } #endregion #region ICloneable Members /// <summary> /// Clones this instance. /// </summary> /// <returns>An <see cref="ParameterProperty"/></returns> public ParameterProperty Clone() { ParameterProperty property = new ParameterProperty(); property.CallBackName = this.CallBackName; property.CLRType = this.CLRType; property.ColumnName = this.ColumnName; property.DbType = this.DbType; property.DirectionAttribute = this.DirectionAttribute; property.NullValue = this.NullValue; property.PropertyName = this.PropertyName; property.Precision = this.Precision; property.Scale = this.Scale; property.Size = this.Size; return property; } #endregion } }
#region Using directives using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Workflow.ComponentModel.Compiler; using System.Runtime.CompilerServices; using System.Security.Permissions; #endregion namespace System.Workflow.ComponentModel { // [Serializable] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class DependencyProperty : ISerializable { private static IDictionary<int, DependencyProperty> dependencyProperties = new Dictionary<int, DependencyProperty>(); internal enum PropertyValidity { Uninitialize, Reexecute, Always } class KnownDependencyProperty { internal DependencyProperty dependencyProperty; //indicates whether this property, survives beyond Uninitialize. internal PropertyValidity propertyValidity; internal KnownDependencyProperty(DependencyProperty dependencyProperty, PropertyValidity propertyValidity) { this.dependencyProperty = dependencyProperty; this.propertyValidity = propertyValidity; } } private static KnownDependencyProperty[] knownProperties = new KnownDependencyProperty[256]; private bool isRegistered = false; private string name = String.Empty; private System.Type propertyType = null; private System.Type ownerType = null; private System.Type validatorType = null; private PropertyMetadata defaultMetadata = null; private byte knownIndex = (byte)0; [NonSerialized] private bool isEvent = false; public static DependencyProperty Register(string name, System.Type propertyType, System.Type ownerType) { return ValidateAndRegister(name, propertyType, ownerType, null, null, true); } public static DependencyProperty Register(string name, System.Type propertyType, System.Type ownerType, PropertyMetadata defaultMetadata) { return ValidateAndRegister(name, propertyType, ownerType, defaultMetadata, null, true); } public static DependencyProperty RegisterAttached(string name, System.Type propertyType, System.Type ownerType) { return ValidateAndRegister(name, propertyType, ownerType, null, null, false); } public static DependencyProperty RegisterAttached(string name, System.Type propertyType, System.Type ownerType, PropertyMetadata defaultMetadata) { return ValidateAndRegister(name, propertyType, ownerType, defaultMetadata, null, false); } internal static void RegisterAsKnown(DependencyProperty dependencyProperty, byte byteVal, PropertyValidity propertyValidity) { if (dependencyProperty == null) throw new ArgumentNullException("dependencyProperty"); if (knownProperties[byteVal] != null) { throw new InvalidOperationException(SR.GetString(SR.Error_AlreadyRegisteredAs, knownProperties[byteVal].dependencyProperty.ToString())); } dependencyProperty.KnownIndex = byteVal; knownProperties[byteVal] = new KnownDependencyProperty(dependencyProperty, propertyValidity); } internal static DependencyProperty FromKnown(Byte byteVal) { if (knownProperties[byteVal] == null) { throw new InvalidOperationException(SR.GetString(SR.Error_NotRegisteredAs, knownProperties[byteVal].dependencyProperty.ToString())); } return knownProperties[byteVal].dependencyProperty; } //TBD: Dharma - Get rid of this overload public static DependencyProperty RegisterAttached(string name, System.Type propertyType, System.Type ownerType, PropertyMetadata defaultMetadata, System.Type validatorType) { if (validatorType == null) throw new ArgumentNullException("validatorType"); else if (!typeof(Validator).IsAssignableFrom(validatorType)) throw new ArgumentException(SR.GetString(SR.Error_ValidatorTypeIsInvalid), "validatorType"); return ValidateAndRegister(name, propertyType, ownerType, defaultMetadata, validatorType, false); } public static DependencyProperty FromName(string propertyName, Type ownerType) { if (propertyName == null) throw new ArgumentNullException("propertyName"); if (ownerType == null) throw new ArgumentNullException("ownerType"); DependencyProperty dp = null; while ((dp == null) && (ownerType != null)) { // Ensure static constructor of type has run RuntimeHelpers.RunClassConstructor(ownerType.TypeHandle); // Locate property int hashCode = propertyName.GetHashCode() ^ ownerType.GetHashCode(); lock (((ICollection)DependencyProperty.dependencyProperties).SyncRoot) { if (DependencyProperty.dependencyProperties.ContainsKey(hashCode)) dp = DependencyProperty.dependencyProperties[hashCode]; } ownerType = ownerType.BaseType; } return dp; } public static IList<DependencyProperty> FromType(Type ownerType) { if (ownerType == null) throw new ArgumentNullException("ownerType"); // Ensure static constructor of type has run RuntimeHelpers.RunClassConstructor(ownerType.TypeHandle); List<DependencyProperty> filteredProperties = new List<DependencyProperty>(); lock (((ICollection)DependencyProperty.dependencyProperties).SyncRoot) { foreach (DependencyProperty dependencyProperty in DependencyProperty.dependencyProperties.Values) { if (TypeProvider.IsSubclassOf(ownerType, dependencyProperty.ownerType) || ownerType == dependencyProperty.ownerType) filteredProperties.Add(dependencyProperty); } } return filteredProperties.AsReadOnly(); } private static DependencyProperty ValidateAndRegister(string name, System.Type propertyType, System.Type ownerType, PropertyMetadata defaultMetadata, System.Type validatorType, bool isRegistered) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(SR.GetString(SR.Error_EmptyArgument), "name"); if (propertyType == null) throw new ArgumentNullException("propertyType"); if (ownerType == null) throw new ArgumentNullException("ownerType"); FieldInfo fieldInfo = null; bool isEvent = (typeof(System.Delegate).IsAssignableFrom(propertyType) && (defaultMetadata == null || (defaultMetadata.Options & DependencyPropertyOptions.DelegateProperty) == 0)); // WinOE Bug 13807: events can not be meta properties. if (isEvent && defaultMetadata != null && defaultMetadata.IsMetaProperty) throw new ArgumentException(SR.GetString(SR.Error_DPAddHandlerMetaProperty), "defaultMetadata"); //Field must exists if (isEvent) fieldInfo = ownerType.GetField(name + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.GetProperty); else fieldInfo = ownerType.GetField(name + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.GetProperty); if (fieldInfo == null) { string error = SR.GetString((isEvent) ? SR.Error_DynamicEventNotSupported : SR.Error_DynamicPropertyNotSupported, new object[] { ownerType.FullName, name }); throw new ArgumentException(error, "ownerType"); } PropertyMetadata metadata = null; object defaultValue = null; // Establish default metadata for all types, if none is provided if (defaultMetadata == null) { defaultValue = GetDefaultValue(name, propertyType, ownerType); metadata = new PropertyMetadata(defaultValue); } else { metadata = defaultMetadata; if (metadata.DefaultValue == null) metadata.DefaultValue = GetDefaultValue(name, propertyType, ownerType); } DependencyProperty dependencyProperty = new DependencyProperty(name, propertyType, ownerType, metadata, validatorType, isRegistered); lock (((ICollection)DependencyProperty.dependencyProperties).SyncRoot) { if (DependencyProperty.dependencyProperties.ContainsKey(dependencyProperty.GetHashCode())) throw new InvalidOperationException(SR.GetString(SR.Error_DPAlreadyExist, new object[] { name, ownerType.FullName })); DependencyProperty.dependencyProperties.Add(dependencyProperty.GetHashCode(), dependencyProperty); } return dependencyProperty; } private static object GetDefaultValue(string name, System.Type propertyType, System.Type ownerType) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(SR.GetString(SR.Error_EmptyArgument), "name"); if (propertyType == null) throw new ArgumentNullException("propertyType"); if (ownerType == null) throw new ArgumentNullException("ownerType"); object defaultValue = null; if (propertyType.IsValueType) { try { if (propertyType.IsEnum) { Array values = Enum.GetValues(propertyType); if (values.Length > 0) defaultValue = values.GetValue(0); else defaultValue = Activator.CreateInstance(propertyType); } else defaultValue = Activator.CreateInstance(propertyType); } catch { } } return defaultValue; } private DependencyProperty(string name, System.Type propertyType, System.Type ownerType, PropertyMetadata defaultMetadata, System.Type validatorType, bool isRegistered) { this.name = name; this.propertyType = propertyType; this.ownerType = ownerType; this.validatorType = validatorType; this.isRegistered = isRegistered; this.defaultMetadata = defaultMetadata; this.defaultMetadata.Seal(this, propertyType); this.isEvent = (typeof(System.Delegate).IsAssignableFrom(this.propertyType) && (this.defaultMetadata == null || (this.defaultMetadata.Options & DependencyPropertyOptions.DelegateProperty) == 0)); } public bool IsEvent { get { return this.isEvent; } } public bool IsAttached { get { return !this.isRegistered; } } public string Name { get { return this.name; } } public System.Type PropertyType { get { return this.propertyType; } } public System.Type OwnerType { get { return this.ownerType; } } public PropertyMetadata DefaultMetadata { get { return this.defaultMetadata; } } public System.Type ValidatorType { get { return this.validatorType; } } internal byte KnownIndex { get { return this.knownIndex; } set { this.knownIndex = value; } } internal bool IsKnown { get { return (this.knownIndex != 0); } } internal PropertyValidity Validity { get { return IsKnown ? knownProperties[this.knownIndex].propertyValidity : PropertyValidity.Always; } } public override string ToString() { return this.name; } public override int GetHashCode() { // Debug.Assert(this.name != null && this.ownerType != null); return (this.name.GetHashCode() ^ this.ownerType.GetHashCode()); } #region ISerializable Members void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("type", this.ownerType); info.AddValue("name", this.name); info.SetType(typeof(DependencyPropertyReference)); } #endregion [Serializable] private sealed class DependencyPropertyReference : IObjectReference { private Type type = null; private string name = null; public Object GetRealObject(StreamingContext context) { return DependencyProperty.FromName(this.name, this.type); } } } }
// <copyright file=Ray.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:58 PM</date> using HciLab.Utilities.Mathematics.Core; using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace HciLab.Utilities.Mathematics.Geometry3D { /// <summary> /// Represents a ray in 3D space. /// </summary> /// <remarks> /// A ray is R(t) = Origin + t * Direction where t>=0. The Direction isnt necessarily of unit length. /// </remarks> [Serializable] [TypeConverter(typeof(RayConverter))] public class Ray : ICloneable, ISerializable { #region Private Fields private Vector3 _origin; private Vector3 _direction; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Ray"/> class using given origin and direction vectors. /// </summary> /// <param name="origin">Ray's origin point.</param> /// <param name="direction">Ray's direction vector.</param> private Ray(Vector3 origin, Vector3 direction) { _origin = origin; _direction = direction; } /// <summary> /// Initializes a new instance of the <see cref="Ray"/> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> private Ray(SerializationInfo info, StreamingContext context) { _origin = (Vector3)info.GetValue("Origin", typeof(Vector3)); _direction = (Vector3)info.GetValue("Direction", typeof(Vector3)); } #endregion #region Public Properties /// <summary> /// Gets or sets the ray's origin. /// </summary> public Vector3 Origin { get { return _origin; } set { _origin = value;} } /// <summary> /// Gets or sets the ray's direction vector. /// </summary> public Vector3 Direction { get { return _direction; } set { _direction = value;} } #endregion #region ICloneable Members /// <summary> /// Creates an exact copy of this <see cref="Ray"/> object. /// </summary> /// <returns>The <see cref="Ray"/> object this method creates, cast as an object.</returns> object ICloneable.Clone() { return Ray.CreateUsingRay(this); } /// <summary> /// Creates an exact copy of this <see cref="Ray"/> object. /// </summary> /// <returns>The <see cref="Ray"/> object this method creates.</returns> public Ray Clone() { return Ray.CreateUsingRay(this); } #endregion #region ISerializable Members /// <summary> /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param> //[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Origin", _origin, typeof(Vector3)); info.AddValue("Direction", _direction, typeof(Vector3)); } #endregion #region Public Static Parse Methods /// <summary> /// Converts the specified string to its <see cref="Ray"/> equivalent. /// </summary> /// <param name="s">A string representation of a <see cref="Ray"/></param> /// <returns>A <see cref="Ray"/> that represents the vector specified by the <paramref name="s"/> parameter.</returns> public static Ray Parse(string s) { Regex r = new Regex(@"Ray\(Origin=(?<origin>\([^\)]*\)), Direction=(?<direction>\([^\)]*\))\)", RegexOptions.None); Match m = r.Match(s); if (m.Success) { return new Ray( Vector3.Parse(m.Result("${origin}")), Vector3.Parse(m.Result("${direction}")) ); } else { throw new ParseException("Unsuccessful Match."); } } #endregion #region Public Methods /// <summary> /// Gets a point on the ray. /// </summary> /// <param name="t"></param> /// <returns></returns> public Vector3 GetPointOnRay(float t) { return (Origin + Direction * t); } #endregion #region Overrides /// <summary> /// Get the hashcode for this vector instance. /// </summary> /// <returns>Returns the hash code for this vector instance.</returns> public override int GetHashCode() { return _origin.GetHashCode() ^ _direction.GetHashCode(); } /// <summary> /// Returns a value indicating whether this instance is equal to /// the specified object. /// </summary> /// <param name="obj">An object to compare to this instance.</param> /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="Vector3"/> and has the same values as this instance; otherwise, <see langword="false"/>.</returns> public override bool Equals(object obj) { if(obj is Ray) { Ray r = (Ray)obj; return (_origin == r.Origin) && (_direction == r.Direction); } return false; } /// <summary> /// Returns a string representation of this object. /// </summary> /// <returns>A string representation of this object.</returns> public override string ToString() { return string.Format("Ray(Origin={0}, Direction={1})", _origin, _direction); } #endregion #region Comparison Operators /// <summary> /// Tests whether two specified rays are equal. /// </summary> /// <param name="a">The first of two rays to compare.</param> /// <param name="b">The second of two rays to compare.</param> /// <returns><see langword="true"/> if the two rays are equal; otherwise, <see langword="false"/>.</returns> public static bool operator==(Ray a, Ray b) { return ValueType.Equals(a,b); } /// <summary> /// Tests whether two specified rays are not equal. /// </summary> /// <param name="a">The first of two rays to compare.</param> /// <param name="b">The second of two rays to compare.</param> /// <returns><see langword="true"/> if the two rays are not equal; otherwise, <see langword="false"/>.</returns> public static bool operator!=(Ray a, Ray b) { return !ValueType.Equals(a,b); } #endregion public Vector3[] GetTowPointsOnRay() { return new Vector3[] { this._origin, this._direction + this._origin }; } public double[,] GetDoubleMartixWithPointsOnRay() { Vector3[] dV = this.GetTowPointsOnRay(); return new double[2, 3] { { dV[0].X, dV[0].Y, dV[0].Z }, { dV[1].X, dV[1].Y, dV[1].Z } }; } public static Ray CreateUsingTowPoints(Vector3 p1, Vector3 p2) { return new Ray(p1, p2 - p1); } public static Ray CreateUsingOrginAndDirection(Vector3 origin, Vector3 direction) { return new Ray(origin, direction); } /// <summary> /// Initializes a new instance of the <see cref="Ray"/> class using given ray. /// </summary> /// <param name="ray">A <see cref="Ray"/> instance to assign values from.</param> public static Ray CreateUsingRay(Ray ray) { return new Ray(ray.Origin, ray.Direction); } } #region RayConverter class /// <summary> /// Converts a <see cref="Ray"/> to and from string representation. /// </summary> public class RayConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom (context, sourceType); } /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; return base.CanConvertTo (context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">A <see cref="System.Globalization.CultureInfo"/> object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <param name="destinationType">The Type to convert the <paramref name="value"/> parameter to.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if ((destinationType == typeof(string)) && (value is Ray)) { Ray r = (Ray)value; return r.ToString(); } return base.ConvertTo (context, culture, value, destinationType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to use as the current culture. </param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> /// <exception cref="ParseException">Failed parsing from string.</exception> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value.GetType() == typeof(string)) { return Ray.Parse((string)value); } return base.ConvertFrom (context, culture, value); } } #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.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public abstract class Accept<T> : SocketTestHelperBase<T> where T : SocketHelperBase, new() { [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Loopbacks))] public async Task Accept_Success(IPAddress listenAt) { using (Socket listen = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { int port = listen.BindToAnonymousPort(listenAt); listen.Listen(1); Task<Socket> acceptTask = AcceptAsync(listen); Assert.False(acceptTask.IsCompleted); using (Socket client = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, new IPEndPoint(listenAt, port)); Socket accept = await acceptTask; Assert.NotNull(accept); Assert.True(accept.Connected); Assert.Equal(client.LocalEndPoint, accept.RemoteEndPoint); Assert.Equal(accept.LocalEndPoint, client.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task Accept_ConcurrentAcceptsBeforeConnects_Success(int numberAccepts) { // The SyncForceNonBlocking implementation currently toggles the listener's Blocking setting // back and force on every Accept, which causes pending sync Accepts to return EWOULDBLOCK. // For now, just skip the test for SyncForceNonBlocking. // TODO: Issue #22885 if (typeof(T) == typeof(SocketHelperSyncForceNonBlocking)) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(numberAccepts); var clients = new Socket[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); servers[i] = AcceptAsync(listener); } foreach (Socket client in clients) { await ConnectAsync(client, listener.LocalEndPoint); } await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task Accept_ConcurrentAcceptsAfterConnects_Success(int numberAccepts) { // The SyncForceNonBlocking implementation currently toggles the listener's Blocking setting // back and force on every Accept, which causes pending sync Accepts to return EWOULDBLOCK. // For now, just skip the test for SyncForceNonBlocking. // TODO: Issue #22885 if (typeof(T) == typeof(SocketHelperSyncForceNonBlocking)) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(numberAccepts); var clients = new Socket[numberAccepts]; var clientConnects = new Task[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientConnects[i] = ConnectAsync(clients[i], listener.LocalEndPoint); } for (int i = 0; i < numberAccepts; i++) { servers[i] = AcceptAsync(listener); } await Task.WhenAll(clientConnects); Assert.All(clientConnects, c => Assert.Equal(TaskStatus.RanToCompletion, c.Status)); await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public async Task Accept_WithTargetSocket_Success() { if (!SupportsAcceptIntoExistingSocket) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); } } [ActiveIssue(17209, TestPlatforms.AnyUnix)] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public async Task Accept_WithTargetSocket_ReuseAfterDisconnect_Success(bool reuseSocket) { if (!SupportsAcceptIntoExistingSocket) return; // APM mode fails currently. Issue: #22764 if (typeof(T) == typeof(SocketHelperApm)) return; using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); } server.Disconnect(reuseSocket); Assert.False(server.Connected); if (reuseSocket) { using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); } } else { SocketException se = await Assert.ThrowsAsync<SocketException>(() => AcceptAsync(listener, server)); Assert.Equal(SocketError.InvalidArgument, se.SocketErrorCode); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public void Accept_WithAlreadyBoundTargetSocket_Fails() { if (!SupportsAcceptIntoExistingSocket) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); server.BindToAnonymousPort(IPAddress.Loopback); Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); }); } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public async Task Accept_WithInUseTargetSocket_Fails() { if (!SupportsAcceptIntoExistingSocket) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); }); } } } public sealed class AcceptSync : Accept<SocketHelperArraySync> { } public sealed class AcceptSyncForceNonBlocking : Accept<SocketHelperSyncForceNonBlocking> { } public sealed class AcceptApm : Accept<SocketHelperApm> { } public sealed class AcceptTask : Accept<SocketHelperTask> { } public sealed class AcceptEap : Accept<SocketHelperEap> { } }
using SharpGL.Enumerations; using SharpGL.OpenGLAttributes; using SharpGL.SceneGraph.Core; using System.ComponentModel; namespace SharpGL.SceneGraph.Effects { /// <summary> /// The OpenGLAttributes are an effect that can set /// any OpenGL attributes. /// </summary> public class OpenGLAttributesEffect : Effect { /// <summary> /// Initializes a new instance of the <see cref="OpenGLAttributesEffect"/> class. /// </summary> public OpenGLAttributesEffect() { Name = "OpenGL Attributes"; } /// <summary> /// Pushes the effect onto the specified parent element. /// </summary> /// <param name="gl">The OpenGL instance.</param> /// <param name="parentElement">The parent element.</param> public override void Push(OpenGL gl, SceneElement parentElement) { // Create a combined mask. AttributeMask attributeFlags = AttributeMask.None; // accum buffer attribute already added to CSharpGL. attributeFlags |= accumBufferAttributes.AreAnyAttributesSet() ? accumBufferAttributes.AttributeFlags : AttributeMask.None; // accum buffer attribute already added to CSharpGL except one. attributeFlags |= colorBufferAttributes.AreAnyAttributesSet() ? colorBufferAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= currentAttributes.AreAnyAttributesSet() ? currentAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= depthBufferAttributes.AreAnyAttributesSet() ? depthBufferAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= enableAttributes.AreAnyAttributesSet() ? enableAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= fogAttributes.AreAnyAttributesSet() ? fogAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= lightingAttributes.AreAnyAttributesSet() ? lightingAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= lineAttributes.AreAnyAttributesSet() ? lineAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= pointAttributes.AreAnyAttributesSet() ? pointAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= polygonAttributes.AreAnyAttributesSet() ? polygonAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= evalAttributes.AreAnyAttributesSet() ? evalAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= hintAttributes.AreAnyAttributesSet() ? hintAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= listAttributes.AreAnyAttributesSet() ? listAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= pixelModeAttributes.AreAnyAttributesSet() ? pixelModeAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= polygonStippleAttributes.AreAnyAttributesSet() ? polygonStippleAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= scissorAttributes.AreAnyAttributesSet() ? scissorAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= stencilBufferAttributes.AreAnyAttributesSet() ? stencilBufferAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= textureAttributes.AreAnyAttributesSet() ? textureAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= transformAttributes.AreAnyAttributesSet() ? transformAttributes.AttributeFlags : AttributeMask.None; attributeFlags |= viewportAttributes.AreAnyAttributesSet() ? viewportAttributes.AttributeFlags : AttributeMask.None; // Push the attribute stack. gl.PushAttrib((uint)attributeFlags); // Set the attributes. accumBufferAttributes.SetAttributes(gl); colorBufferAttributes.SetAttributes(gl); currentAttributes.SetAttributes(gl); depthBufferAttributes.SetAttributes(gl); enableAttributes.SetAttributes(gl); fogAttributes.SetAttributes(gl); lightingAttributes.SetAttributes(gl); lineAttributes.SetAttributes(gl); pointAttributes.SetAttributes(gl); polygonAttributes.SetAttributes(gl); evalAttributes.SetAttributes(gl); hintAttributes.SetAttributes(gl); listAttributes.SetAttributes(gl); pixelModeAttributes.SetAttributes(gl); polygonStippleAttributes.SetAttributes(gl); scissorAttributes.SetAttributes(gl); stencilBufferAttributes.SetAttributes(gl); textureAttributes.SetAttributes(gl); transformAttributes.SetAttributes(gl); viewportAttributes.SetAttributes(gl); } /// <summary> /// Pops the effect off the specified parent element. /// </summary> /// <param name="gl">The OpenGL instance.</param> /// <param name="parentElement">The parent element.</param> public override void Pop(OpenGL gl, SceneElement parentElement) { // Pop the attribute stack. gl.PopAttrib(); } private AccumBufferAttributes accumBufferAttributes = new AccumBufferAttributes(); private ColorBufferAttributes colorBufferAttributes = new ColorBufferAttributes(); private CurrentAttributes currentAttributes = new CurrentAttributes(); private DepthBufferAttributes depthBufferAttributes = new DepthBufferAttributes(); private EnableAttributes enableAttributes = new EnableAttributes(); private EvalAttributes evalAttributes = new EvalAttributes(); private FogAttributes fogAttributes = new FogAttributes(); private HintAttributes hintAttributes = new HintAttributes(); private LightingAttributes lightingAttributes = new LightingAttributes(); private LineAttributes lineAttributes = new LineAttributes(); private ListAttributes listAttributes = new ListAttributes(); private PixelModeAttributes pixelModeAttributes = new PixelModeAttributes(); private PointAttributes pointAttributes = new PointAttributes(); private PolygonAttributes polygonAttributes = new PolygonAttributes(); private PolygonStippleAttributes polygonStippleAttributes = new PolygonStippleAttributes(); private ScissorAttributes scissorAttributes = new ScissorAttributes(); private StencilBufferAttributes stencilBufferAttributes = new StencilBufferAttributes(); private TextureAttributes textureAttributes = new TextureAttributes(); private TransformAttributes transformAttributes = new TransformAttributes(); private ViewportAttributes viewportAttributes = new ViewportAttributes(); /// <summary> /// Gets or sets the hint attributes. /// </summary> /// <value> /// The hint attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public HintAttributes HintAttributes { get { return hintAttributes; } set { hintAttributes = value; } } /// <summary> /// Gets or sets the list attributes. /// </summary> /// <value> /// The list attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public ListAttributes ListAttributes { get { return listAttributes; } set { listAttributes = value; } } /// <summary> /// Gets or sets the pixel mode attributes. /// </summary> /// <value> /// The pixel mode attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public PixelModeAttributes PixelModeAttributes { get { return pixelModeAttributes; } set { pixelModeAttributes = value; } } /// <summary> /// Gets or sets the polygon stipple attributes. /// </summary> /// <value> /// The polygon stipple attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public PolygonStippleAttributes PolygonStippleAttributes { get { return polygonStippleAttributes; } set { polygonStippleAttributes = value; } } /// <summary> /// Gets or sets the scissor attributes. /// </summary> /// <value> /// The scissor attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public ScissorAttributes ScissorAttributes { get { return scissorAttributes; } set { scissorAttributes = value; } } /// <summary> /// Gets or sets the stencil buffer attributes. /// </summary> /// <value> /// The stencil buffer attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public StencilBufferAttributes StencilBufferAttributes { get { return stencilBufferAttributes; } set { stencilBufferAttributes = value; } } /// <summary> /// Gets or sets the texture attributes. /// </summary> /// <value> /// The texture attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public TextureAttributes TextureAttributes { get { return textureAttributes; } set { textureAttributes = value; } } /// <summary> /// Gets or sets the transform attributes. /// </summary> /// <value> /// The transform attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public TransformAttributes TransformAttributes { get { return transformAttributes; } set { transformAttributes = value; } } /// <summary> /// Gets or sets the viewport attributes. /// </summary> /// <value> /// The viewport attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public ViewportAttributes ViewportAttributes { get { return viewportAttributes; } set { viewportAttributes = value; } } /// <summary> /// Gets or sets the eval attributes. /// </summary> /// <value> /// The eval attributes. /// </value> [Description(""), Category("OpenGL Attributes")] public EvalAttributes EvalAttributes { get { return evalAttributes; } set { evalAttributes = value; } } /// <summary> /// Gets or sets the accum buffer attributes. /// </summary> /// <value> /// The accum buffer attributes. /// </value> [Description("AccumBuffer attributes"), Category("OpenGL Attributes")] public AccumBufferAttributes AccumBufferAttributes { get { return accumBufferAttributes; } set { accumBufferAttributes = value; } } /// <summary> /// Gets or sets the color buffer attributes. /// </summary> /// <value> /// The color buffer attributes. /// </value> [Description("ColorBuffer attributes"), Category("OpenGL Attributes")] public ColorBufferAttributes ColorBufferAttributes { get { return colorBufferAttributes; } set { colorBufferAttributes = value; } } /// <summary> /// Gets or sets the current attributes. /// </summary> /// <value> /// The current buffer. /// </value> [Description("Current attributes"), Category("OpenGL Attributes")] public CurrentAttributes CurrentAttributes { get { return currentAttributes; } set { currentAttributes = value; } } /// <summary> /// Gets or sets the depth buffer attributes. /// </summary> /// <value> /// The depth buffer attributes. /// </value> [Description("DepthBuffer attributes"), Category("OpenGL Attributes")] public DepthBufferAttributes DepthBufferAttributes { get { return depthBufferAttributes; } set { depthBufferAttributes = value; } } /// <summary> /// Gets or sets the enable attributes. /// </summary> /// <value> /// The enable attributes. /// </value> [Description("Enable attributes"), Category("OpenGL Attributes")] public EnableAttributes EnableAttributes { get { return enableAttributes; } set { enableAttributes = value; } } /// <summary> /// Gets the fog attributes. /// </summary> [Description("Fog attributes"), Category("OpenGL Attributes")] public FogAttributes FogAttributes { get { return fogAttributes; } set { fogAttributes = value; } } /// <summary> /// Gets the lighting attributes. /// </summary> [Description("Lighting attributes"), Category("OpenGL Attributes")] public LightingAttributes LightingAttributes { get { return lightingAttributes; } set { lightingAttributes = value; } } /// <summary> /// Gets the line attributes. /// </summary> [Description("Line attributes"), Category("OpenGL Attributes")] public LineAttributes LineAttributes { get { return lineAttributes; } set { lineAttributes = value; } } /// <summary> /// Gets the point attributes. /// </summary> [Description("Point attributes"), Category("OpenGL Attributes")] public PointAttributes PointAttributes { get { return pointAttributes; } set { pointAttributes = value; } } /// <summary> /// Gets the polygon attributes. /// </summary> [Description("Polygon attributes"), Category("OpenGL Attributes")] public PolygonAttributes PolygonAttributes { get { return polygonAttributes; } set { polygonAttributes = value; } } } }
using J2N.Runtime.CompilerServices; using J2N.Threading.Atomic; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using JCG = J2N.Collections.Generic; namespace YAF.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 InfoStream = YAF.Lucene.Net.Util.InfoStream; using ThreadState = YAF.Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState; /// <summary> /// This class controls <see cref="DocumentsWriterPerThread"/> flushing during /// indexing. It tracks the memory consumption per /// <see cref="DocumentsWriterPerThread"/> and uses a configured <see cref="flushPolicy"/> to /// decide if a <see cref="DocumentsWriterPerThread"/> must flush. /// <para/> /// In addition to the <see cref="flushPolicy"/> the flush control might set certain /// <see cref="DocumentsWriterPerThread"/> as flush pending iff a /// <see cref="DocumentsWriterPerThread"/> exceeds the /// <see cref="IndexWriterConfig.RAMPerThreadHardLimitMB"/> to prevent address /// space exhaustion. /// </summary> internal sealed class DocumentsWriterFlushControl { private readonly long hardMaxBytesPerDWPT; private long activeBytes = 0; private long flushBytes = 0; private volatile int numPending = 0; private int numDocsSinceStalled = 0; // only with assert internal readonly AtomicBoolean flushDeletes = new AtomicBoolean(false); private bool fullFlush = false; private readonly Queue<DocumentsWriterPerThread> flushQueue = new Queue<DocumentsWriterPerThread>(); // only for safety reasons if a DWPT is close to the RAM limit private readonly LinkedList<BlockedFlush> blockedFlushes = new LinkedList<BlockedFlush>(); private readonly IDictionary<DocumentsWriterPerThread, long?> flushingWriters = new JCG.Dictionary<DocumentsWriterPerThread, long?>(IdentityEqualityComparer<DocumentsWriterPerThread>.Default); internal double maxConfiguredRamBuffer = 0; internal long peakActiveBytes = 0; // only with assert internal long peakFlushBytes = 0; // only with assert internal long peakNetBytes = 0; // only with assert internal long peakDelta = 0; // only with assert internal readonly DocumentsWriterStallControl stallControl; private readonly DocumentsWriterPerThreadPool perThreadPool; private readonly FlushPolicy flushPolicy; private bool closed = false; private readonly DocumentsWriter documentsWriter; private readonly LiveIndexWriterConfig config; private readonly BufferedUpdatesStream bufferedUpdatesStream; private readonly InfoStream infoStream; internal DocumentsWriterFlushControl(DocumentsWriter documentsWriter, LiveIndexWriterConfig config, BufferedUpdatesStream bufferedUpdatesStream) { this.infoStream = config.InfoStream; this.stallControl = new DocumentsWriterStallControl(); this.perThreadPool = documentsWriter.perThreadPool; this.flushPolicy = documentsWriter.flushPolicy; this.config = config; this.hardMaxBytesPerDWPT = config.RAMPerThreadHardLimitMB * 1024 * 1024; this.documentsWriter = documentsWriter; this.bufferedUpdatesStream = bufferedUpdatesStream; } public long ActiveBytes { get { lock (this) { return activeBytes; } } } public long FlushBytes { get { lock (this) { return flushBytes; } } } public long NetBytes { get { lock (this) { return flushBytes + activeBytes; } } } private long StallLimitBytes { get { double maxRamMB = config.RAMBufferSizeMB; return maxRamMB != IndexWriterConfig.DISABLE_AUTO_FLUSH ? (long)(2 * (maxRamMB * 1024 * 1024)) : long.MaxValue; } } private bool AssertMemory() { double maxRamMB = config.RAMBufferSizeMB; if (maxRamMB != IndexWriterConfig.DISABLE_AUTO_FLUSH) { // for this assert we must be tolerant to ram buffer changes! maxConfiguredRamBuffer = Math.Max(maxRamMB, maxConfiguredRamBuffer); long ram = flushBytes + activeBytes; long ramBufferBytes = (long)(maxConfiguredRamBuffer * 1024 * 1024); // take peakDelta into account - worst case is that all flushing, pending and blocked DWPT had maxMem and the last doc had the peakDelta // 2 * ramBufferBytes -> before we stall we need to cross the 2xRAM Buffer border this is still a valid limit // (numPending + numFlushingDWPT() + numBlockedFlushes()) * peakDelta) -> those are the total number of DWPT that are not active but not yet fully fluhsed // all of them could theoretically be taken out of the loop once they crossed the RAM buffer and the last document was the peak delta // (numDocsSinceStalled * peakDelta) -> at any given time there could be n threads in flight that crossed the stall control before we reached the limit and each of them could hold a peak document long expected = (2 * (ramBufferBytes)) + ((numPending + NumFlushingDWPT + NumBlockedFlushes) * peakDelta) + (numDocsSinceStalled * peakDelta); // the expected ram consumption is an upper bound at this point and not really the expected consumption if (peakDelta < (ramBufferBytes >> 1)) { /* * if we are indexing with very low maxRamBuffer like 0.1MB memory can * easily overflow if we check out some DWPT based on docCount and have * several DWPT in flight indexing large documents (compared to the ram * buffer). this means that those DWPT and their threads will not hit * the stall control before asserting the memory which would in turn * fail. To prevent this we only assert if the the largest document seen * is smaller than the 1/2 of the maxRamBufferMB */ Debug.Assert(ram <= expected, "actual mem: " + ram + " byte, expected mem: " + expected + " byte, flush mem: " + flushBytes + ", active mem: " + activeBytes + ", pending DWPT: " + numPending + ", flushing DWPT: " + NumFlushingDWPT + ", blocked DWPT: " + NumBlockedFlushes + ", peakDelta mem: " + peakDelta + " byte"); } } return true; } private void CommitPerThreadBytes(ThreadState perThread) { long delta = perThread.dwpt.BytesUsed - perThread.bytesUsed; perThread.bytesUsed += delta; /* * We need to differentiate here if we are pending since setFlushPending * moves the perThread memory to the flushBytes and we could be set to * pending during a delete */ if (perThread.flushPending) { flushBytes += delta; } else { activeBytes += delta; } Debug.Assert(UpdatePeaks(delta)); } // only for asserts private bool UpdatePeaks(long delta) { peakActiveBytes = Math.Max(peakActiveBytes, activeBytes); peakFlushBytes = Math.Max(peakFlushBytes, flushBytes); peakNetBytes = Math.Max(peakNetBytes, NetBytes); peakDelta = Math.Max(peakDelta, delta); return true; } internal DocumentsWriterPerThread DoAfterDocument(ThreadState perThread, bool isUpdate) { lock (this) { try { CommitPerThreadBytes(perThread); if (!perThread.flushPending) { if (isUpdate) { flushPolicy.OnUpdate(this, perThread); } else { flushPolicy.OnInsert(this, perThread); } if (!perThread.flushPending && perThread.bytesUsed > hardMaxBytesPerDWPT) { // Safety check to prevent a single DWPT exceeding its RAM limit. this // is super important since we can not address more than 2048 MB per DWPT SetFlushPending(perThread); } } DocumentsWriterPerThread flushingDWPT; if (fullFlush) { if (perThread.flushPending) { CheckoutAndBlock(perThread); flushingDWPT = NextPendingFlush(); } else { flushingDWPT = null; } } else { flushingDWPT = TryCheckoutForFlush(perThread); } return flushingDWPT; } finally { bool stalled = UpdateStallState(); Debug.Assert(AssertNumDocsSinceStalled(stalled) && AssertMemory()); } } } private bool AssertNumDocsSinceStalled(bool stalled) { /* * updates the number of documents "finished" while we are in a stalled state. * this is important for asserting memory upper bounds since it corresponds * to the number of threads that are in-flight and crossed the stall control * check before we actually stalled. * see #assertMemory() */ if (stalled) { numDocsSinceStalled++; } else { numDocsSinceStalled = 0; } return true; } internal void DoAfterFlush(DocumentsWriterPerThread dwpt) { lock (this) { Debug.Assert(flushingWriters.ContainsKey(dwpt)); try { long? bytes = flushingWriters[dwpt]; flushingWriters.Remove(dwpt); flushBytes -= (long)bytes; perThreadPool.Recycle(dwpt); Debug.Assert(AssertMemory()); } finally { try { UpdateStallState(); } finally { Monitor.PulseAll(this); } } } } private bool UpdateStallState() { //Debug.Assert(Thread.holdsLock(this)); long limit = StallLimitBytes; /* * we block indexing threads if net byte grows due to slow flushes * yet, for small ram buffers and large documents we can easily * reach the limit without any ongoing flushes. we need to ensure * that we don't stall/block if an ongoing or pending flush can * not free up enough memory to release the stall lock. */ bool stall = ((activeBytes + flushBytes) > limit) && (activeBytes < limit) && !closed; stallControl.UpdateStalled(stall); return stall; } public void WaitForFlush() { lock (this) { while (flushingWriters.Count != 0) { //#if !NETSTANDARD1_6 // try // { //#endif Monitor.Wait(this); //#if !NETSTANDARD1_6 // LUCENENET NOTE: Senseless to catch and rethrow the same exception type // } // catch (ThreadInterruptedException e) // { // throw new ThreadInterruptedException("Thread Interrupted Exception", e); // } //#endif } } } /// <summary> /// Sets flush pending state on the given <see cref="ThreadState"/>. The /// <see cref="ThreadState"/> must have indexed at least on <see cref="Documents.Document"/> and must not be /// already pending. /// </summary> public void SetFlushPending(ThreadState perThread) { lock (this) { Debug.Assert(!perThread.flushPending); if (perThread.dwpt.NumDocsInRAM > 0) { perThread.flushPending = true; // write access synced long bytes = perThread.bytesUsed; flushBytes += bytes; activeBytes -= bytes; numPending++; // write access synced Debug.Assert(AssertMemory()); } // don't assert on numDocs since we could hit an abort excp. while selecting that dwpt for flushing } } internal void DoOnAbort(ThreadState state) { lock (this) { try { if (state.flushPending) { flushBytes -= state.bytesUsed; } else { activeBytes -= state.bytesUsed; } Debug.Assert(AssertMemory()); // Take it out of the loop this DWPT is stale perThreadPool.Reset(state, closed); } finally { UpdateStallState(); } } } internal DocumentsWriterPerThread TryCheckoutForFlush(ThreadState perThread) { lock (this) { return perThread.flushPending ? InternalTryCheckOutForFlush(perThread) : null; } } private void CheckoutAndBlock(ThreadState perThread) { perThread.@Lock(); try { Debug.Assert(perThread.flushPending, "can not block non-pending threadstate"); Debug.Assert(fullFlush, "can not block if fullFlush == false"); DocumentsWriterPerThread dwpt; long bytes = perThread.bytesUsed; dwpt = perThreadPool.Reset(perThread, closed); numPending--; blockedFlushes.AddLast(new BlockedFlush(dwpt, bytes)); } finally { perThread.Unlock(); } } private DocumentsWriterPerThread InternalTryCheckOutForFlush(ThreadState perThread) { //Debug.Assert(Thread.HoldsLock(this)); Debug.Assert(perThread.flushPending); try { // We are pending so all memory is already moved to flushBytes if (perThread.TryLock()) { try { if (perThread.IsInitialized) { //Debug.Assert(perThread.HeldByCurrentThread); DocumentsWriterPerThread dwpt; long bytes = perThread.bytesUsed; // do that before // replace! dwpt = perThreadPool.Reset(perThread, closed); Debug.Assert(!flushingWriters.ContainsKey(dwpt), "DWPT is already flushing"); // Record the flushing DWPT to reduce flushBytes in doAfterFlush flushingWriters[dwpt] = bytes; numPending--; // write access synced return dwpt; } } finally { perThread.Unlock(); } } return null; } finally { UpdateStallState(); } } public override string ToString() { return "DocumentsWriterFlushControl [activeBytes=" + activeBytes + ", flushBytes=" + flushBytes + "]"; } internal DocumentsWriterPerThread NextPendingFlush() { int numPending; bool fullFlush; lock (this) { DocumentsWriterPerThread poll; if (flushQueue.Count > 0 && (poll = flushQueue.Dequeue()) != null) { UpdateStallState(); return poll; } fullFlush = this.fullFlush; numPending = this.numPending; } if (numPending > 0 && !fullFlush) // don't check if we are doing a full flush { int limit = perThreadPool.NumThreadStatesActive; for (int i = 0; i < limit && numPending > 0; i++) { ThreadState next = perThreadPool.GetThreadState(i); if (next.flushPending) { DocumentsWriterPerThread dwpt = TryCheckoutForFlush(next); if (dwpt != null) { return dwpt; } } } } return null; } internal void SetClosed() { lock (this) { // set by DW to signal that we should not release new DWPT after close if (!closed) { this.closed = true; perThreadPool.DeactivateUnreleasedStates(); } } } /// <summary> /// Returns an iterator that provides access to all currently active <see cref="ThreadState"/>s /// </summary> public IEnumerator<ThreadState> AllActiveThreadStates() { return GetPerThreadsIterator(perThreadPool.NumThreadStatesActive); } private IEnumerator<ThreadState> GetPerThreadsIterator(int upto) { return new IteratorAnonymousInnerClassHelper(this, upto); } private class IteratorAnonymousInnerClassHelper : IEnumerator<ThreadState> { private readonly DocumentsWriterFlushControl outerInstance; private ThreadState current; private int upto; private int i; public IteratorAnonymousInnerClassHelper(DocumentsWriterFlushControl outerInstance, int upto) { this.outerInstance = outerInstance; this.upto = upto; i = 0; } public ThreadState Current { get { return current; } } public void Dispose() { } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (i < upto) { current = outerInstance.perThreadPool.GetThreadState(i++); return true; } return false; } public void Reset() { throw new NotSupportedException(); } } internal void DoOnDelete() { lock (this) { // pass null this is a global delete no update flushPolicy.OnDelete(this, null); } } /// <summary> /// Returns the number of delete terms in the global pool /// </summary> public int NumGlobalTermDeletes { get { return documentsWriter.deleteQueue.NumGlobalTermDeletes + bufferedUpdatesStream.NumTerms; } } public long DeleteBytesUsed { get { return documentsWriter.deleteQueue.BytesUsed + bufferedUpdatesStream.BytesUsed; } } internal int NumFlushingDWPT { get { lock (this) { return flushingWriters.Count; } } } public bool GetAndResetApplyAllDeletes() { return flushDeletes.GetAndSet(false); } public void SetApplyAllDeletes() { flushDeletes.Value = true; } internal int NumActiveDWPT { get { return this.perThreadPool.NumThreadStatesActive; } } internal ThreadState ObtainAndLock() { ThreadState perThread = perThreadPool.GetAndLock(Thread.CurrentThread, documentsWriter); bool success = false; try { if (perThread.IsInitialized && perThread.dwpt.deleteQueue != documentsWriter.deleteQueue) { // There is a flush-all in process and this DWPT is // now stale -- enroll it for flush and try for // another DWPT: AddFlushableState(perThread); } success = true; // simply return the ThreadState even in a flush all case sine we already hold the lock return perThread; } finally { if (!success) // make sure we unlock if this fails { perThread.Unlock(); } } } internal void MarkForFullFlush() { DocumentsWriterDeleteQueue flushingQueue; lock (this) { Debug.Assert(!fullFlush, "called DWFC#markForFullFlush() while full flush is still running"); Debug.Assert(fullFlushBuffer.Count == 0, "full flush buffer should be empty: " + fullFlushBuffer); fullFlush = true; flushingQueue = documentsWriter.deleteQueue; // Set a new delete queue - all subsequent DWPT will use this queue until // we do another full flush DocumentsWriterDeleteQueue newQueue = new DocumentsWriterDeleteQueue(flushingQueue.generation + 1); documentsWriter.deleteQueue = newQueue; } int limit = perThreadPool.NumThreadStatesActive; for (int i = 0; i < limit; i++) { ThreadState next = perThreadPool.GetThreadState(i); next.@Lock(); try { if (!next.IsInitialized) { if (closed && next.IsActive) { perThreadPool.DeactivateThreadState(next); } continue; } Debug.Assert(next.dwpt.deleteQueue == flushingQueue || next.dwpt.deleteQueue == documentsWriter.deleteQueue, " flushingQueue: " + flushingQueue + " currentqueue: " + documentsWriter.deleteQueue + " perThread queue: " + next.dwpt.deleteQueue + " numDocsInRam: " + next.dwpt.NumDocsInRAM); if (next.dwpt.deleteQueue != flushingQueue) { // this one is already a new DWPT continue; } AddFlushableState(next); } finally { next.Unlock(); } } lock (this) { /* make sure we move all DWPT that are where concurrently marked as * pending and moved to blocked are moved over to the flushQueue. There is * a chance that this happens since we marking DWPT for full flush without * blocking indexing.*/ PruneBlockedQueue(flushingQueue); Debug.Assert(AssertBlockedFlushes(documentsWriter.deleteQueue)); //FlushQueue.AddAll(FullFlushBuffer); foreach (var dwpt in fullFlushBuffer) { flushQueue.Enqueue(dwpt); } fullFlushBuffer.Clear(); UpdateStallState(); } Debug.Assert(AssertActiveDeleteQueue(documentsWriter.deleteQueue)); } private bool AssertActiveDeleteQueue(DocumentsWriterDeleteQueue queue) { int limit = perThreadPool.NumThreadStatesActive; for (int i = 0; i < limit; i++) { ThreadState next = perThreadPool.GetThreadState(i); next.@Lock(); try { Debug.Assert(!next.IsInitialized || next.dwpt.deleteQueue == queue, "isInitialized: " + next.IsInitialized + " numDocs: " + (next.IsInitialized ? next.dwpt.NumDocsInRAM : 0)); } finally { next.Unlock(); } } return true; } private readonly IList<DocumentsWriterPerThread> fullFlushBuffer = new List<DocumentsWriterPerThread>(); internal void AddFlushableState(ThreadState perThread) { if (infoStream.IsEnabled("DWFC")) { infoStream.Message("DWFC", "addFlushableState " + perThread.dwpt); } DocumentsWriterPerThread dwpt = perThread.dwpt; //Debug.Assert(perThread.HeldByCurrentThread); Debug.Assert(perThread.IsInitialized); Debug.Assert(fullFlush); Debug.Assert(dwpt.deleteQueue != documentsWriter.deleteQueue); if (dwpt.NumDocsInRAM > 0) { lock (this) { if (!perThread.flushPending) { SetFlushPending(perThread); } DocumentsWriterPerThread flushingDWPT = InternalTryCheckOutForFlush(perThread); Debug.Assert(flushingDWPT != null, "DWPT must never be null here since we hold the lock and it holds documents"); Debug.Assert(dwpt == flushingDWPT, "flushControl returned different DWPT"); fullFlushBuffer.Add(flushingDWPT); } } else { perThreadPool.Reset(perThread, closed); // make this state inactive } } /// <summary> /// Prunes the blockedQueue by removing all DWPT that are associated with the given flush queue. /// </summary> private void PruneBlockedQueue(DocumentsWriterDeleteQueue flushingQueue) { var node = blockedFlushes.First; while (node != null) { var nextNode = node.Next; BlockedFlush blockedFlush = node.Value; if (blockedFlush.Dwpt.deleteQueue == flushingQueue) { blockedFlushes.Remove(node); Debug.Assert(!flushingWriters.ContainsKey(blockedFlush.Dwpt), "DWPT is already flushing"); // Record the flushing DWPT to reduce flushBytes in doAfterFlush flushingWriters[blockedFlush.Dwpt] = blockedFlush.Bytes; // don't decr pending here - its already done when DWPT is blocked flushQueue.Enqueue(blockedFlush.Dwpt); } node = nextNode; } } internal void FinishFullFlush() { lock (this) { Debug.Assert(fullFlush); Debug.Assert(flushQueue.Count == 0); Debug.Assert(flushingWriters.Count == 0); try { if (blockedFlushes.Count > 0) { Debug.Assert(AssertBlockedFlushes(documentsWriter.deleteQueue)); PruneBlockedQueue(documentsWriter.deleteQueue); Debug.Assert(blockedFlushes.Count == 0); } } finally { fullFlush = false; UpdateStallState(); } } } internal bool AssertBlockedFlushes(DocumentsWriterDeleteQueue flushingQueue) { foreach (BlockedFlush blockedFlush in blockedFlushes) { Debug.Assert(blockedFlush.Dwpt.deleteQueue == flushingQueue); } return true; } internal void AbortFullFlushes(ISet<string> newFiles) { lock (this) { try { AbortPendingFlushes(newFiles); } finally { fullFlush = false; } } } internal void AbortPendingFlushes(ISet<string> newFiles) { lock (this) { try { foreach (DocumentsWriterPerThread dwpt in flushQueue) { try { documentsWriter.SubtractFlushedNumDocs(dwpt.NumDocsInRAM); dwpt.Abort(newFiles); } catch (Exception) { // ignore - keep on aborting the flush queue } finally { DoAfterFlush(dwpt); } } foreach (BlockedFlush blockedFlush in blockedFlushes) { try { flushingWriters[blockedFlush.Dwpt] = blockedFlush.Bytes; documentsWriter.SubtractFlushedNumDocs(blockedFlush.Dwpt.NumDocsInRAM); blockedFlush.Dwpt.Abort(newFiles); } catch (Exception) { // ignore - keep on aborting the blocked queue } finally { DoAfterFlush(blockedFlush.Dwpt); } } } finally { flushQueue.Clear(); blockedFlushes.Clear(); UpdateStallState(); } } } /// <summary> /// Returns <c>true</c> if a full flush is currently running /// </summary> internal bool IsFullFlush { get { lock (this) { return fullFlush; } } } /// <summary> /// Returns the number of flushes that are already checked out but not yet /// actively flushing /// </summary> internal int NumQueuedFlushes { get { lock (this) { return flushQueue.Count; } } } /// <summary> /// Returns the number of flushes that are checked out but not yet available /// for flushing. This only applies during a full flush if a DWPT needs /// flushing but must not be flushed until the full flush has finished. /// </summary> internal int NumBlockedFlushes { get { lock (this) { return blockedFlushes.Count; } } } private class BlockedFlush { internal DocumentsWriterPerThread Dwpt { get; private set; } internal long Bytes { get; private set; } internal BlockedFlush(DocumentsWriterPerThread dwpt, long bytes) : base() { this.Dwpt = dwpt; this.Bytes = bytes; } } /// <summary> /// This method will block if too many DWPT are currently flushing and no /// checked out DWPT are available /// </summary> internal void WaitIfStalled() { if (infoStream.IsEnabled("DWFC")) { infoStream.Message("DWFC", "waitIfStalled: numFlushesPending: " + flushQueue.Count + " netBytes: " + NetBytes + " flushBytes: " + FlushBytes + " fullFlush: " + fullFlush); } stallControl.WaitIfStalled(); } /// <summary> /// Returns <c>true</c> iff stalled /// </summary> internal bool AnyStalledThreads() { return stallControl.AnyStalledThreads(); } /// <summary> /// Returns the <see cref="IndexWriter"/> <see cref="Util.InfoStream"/> /// </summary> public InfoStream InfoStream { get { return infoStream; } } } }
/* * 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.Linq; using System.Threading; using log4net; namespace OpenSim.Framework.Monitoring { /// <summary> /// Manages launching threads and keeping watch over them for timeouts /// </summary> public static class Watchdog { /// <summary>Timer interval in milliseconds for the watchdog timer</summary> public const double WATCHDOG_INTERVAL_MS = 2500.0d; /// <summary>Default timeout in milliseconds before a thread is considered dead</summary> public const int DEFAULT_WATCHDOG_TIMEOUT_MS = 5000; [System.Diagnostics.DebuggerDisplay("{Thread.Name}")] public class ThreadWatchdogInfo { public Thread Thread { get; private set; } /// <summary> /// Approximate tick when this thread was started. /// </summary> /// <remarks> /// Not terribly good since this quickly wraps around. /// </remarks> public int FirstTick { get; private set; } /// <summary> /// Last time this heartbeat update was invoked /// </summary> public int LastTick { get; set; } /// <summary> /// Number of milliseconds before we notify that the thread is having a problem. /// </summary> public int Timeout { get; set; } /// <summary> /// Is this thread considered timed out? /// </summary> public bool IsTimedOut { get; set; } /// <summary> /// Will this thread trigger the alarm function if it has timed out? /// </summary> public bool AlarmIfTimeout { get; set; } /// <summary> /// Method execute if alarm goes off. If null then no alarm method is fired. /// </summary> public Func<string> AlarmMethod { get; set; } public ThreadWatchdogInfo(Thread thread, int timeout) { Thread = thread; Timeout = timeout; FirstTick = Environment.TickCount & Int32.MaxValue; LastTick = FirstTick; } public ThreadWatchdogInfo(ThreadWatchdogInfo previousTwi) { Thread = previousTwi.Thread; FirstTick = previousTwi.FirstTick; LastTick = previousTwi.LastTick; Timeout = previousTwi.Timeout; IsTimedOut = previousTwi.IsTimedOut; AlarmIfTimeout = previousTwi.AlarmIfTimeout; AlarmMethod = previousTwi.AlarmMethod; } } /// <summary> /// This event is called whenever a tracked thread is /// stopped or has not called UpdateThread() in time< /// /summary> public static event Action<ThreadWatchdogInfo> OnWatchdogTimeout; /// <summary> /// Is this watchdog active? /// </summary> public static bool Enabled { get { return m_enabled; } set { // m_log.DebugFormat("[MEMORY WATCHDOG]: Setting MemoryWatchdog.Enabled to {0}", value); if (value == m_enabled) return; m_enabled = value; if (m_enabled) { // Set now so we don't get alerted on the first run LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue; } m_watchdogTimer.Enabled = m_enabled; } } private static bool m_enabled; private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static Dictionary<int, ThreadWatchdogInfo> m_threads; private static System.Timers.Timer m_watchdogTimer; /// <summary> /// Last time the watchdog thread ran. /// </summary> /// <remarks> /// Should run every WATCHDOG_INTERVAL_MS /// </remarks> public static int LastWatchdogThreadTick { get; private set; } static Watchdog() { m_threads = new Dictionary<int, ThreadWatchdogInfo>(); m_watchdogTimer = new System.Timers.Timer(WATCHDOG_INTERVAL_MS); m_watchdogTimer.AutoReset = false; m_watchdogTimer.Elapsed += WatchdogTimerElapsed; } /// <summary> /// Start a new thread that is tracked by the watchdog timer. /// </summary> /// <param name="start">The method that will be executed in a new thread</param> /// <param name="name">A name to give to the new thread</param> /// <param name="priority">Priority to run the thread at</param> /// <param name="isBackground">True to run this thread as a background thread, otherwise false</param> /// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param> /// <returns>The newly created Thread object</returns> public static Thread StartThread( ThreadStart start, string name, ThreadPriority priority, bool isBackground, bool alarmIfTimeout) { return StartThread(start, name, priority, isBackground, alarmIfTimeout, null, DEFAULT_WATCHDOG_TIMEOUT_MS); } /// <summary> /// Start a new thread that is tracked by the watchdog timer /// </summary> /// <param name="start">The method that will be executed in a new thread</param> /// <param name="name">A name to give to the new thread</param> /// <param name="priority">Priority to run the thread at</param> /// <param name="isBackground">True to run this thread as a background /// thread, otherwise false</param> /// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param> /// <param name="alarmMethod"> /// Alarm method to call if alarmIfTimeout is true and there is a timeout. /// Normally, this will just return some useful debugging information. /// </param> /// <param name="timeout">Number of milliseconds to wait until we issue a warning about timeout.</param> /// <returns>The newly created Thread object</returns> public static Thread StartThread( ThreadStart start, string name, ThreadPriority priority, bool isBackground, bool alarmIfTimeout, Func<string> alarmMethod, int timeout) { Thread thread = new Thread(start); thread.Name = name; thread.Priority = priority; thread.IsBackground = isBackground; ThreadWatchdogInfo twi = new ThreadWatchdogInfo(thread, timeout) { AlarmIfTimeout = alarmIfTimeout, AlarmMethod = alarmMethod }; m_log.DebugFormat( "[WATCHDOG]: Started tracking thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId); lock (m_threads) m_threads.Add(twi.Thread.ManagedThreadId, twi); thread.Start(); return thread; } /// <summary> /// Marks the current thread as alive /// </summary> public static void UpdateThread() { UpdateThread(Thread.CurrentThread.ManagedThreadId); } /// <summary> /// Stops watchdog tracking on the current thread /// </summary> /// <returns> /// True if the thread was removed from the list of tracked /// threads, otherwise false /// </returns> public static bool RemoveThread() { return RemoveThread(Thread.CurrentThread.ManagedThreadId); } private static bool RemoveThread(int threadID) { lock (m_threads) { ThreadWatchdogInfo twi; if (m_threads.TryGetValue(threadID, out twi)) { m_log.DebugFormat( "[WATCHDOG]: Removing thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId); m_threads.Remove(threadID); return true; } else { m_log.WarnFormat( "[WATCHDOG]: Requested to remove thread with ID {0} but this is not being monitored", threadID); return false; } } } public static bool AbortThread(int threadID) { lock (m_threads) { if (m_threads.ContainsKey(threadID)) { ThreadWatchdogInfo twi = m_threads[threadID]; twi.Thread.Abort(); RemoveThread(threadID); return true; } else { return false; } } } private static void UpdateThread(int threadID) { ThreadWatchdogInfo threadInfo; // Although TryGetValue is not a thread safe operation, we use a try/catch here instead // of a lock for speed. Adding/removing threads is a very rare operation compared to // UpdateThread(), and a single UpdateThread() failure here and there won't break // anything try { if (m_threads.TryGetValue(threadID, out threadInfo)) { threadInfo.LastTick = Environment.TickCount & Int32.MaxValue; threadInfo.IsTimedOut = false; } else { m_log.WarnFormat("[WATCHDOG]: Asked to update thread {0} which is not being monitored", threadID); } } catch { } } /// <summary> /// Get currently watched threads for diagnostic purposes /// </summary> /// <returns></returns> public static ThreadWatchdogInfo[] GetThreadsInfo() { lock (m_threads) return m_threads.Values.ToArray(); } /// <summary> /// Return the current thread's watchdog info. /// </summary> /// <returns>The watchdog info. null if the thread isn't being monitored.</returns> public static ThreadWatchdogInfo GetCurrentThreadInfo() { lock (m_threads) { if (m_threads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) return m_threads[Thread.CurrentThread.ManagedThreadId]; } return null; } /// <summary> /// Check watched threads. Fire alarm if appropriate. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e) { int now = Environment.TickCount & Int32.MaxValue; int msElapsed = now - LastWatchdogThreadTick; if (msElapsed > WATCHDOG_INTERVAL_MS * 2) m_log.WarnFormat( "[WATCHDOG]: {0} ms since Watchdog last ran. Interval should be approximately {1} ms", msElapsed, WATCHDOG_INTERVAL_MS); LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue; Action<ThreadWatchdogInfo> callback = OnWatchdogTimeout; if (callback != null) { List<ThreadWatchdogInfo> callbackInfos = null; lock (m_threads) { foreach (ThreadWatchdogInfo threadInfo in m_threads.Values) { if (threadInfo.Thread.ThreadState == ThreadState.Stopped) { RemoveThread(threadInfo.Thread.ManagedThreadId); if (callbackInfos == null) callbackInfos = new List<ThreadWatchdogInfo>(); callbackInfos.Add(threadInfo); } else if (!threadInfo.IsTimedOut && now - threadInfo.LastTick >= threadInfo.Timeout) { threadInfo.IsTimedOut = true; if (threadInfo.AlarmIfTimeout) { if (callbackInfos == null) callbackInfos = new List<ThreadWatchdogInfo>(); // Send a copy of the watchdog info to prevent race conditions where the watchdog // thread updates the monitoring info after an alarm has been sent out. callbackInfos.Add(new ThreadWatchdogInfo(threadInfo)); } } } } if (callbackInfos != null) foreach (ThreadWatchdogInfo callbackInfo in callbackInfos) callback(callbackInfo); } if (MemoryWatchdog.Enabled) MemoryWatchdog.Update(); StatsManager.RecordStats(); m_watchdogTimer.Start(); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Data.SqlClient; using System.Linq; using System.Security.Authentication; using System.Text; using System.Threading.Tasks; using FLS.Common.Extensions; using FLS.Data.WebApi; using FLS.Server.Data.DbEntities; using FLS.Server.Data.Enums; using FLS.Server.Data.Exceptions; using NLog; using TrackerEnabledDbContext; using TrackerEnabledDbContext.Common.Configuration; using FLS.Server.Data.Resources; namespace FLS.Server.Data { public partial class FLSDataEntities : TrackerContext { private readonly IIdentityService _identityService; private Logger _logger = LogManager.GetCurrentClassLogger(); protected Logger Logger { get { return _logger; } set { _logger = value; } } public FLSDataEntities(IIdentityService identityService) : base("name=FLSDataEntities") { _identityService = identityService; //tried to fix the lazy loading issue with this configuration on 5.1.2014 PAS, but without success Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; } #region DbSet Entity Properties public virtual DbSet<AccountingRuleFilter> AccountingRuleFilters { get; set; } public virtual DbSet<AccountingRuleFilterType> AccountingRuleFilterTypes { get; set; } public virtual DbSet<AccountingUnitType> AccountingUnitTypes { get; set; } public virtual DbSet<AircraftAircraftState> AircraftAircraftStates { get; set; } public virtual DbSet<Aircraft> Aircrafts { get; set; } public virtual DbSet<AircraftOperatingCounter> AircraftOperatingCounters { get; set; } public virtual DbSet<AircraftReservation> AircraftReservations { get; set; } public virtual DbSet<AircraftReservationType> AircraftReservationTypes { get; set; } public virtual DbSet<AircraftState> AircraftStates { get; set; } public virtual DbSet<AircraftType> AircraftTypes { get; set; } public virtual DbSet<Article> Articles { get; set; } public virtual DbSet<ClubExtension> ClubExtensions { get; set; } public virtual DbSet<Club> Clubs { get; set; } public virtual DbSet<ClubState> ClubStates { get; set; } public virtual DbSet<Country> Countries { get; set; } public virtual DbSet<CounterUnitType> CounterUnitTypes { get; set; } public virtual DbSet<Delivery> Deliveries { get; set; } public virtual DbSet<DeliveryCreationTest> DeliveryCreationTests { get; set; } public virtual DbSet<DeliveryItem> DeliveryItems { get; set; } public virtual DbSet<ElevationUnitType> ElevationUnitTypes { get; set; } public virtual DbSet<EmailTemplate> EmailTemplates { get; set; } public virtual DbSet<ExtensionValue> ExtensionValues { get; set; } public virtual DbSet<Extension> Extensions { get; set; } public virtual DbSet<ExtensionType> ExtensionTypes { get; set; } public virtual DbSet<FlightCostBalanceType> FlightCostBalanceTypes { get; set; } public virtual DbSet<FlightCrew> FlightCrews { get; set; } public virtual DbSet<FlightCrewType> FlightCrewTypes { get; set; } public virtual DbSet<Flight> Flights { get; set; } public virtual DbSet<FlightAirState> FlightAirStates { get; set; } public virtual DbSet<FlightProcessState> FlightProcessStates { get; set; } public virtual DbSet<FlightType> FlightTypes { get; set; } public virtual DbSet<InOutboundPoint> InOutboundPoints { get; set; } public virtual DbSet<LanguageTranslation> LanguageTranslations { get; set; } public virtual DbSet<Language> Languages { get; set; } public virtual DbSet<LengthUnitType> LengthUnitTypes { get; set; } public virtual DbSet<Location> Locations { get; set; } public virtual DbSet<LocationType> LocationTypes { get; set; } public virtual DbSet<MemberState> MemberStates { get; set; } public virtual DbSet<PersonCategory> PersonCategories { get; set; } public virtual DbSet<PersonClub> PersonClubs { get; set; } public virtual DbSet<PersonFlightTimeCredit> PersonFlightTimeCredits { get; set; } public virtual DbSet<PersonFlightTimeCreditTransaction> PersonFlightTimeCreditTransactions { get; set; } public virtual DbSet<PersonPersonCategory> PersonPersonCategories { get; set; } public virtual DbSet<PlanningDay> PlanningDays { get; set; } public virtual DbSet<PlanningDayAssignment> PlanningDayAssignments { get; set; } public virtual DbSet<PlanningDayAssignmentType> PlanningDayAssignmentTypes { get; set; } public virtual DbSet<Person> Persons { get; set; } public virtual DbSet<Role> Roles { get; set; } public virtual DbSet<Setting> Settings { get; set; } public virtual DbSet<StartType> StartTypes { get; set; } public virtual DbSet<SystemData> SystemDatas { get; set; } public virtual DbSet<SystemLog> SystemLogs { get; set; } public virtual DbSet<SystemVersion> SystemVersions { get; set; } public virtual DbSet<UserAccountState> UserAccountStates { get; set; } public virtual DbSet<UserRole> UserRoles { get; set; } public virtual DbSet<User> Users { get; set; } #endregion DbSet Entity Properties protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Aircraft>().Ignore(t => t.Id); modelBuilder.Entity<Aircraft>().Ignore(t => t.CurrentAircraftAircraftState); modelBuilder.Entity<Aircraft>().Ignore(t => t.HasEngine); modelBuilder.Entity<Aircraft>().Ignore(t => t.CurrentAircraftOperatingCounter); modelBuilder.Entity<AccountingRuleFilter>().Ignore(t => t.Id); modelBuilder.Entity<AircraftAircraftState>().Ignore(t => t.Id); modelBuilder.Entity<AircraftReservation>().Ignore(t => t.Id); modelBuilder.Entity<AircraftReservationType>().Ignore(t => t.Id); modelBuilder.Entity<AircraftOperatingCounter>().Ignore(t => t.Id); modelBuilder.Entity<AircraftState>().Ignore(t => t.Id); modelBuilder.Entity<Article>().Ignore(t => t.Id); modelBuilder.Entity<Club>().Ignore(t => t.Id); modelBuilder.Entity<Club>().Ignore(t => t.HomebaseName); modelBuilder.Entity<Country>().Ignore(t => t.Id); modelBuilder.Entity<Delivery>().Ignore(t => t.Id); modelBuilder.Entity<DeliveryCreationTest>().Ignore(t => t.Id); modelBuilder.Entity<DeliveryItem>().Ignore(t => t.Id); modelBuilder.Entity<EmailTemplate>().Ignore(t => t.Id); modelBuilder.Entity<ExtensionValue>().Ignore(t => t.Id); modelBuilder.Entity<Flight>().Ignore(t => t.Id); modelBuilder.Entity<Flight>().Ignore(t => t.Pilot); modelBuilder.Entity<Flight>().Ignore(t => t.CoPilot); modelBuilder.Entity<Flight>().Ignore(t => t.Passenger); modelBuilder.Entity<Flight>().Ignore(t => t.Passengers); modelBuilder.Entity<Flight>().Ignore(t => t.Instructor); modelBuilder.Entity<Flight>().Ignore(t => t.InvoiceRecipient); modelBuilder.Entity<Flight>().Ignore(t => t.WinchOperator); modelBuilder.Entity<Flight>().Ignore(t => t.ObserverPerson); modelBuilder.Entity<Flight>().Ignore(t => t.IsTowed); modelBuilder.Entity<Flight>().Ignore(t => t.IsGliderFlight); modelBuilder.Entity<Flight>().Ignore(t => t.IsTowFlight); modelBuilder.Entity<Flight>().Ignore(t => t.IsMotorFlight); modelBuilder.Entity<Flight>().Ignore(t => t.PilotDisplayName); modelBuilder.Entity<Flight>().Ignore(t => t.InstructorDisplayName); modelBuilder.Entity<Flight>().Ignore(t => t.CoPilotDisplayName); modelBuilder.Entity<Flight>().Ignore(t => t.PassengerDisplayName); modelBuilder.Entity<Flight>().Ignore(t => t.AircraftImmatriculation); modelBuilder.Entity<Flight>().Ignore(t => t.IsStarted); modelBuilder.Entity<Flight>().Ignore(t => t.DoNotUpdateMetaData); modelBuilder.Entity<FlightCrew>().Ignore(t => t.Id); modelBuilder.Entity<FlightCrew>().Ignore(t => t.EntityState); modelBuilder.Entity<FlightCrew>().Ignore(t => t.HasPerson); modelBuilder.Entity<FlightType>().Ignore(t => t.Id); modelBuilder.Entity<Language>().Ignore(t => t.Id); modelBuilder.Entity<LanguageTranslation>().Ignore(t => t.Id); modelBuilder.Entity<Location>().Ignore(t => t.Id); modelBuilder.Entity<LocationType>().Ignore(t => t.Id); modelBuilder.Entity<MemberState>().Ignore(t => t.Id); modelBuilder.Entity<PlanningDay>().Ignore(t => t.Id); modelBuilder.Entity<PlanningDayAssignment>().Ignore(t => t.Id); modelBuilder.Entity<PlanningDayAssignment>().Ignore(t => t.EntityState); modelBuilder.Entity<PlanningDayAssignmentType>().Ignore(t => t.Id); modelBuilder.Entity<Person>().Ignore(t => t.Id); modelBuilder.Entity<Person>().Ignore(t => t.DisplayName); modelBuilder.Entity<Person>().Ignore(t => t.EmailAddressForCommunication); modelBuilder.Entity<Person>().Ignore(t => t.DoNotUpdateTimeStampsInMetaData); modelBuilder.Entity<PersonCategory>().Ignore(t => t.Id); modelBuilder.Entity<PersonClub>().Ignore(t => t.Id); modelBuilder.Entity<PersonClub>().Ignore(t => t.DoNotUpdateTimeStampsInMetaData); modelBuilder.Entity<PersonFlightTimeCredit>().Ignore(t => t.Id); modelBuilder.Entity<PersonFlightTimeCreditTransaction>().Ignore(t => t.Id); modelBuilder.Entity<PersonPersonCategory>().Ignore(t => t.Id); modelBuilder.Entity<Role>().Ignore(t => t.Id); modelBuilder.Entity<Role>().Ignore(t => t.Name); modelBuilder.Entity<StartType>().Ignore(t => t.Id); modelBuilder.Entity<Setting>().Ignore(t => t.Id); modelBuilder.Entity<User>().Ignore(t => t.Id); modelBuilder.Entity<Aircraft>() .Property(e => e.NoiseLevel) .HasPrecision(18, 1); modelBuilder.Entity<DeliveryItem>() .Property(e => e.Quantity) .HasPrecision(18, 3); modelBuilder.Entity<Aircraft>() .HasMany(e => e.Flights) .WithRequired(e => e.Aircraft) .WillCascadeOnDelete(false); modelBuilder.Entity<Aircraft>() .HasMany(e => e.AircraftReservations) .WithRequired(e => e.Aircraft) .WillCascadeOnDelete(false); modelBuilder.Entity<Aircraft>() .HasMany(e => e.AircraftOperatingCounters) .WithRequired(e => e.Aircraft) .WillCascadeOnDelete(); modelBuilder.Entity<AircraftReservationType>() .HasMany(e => e.AircraftReservations) .WithOptional(e => e.AircraftReservationType) .HasForeignKey(e => e.AircraftReservationTypeId) .WillCascadeOnDelete(false); modelBuilder.Entity<FlightType>() .HasMany(e => e.AircraftReservations) .WithOptional(e => e.FlightType) .HasForeignKey(e => e.FlightTypeId) .WillCascadeOnDelete(false); modelBuilder.Entity<AircraftState>() .HasMany(e => e.AircraftAircraftStates) .WithRequired(e => e.AircraftState) .HasForeignKey(e => e.AircraftStateId); modelBuilder.Entity<AircraftType>() .HasMany(e => e.Aircrafts) .WithRequired(e => e.AircraftType) .HasForeignKey(e => e.AircraftTypeId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.Aircrafts) .WithOptional(e => e.AircraftOwnerClub) .HasForeignKey(e => e.AircraftOwnerClubId); modelBuilder.Entity<Club>() .HasMany(e => e.AircraftReservations) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.AircraftReservationTypes) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.Deliveries) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.DeliveryCreationTests) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.EmailTemplates) .WithOptional(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.AccountingRuleFilters) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.PlanningDays) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.PlanningDayAssignmentTypes) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.ClubExtensions) .WithRequired(e => e.Club) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.FlightTypes) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.Articles) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.Settings) .WithRequired(e => e.Club) .HasForeignKey(e => e.ClubId) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.MemberStates) .WithRequired(e => e.Club) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.PersonCategories) .WithRequired(e => e.Club) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.ClubPersons) .WithRequired(e => e.Club) .WillCascadeOnDelete(false); modelBuilder.Entity<Club>() .HasMany(e => e.Users) .WithRequired(e => e.Club) .WillCascadeOnDelete(false); modelBuilder.Entity<ClubState>() .HasMany(e => e.Clubs) .WithRequired(e => e.ClubState) .HasForeignKey(e => e.ClubStateId) .WillCascadeOnDelete(false); modelBuilder.Entity<Country>() .Property(e => e.CountryCodeIso2) .IsUnicode(false); modelBuilder.Entity<Country>() .HasMany(e => e.Clubs) .WithRequired(e => e.Country) .WillCascadeOnDelete(false); modelBuilder.Entity<Country>() .HasMany(e => e.Locations) .WithRequired(e => e.Country) .WillCascadeOnDelete(false); modelBuilder.Entity<CounterUnitType>() .HasMany(e => e.AircraftFlightOperatingCounters) .WithOptional(e => e.FlightOperatingCounterUnitType) .HasForeignKey(e => e.FlightOperatingCounterUnitTypeId); modelBuilder.Entity<CounterUnitType>() .HasMany(e => e.AircraftEngineOperatingCounters) .WithOptional(e => e.EngineOperatingCounterUnitType) .HasForeignKey(e => e.EngineOperatingCounterUnitTypeId); modelBuilder.Entity<Delivery>() .HasMany(e => e.DeliveryItems) .WithRequired(e => e.Delivery) .HasForeignKey(e => e.DeliveryId) .WillCascadeOnDelete(true); modelBuilder.Entity<Delivery>() .HasMany(e => e.PersonFlightTimeCreditTransactions) .WithOptional(e => e.BalancedDelivery) .HasForeignKey(e => e.BalancedDeliveryId); modelBuilder.Entity<ElevationUnitType>() .HasMany(e => e.Locations) .WithOptional(e => e.ElevationUnitType) .HasForeignKey(e => e.ElevationUnitTypeId); modelBuilder.Entity<Extension>() .HasMany(e => e.ClubExtensions) .WithRequired(e => e.Extension) .WillCascadeOnDelete(false); modelBuilder.Entity<ExtensionType>() .HasMany(e => e.Extensions) .WithRequired(e => e.ExtensionType) .WillCascadeOnDelete(false); modelBuilder.Entity<AccountingRuleFilterType>() .HasMany(e => e.AccountingRuleFilters) .WithRequired(e => e.AccountingRuleFilterType) .WillCascadeOnDelete(false); modelBuilder.Entity<AccountingUnitType>() .HasMany(e => e.AccountingRuleFilters) .WithOptional(e => e.AccountingUnitType) .WillCascadeOnDelete(false); modelBuilder.Entity<FlightCostBalanceType>() .HasMany(e => e.Flights) .WithOptional(e => e.FlightCostBalanceType) .HasForeignKey(e => e.FlightCostBalanceTypeId); modelBuilder.Entity<FlightCrewType>() .HasMany(e => e.FlightCrews) .WithRequired(e => e.FlightCrewType) .HasForeignKey(e => e.FlightCrewTypeId) .WillCascadeOnDelete(false); modelBuilder.Entity<Flight>() .HasMany(e => e.FlightCrews) .WithRequired(e => e.Flight) .HasForeignKey(e => e.FlightId) .WillCascadeOnDelete(false); modelBuilder.Entity<Flight>() .HasMany(e => e.Deliveries) .WithOptional(e => e.Flight) .HasForeignKey(e => e.FlightId) .WillCascadeOnDelete(false); modelBuilder.Entity<Flight>() .HasMany(e => e.DeliveryCreationTests) .WithRequired(e => e.Flight) .HasForeignKey(e => e.FlightId) .WillCascadeOnDelete(false); modelBuilder.Entity<FlightCrew>() .HasRequired(e => e.Flight); modelBuilder.Entity<Flight>() .HasMany(e => e.TowedFlights) .WithOptional(e => e.TowFlight) .HasForeignKey(e => e.TowFlightId); modelBuilder.Entity<FlightAirState>() .HasMany(e => e.Flights) .WithRequired(e => e.FlightAirState) .HasForeignKey(e => e.AirStateId) .WillCascadeOnDelete(false); modelBuilder.Entity<FlightProcessState>() .HasMany(e => e.Flights) .WithRequired(e => e.FlightProcessState) .HasForeignKey(e => e.ProcessStateId) .WillCascadeOnDelete(false); modelBuilder.Entity<FlightType>() .HasMany(e => e.ClubsDefaultGliderFlightType) .WithOptional(e => e.DefaultGliderFlightType) .HasForeignKey(e => e.DefaultGliderFlightTypeId); modelBuilder.Entity<FlightType>() .HasMany(e => e.ClubsDefaultMotorFlightType) .WithOptional(e => e.DefaultMotorFlightType) .HasForeignKey(e => e.DefaultMotorFlightTypeId); modelBuilder.Entity<FlightType>() .HasMany(e => e.ClubsDefaultTowFlightType) .WithOptional(e => e.DefaultTowFlightType) .HasForeignKey(e => e.DefaultTowFlightTypeId); modelBuilder.Entity<Language>() .HasMany(e => e.LanguageTranslations) .WithRequired(e => e.Language) .HasForeignKey(e => e.LanguageId) .WillCascadeOnDelete(false); modelBuilder.Entity<Language>() .HasMany(e => e.Users) .WithRequired(e => e.Language) .HasForeignKey(e => e.LanguageId) .WillCascadeOnDelete(false); modelBuilder.Entity<Language>() .HasMany(e => e.EmailTemplates) .WithRequired(e => e.Language) .HasForeignKey(e => e.LanguageId) .WillCascadeOnDelete(false); modelBuilder.Entity<LengthUnitType>() .HasMany(e => e.Locations) .WithOptional(e => e.LengthUnitType) .HasForeignKey(e => e.RunwayLengthUnitType); modelBuilder.Entity<Location>() .HasMany(e => e.Clubs) .WithOptional(e => e.Homebase) .HasForeignKey(e => e.HomebaseId); modelBuilder.Entity<Location>() .HasMany(e => e.HomebasedAircrafts) .WithOptional(e => e.Homebase) .HasForeignKey(e => e.HomebaseId); modelBuilder.Entity<Location>() .HasMany(e => e.LandedFlights) .WithOptional(e => e.LdgLocation) .HasForeignKey(e => e.LdgLocationId); modelBuilder.Entity<Location>() .HasMany(e => e.StartedFlights) .WithOptional(e => e.StartLocation) .HasForeignKey(e => e.StartLocationId); modelBuilder.Entity<Location>() .HasMany(e => e.InOutboundPoints) .WithRequired(e => e.Location) .WillCascadeOnDelete(false); modelBuilder.Entity<Location>() .HasMany(e => e.PlanningDays) .WithRequired(e => e.Location) .HasForeignKey(e => e.LocationId); modelBuilder.Entity<Location>() .HasMany(e => e.AircraftReservations) .WithRequired(e => e.Location) .HasForeignKey(e => e.LocationId) .WillCascadeOnDelete(false); modelBuilder.Entity<LocationType>() .HasMany(e => e.Locations) .WithRequired(e => e.LocationType) .WillCascadeOnDelete(false); modelBuilder.Entity<MemberState>() .HasMany(e => e.PersonClubs) .WithOptional(e => e.MemberState) .HasForeignKey(e => e.MemberStateId); modelBuilder.Entity<PersonCategory>() .HasMany(e => e.ChildPersonCategories) .WithOptional(e => e.ParentPersonCategory) .HasForeignKey(e => e.ParentPersonCategoryId); modelBuilder.Entity<Person>() .HasMany(e => e.ReportedAircraftAircraftStates) .WithOptional(e => e.NoticedByPerson) .HasForeignKey(e => e.NoticedByPersonId) .WillCascadeOnDelete(); modelBuilder.Entity<Person>() .HasMany(e => e.OwnedAircrafts) .WithOptional(e => e.AircraftOwnerPerson) .HasForeignKey(e => e.AircraftOwnerPersonId); modelBuilder.Entity<Person>() .HasMany(e => e.FlightCrews) .WithRequired(e => e.Person) .WillCascadeOnDelete(false); modelBuilder.Entity<Person>() .HasMany(e => e.PersonClubs) .WithRequired(e => e.Person) .WillCascadeOnDelete(false); modelBuilder.Entity<Person>() .HasMany(e => e.AircraftReservations) .WithRequired(e => e.PilotPerson) .HasForeignKey(e => e.PilotPersonId) .WillCascadeOnDelete(false); modelBuilder.Entity<Person>() .HasMany(e => e.SecondCrewAssignedAircraftReservations) .WithOptional(e => e.SecondCrewPerson) .HasForeignKey(e => e.SecondCrewPersonId); modelBuilder.Entity<Person>() .HasMany(e => e.PlanningDayAssignments) .WithRequired(e => e.AssignedPerson) .HasForeignKey(e => e.AssignedPersonId); modelBuilder.Entity<Person>() .HasMany(e => e.PersonFlightTimeCredits) .WithRequired(e => e.Person) .HasForeignKey(e => e.PersonId); modelBuilder.Entity<PersonFlightTimeCredit>() .HasMany(e => e.PersonFlightTimeCreditTransactions) .WithRequired(e => e.PersonFlightTimeCredit) .HasForeignKey(e => e.PersonFlightTimeCreditId); modelBuilder.Entity<PlanningDay>() .HasMany(e => e.PlanningDayAssignments) .WithRequired(e => e.AssignedPlanningDay) .HasForeignKey(e => e.AssignedPlanningDayId); modelBuilder.Entity<PlanningDayAssignmentType>() .HasMany(e => e.PlanningDayAssignments) .WithRequired(e => e.AssignmentType) .HasForeignKey(e => e.AssignmentTypeId); modelBuilder.Entity<StartType>() .HasMany(e => e.Clubs) .WithOptional(e => e.DefaultStartType) .HasForeignKey(e => e.DefaultStartTypeId); modelBuilder.Entity<StartType>() .HasMany(e => e.Flights) .WithOptional(e => e.StartType) .HasForeignKey(e => e.StartTypeId); modelBuilder.Entity<SystemLog>() .Property(e => e.Exception) .IsUnicode(false); modelBuilder.Entity<SystemLog>() .Property(e => e.Stacktrace) .IsUnicode(false); modelBuilder.Entity<UserAccountState>() .HasMany(e => e.Users) .WithRequired(e => e.UserAccountState) .HasForeignKey(e => e.AccountState) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.Settings) .WithRequired(e => e.User) .HasForeignKey(e => e.UserId) .WillCascadeOnDelete(false); SetIsDeletedMapping(modelBuilder, false); #region Audit Tracking Settings //For more details, see: https://github.com/bilal-fazlani/tracker-enabled-dbcontext/wiki EntityTracker.TrackAllProperties<AircraftAircraftState>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Aircraft>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<AircraftOperatingCounter>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<AircraftReservation>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<AircraftReservationType>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Article>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Club>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Delivery>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<DeliveryCreationTest>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<DeliveryItem>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<EmailTemplate>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<FlightCrew>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Flight>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState) .And(x => x.FlightAircraftType); EntityTracker.TrackAllProperties<FlightType>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<InOutboundPoint>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<AccountingRuleFilter>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Location>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<MemberState>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<PersonCategory>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<PersonClub>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<PersonPersonCategory>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<PersonFlightTimeCredit>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<PlanningDay>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<PlanningDayAssignment>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<PlanningDayAssignmentType>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Person>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Role>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<Setting>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); EntityTracker.TrackAllProperties<UserRole>(); EntityTracker.TrackAllProperties<User>().Except(x => x.Id) .And(x => x.CreatedByUserId) .And(x => x.CreatedOn) .And(x => x.ModifiedByUserId) .And(x => x.ModifiedOn) .And(x => x.DeletedByUserId) .And(x => x.DeletedOn) .And(x => x.OwnerId) .And(x => x.OwnershipType) .And(x => x.RecordState); #endregion Audit Tracking Settings } /// <summary> /// Sets the deleted filter to not return deleted objects to the object mapper. /// </summary> /// <param name="modelBuilder"></param> /// <param name="isDeleted"></param> protected virtual void SetIsDeletedMapping(DbModelBuilder modelBuilder, bool isDeleted) { #region Soft-Delete settings //Soft-Delete modelBuilder.Entity<AccountingRuleFilter>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Aircraft>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<AircraftOperatingCounter>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<AircraftReservation>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<AircraftReservationType>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Article>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Club>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<ClubExtension>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Country>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Delivery>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<DeliveryItem>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<DeliveryCreationTest>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<EmailTemplate>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Extension>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<ExtensionValue>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Flight>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<FlightCrew>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<FlightType>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<InOutboundPoint>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Location>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<LocationType>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<MemberState>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<PlanningDay>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<PlanningDayAssignment>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<PlanningDayAssignmentType>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Person>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<PersonCategory>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<PersonClub>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Role>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<User>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); modelBuilder.Entity<Setting>() .Map(m => m.Requires("IsDeleted").HasValue(isDeleted)) .Ignore(m => m.IsDeleted); #endregion Soft-Delete settings } public override Task<int> SaveChangesAsync() { try { PrepareEntitiesForSave(); return base.SaveChangesAsync(_identityService.CurrentAuthenticatedFLSUser?.UserName); } catch (DbEntityValidationException ex) { StringBuilder sb = new StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } Logger.Error(ex, $"DbEntityValidationException: {sb}"); throw new DatabaseException(ErrorMessage.DbEntityValidationException, ex); // Add the original exception as the innerException } catch (Exception ex) { var message = ex.Message; if (ex.InnerException != null) { message += $" InnerException: {ex.InnerException.Message}"; if (ex.InnerException.InnerException != null) { message += $" InnerException: {ex.InnerException.InnerException.Message}"; } } Logger.Error(ex, $"Error while trying to save entity changes: {message}"); throw new DatabaseException(ErrorMessage.GeneralDatabaseException, ex); // Add the original exception as the innerException } } public override int SaveChanges() { int changes = 0; try { PrepareEntitiesForSave(); changes = base.SaveChanges(_identityService.CurrentAuthenticatedFLSUser?.UserName); } catch (DbEntityValidationException ex) { StringBuilder sb = new StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } Logger.Error(ex, $"DbEntityValidationException: {sb}"); throw new DatabaseException(ErrorMessage.DbEntityValidationException, ex); // Add the original exception as the innerException } catch (Exception ex) { var message = ex.Message; var innerException = ex.InnerException; while (innerException != null) { message += $" InnerException: {innerException.Message}"; innerException = innerException.InnerException; } Logger.Error(ex, $"Error while trying to save entity changes: {message}"); throw new DatabaseException(ErrorMessage.GeneralDatabaseException, ex); // Add the original exception as the innerException } return changes; } private void PrepareEntitiesForSave() { foreach (var entry in ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Modified || p.State == EntityState.Deleted)) { if ((entry.Entity.GetType() == typeof(Flight) && ((Flight) entry.Entity).DoNotUpdateMetaData) || (entry.Entity.GetType() == typeof(User) && ((User) entry.Entity).DoNotUpdateMetaData)) { //check next entry } else { //we found an entry which requires the UserId, so we check the authentication values if (_identityService.CurrentAuthenticatedFLSUser == null) { Logger.Error("Could not save entities as no user is authenticated."); throw new AuthenticationException(ErrorMessage.UserNotAuthenticated); } break; } } //https://lostechies.com/jimmybogard/2014/05/08/missing-ef-feature-workarounds-cascade-delete-orphans/ foreach (var orphan in FlightCrews.Local.Where(a => a.Flight == null).ToList()) { FlightCrews.Remove(orphan); } foreach (var orphan in PlanningDayAssignments.Local.Where(a => a.AssignedPlanningDay == null).ToList()) { PlanningDayAssignments.Remove(orphan); } foreach (var orphan in PersonClubs.Local.Where(a => a.Person == null).ToList()) { PersonClubs.Remove(orphan); } #region Added Entities foreach (var entry in ChangeTracker.Entries().Where(p => p.State == EntityState.Added)) { try { var flsEntity = entry.Entity as IFLSMetaData; if (flsEntity != null) { if (flsEntity.Id == Guid.Empty) { flsEntity.SetPropertyValue("Id", Guid.NewGuid()); } if ((entry.Entity.GetType() == typeof(Person) && ((Person) entry.Entity).DoNotUpdateTimeStampsInMetaData) || (entry.Entity.GetType() == typeof(PersonClub) && ((PersonClub) entry.Entity).DoNotUpdateTimeStampsInMetaData)) { //don't update created on metadata } else { flsEntity.SetPropertyValue("CreatedOn", DateTime.UtcNow); } flsEntity.SetPropertyValue("CreatedByUserId", _identityService.CurrentAuthenticatedFLSUser.UserId); flsEntity.SetPropertyValue("OwnerId", _identityService.CurrentAuthenticatedFLSUser.ClubId); flsEntity.SetPropertyValue("OwnershipType", (int) OwnershipType.Club); flsEntity.SetPropertyValue("RecordState", (int) EntityRecordState.Active); Logger.Debug($"Insert {entry.Entity.GetType().Name} with data: {entry.Entity}"); } else if (entry.Entity is UserRole) { Logger.Debug($"Insert {entry.Entity.GetType().Name} with data: {entry.Entity}"); } } catch (Exception ex) { Logger.Error(ex, $"Error while trying to save new FLSDataEntities. Error: {ex.Message}"); throw; } } #endregion Added Entities #region Modified Entities foreach (var entry in ChangeTracker.Entries().Where(p => p.State == EntityState.Modified)) { try { var flsEntity = entry.Entity as IFLSMetaData; if (flsEntity != null) { if ((entry.Entity.GetType() == typeof(Flight) && ((Flight) entry.Entity).DoNotUpdateMetaData) || (entry.Entity.GetType() == typeof(User) && ((User) entry.Entity).DoNotUpdateMetaData) || (entry.Entity.GetType() == typeof(Club) && ((Club) entry.Entity).DoNotUpdateMetaData)) { //don't update metadata when workflow process set flag "DoNotUpdateMetaData" on flight //or when user resets passwords flsEntity.SetPropertyValue("RecordState", (int) EntityRecordState.Active); Logger.Debug($"Update {entry.Entity.GetType().Name} with data: {entry.Entity}"); continue; } var userId = _identityService.CurrentAuthenticatedFLSUser.UserId; if ((entry.Entity.GetType() == typeof(Person) && ((Person) entry.Entity).DoNotUpdateTimeStampsInMetaData) || (entry.Entity.GetType() == typeof(PersonClub) && ((PersonClub) entry.Entity).DoNotUpdateTimeStampsInMetaData)) { //don't update modified on metadata } else { flsEntity.SetPropertyValue("ModifiedOn", DateTime.UtcNow); } flsEntity.SetPropertyValue("ModifiedByUserId", userId); flsEntity.SetPropertyValue("RecordState", (int) EntityRecordState.Active); Logger.Debug($"Update {entry.Entity.GetType().Name} with data: {entry.Entity}"); } } catch (Exception ex) { Logger.Error(ex, $"Error while trying to update FLSDataEntities. Error: {ex.Message}"); throw; } } #endregion Modified Entities #region Deleted Entities foreach (var entry in ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted)) { try { var flsEntity = entry.Entity as IFLSMetaData; if (flsEntity != null) { var userId = _identityService.CurrentAuthenticatedFLSUser.UserId; if ((entry.Entity.GetType() == typeof(Person) && ((Person) entry.Entity).DoNotUpdateTimeStampsInMetaData) || (entry.Entity.GetType() == typeof(PersonClub) && ((PersonClub) entry.Entity).DoNotUpdateTimeStampsInMetaData)) { //don't update deleted on metadata } else { flsEntity.SetPropertyValue("DeletedOn", DateTime.UtcNow); } flsEntity.SetPropertyValue("DeletedByUserId", userId); flsEntity.SetPropertyValue("RecordState", (int) EntityRecordState.Deleted); Logger.Debug($"Delete {entry.Entity.GetType().Name} with Data: {entry.Entity}"); } else if (entry.Entity is UserRole) { Logger.Debug($"Delete {entry.Entity.GetType().Name} with data: {entry.Entity}"); } SoftDelete(entry); } catch (Exception ex) { Logger.Error(ex, $"Error while trying to delete FLSDataEntities. Error: {ex.Message}"); throw; } } #endregion Deleted Entities } #region SoftDelete private void SoftDelete(DbEntityEntry entry) { Type entryEntityType = entry.Entity.GetType(); if (entryEntityType.Name == "UserRole") { //Hard delete user role entries, as we do not have unique key for re-insert a same role return; } try { if (entry.Entity.HasProperty("IsDeleted")) { string tableName = GetTableName(entryEntityType); string primaryKeyName = GetPrimaryKeyName(entryEntityType); DateTime? deletedOn = null; Guid? deletedByUserId = null; string sql = string.Format( "UPDATE {0} SET DeletedOn = @deletedOn, DeletedByUserId = @deletedByUserId, RecordState = @recordState, IsDeleted = 1 WHERE {1} = @id", tableName, primaryKeyName); var flsEntity = entry.Entity as IFLSMetaData; if (flsEntity != null) { deletedOn = flsEntity.DeletedOn; deletedByUserId = flsEntity.DeletedByUserId; } Database.ExecuteSqlCommand( sql, new SqlParameter("@id", entry.OriginalValues[primaryKeyName]), new SqlParameter("@deletedOn", deletedOn), new SqlParameter("@deletedByUserId", deletedByUserId), new SqlParameter("@recordState", (int) EntityRecordState.Deleted)); // prevent hard delete and change state to Detached (not modified as modified will reattach it back to the client entry.State = EntityState.Detached; } } catch (Exception ex) { Logger.Error(ex); throw new DatabaseException(ErrorMessage.SoftDeleteDatabaseException); } } private static Dictionary<Type, EntitySetBase> _mappingCache = new Dictionary<Type, EntitySetBase>(); private string GetTableName(Type type) { EntitySetBase es = GetEntitySet(type); return string.Format("[{0}].[{1}]", es.MetadataProperties["Schema"].Value, es.MetadataProperties["Table"].Value); } private string GetPrimaryKeyName(Type type) { EntitySetBase es = GetEntitySet(type); return es.ElementType.KeyMembers[0].Name; } private EntitySetBase GetEntitySet(Type type) { if (!_mappingCache.ContainsKey(type)) { ObjectContext octx = ((IObjectContextAdapter)this).ObjectContext; string typeName = ObjectContext.GetObjectType(type).Name; var es = octx.MetadataWorkspace .GetItemCollection(DataSpace.SSpace) .GetItems<EntityContainer>() .SelectMany(c => c.BaseEntitySets .Where(e => e.Name == typeName)) .FirstOrDefault(); if (es == null) throw new ArgumentException("Entity type not found in GetTableName", typeName); _mappingCache.Add(type, es); } return _mappingCache[type]; } #endregion SoftDelete } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="CustomerNegativeCriterionServiceClient"/> instances.</summary> public sealed partial class CustomerNegativeCriterionServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CustomerNegativeCriterionServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CustomerNegativeCriterionServiceSettings"/>.</returns> public static CustomerNegativeCriterionServiceSettings GetDefault() => new CustomerNegativeCriterionServiceSettings(); /// <summary> /// Constructs a new <see cref="CustomerNegativeCriterionServiceSettings"/> object with default settings. /// </summary> public CustomerNegativeCriterionServiceSettings() { } private CustomerNegativeCriterionServiceSettings(CustomerNegativeCriterionServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetCustomerNegativeCriterionSettings = existing.GetCustomerNegativeCriterionSettings; MutateCustomerNegativeCriteriaSettings = existing.MutateCustomerNegativeCriteriaSettings; OnCopy(existing); } partial void OnCopy(CustomerNegativeCriterionServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerNegativeCriterionServiceClient.GetCustomerNegativeCriterion</c> and /// <c>CustomerNegativeCriterionServiceClient.GetCustomerNegativeCriterionAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetCustomerNegativeCriterionSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerNegativeCriterionServiceClient.MutateCustomerNegativeCriteria</c> and /// <c>CustomerNegativeCriterionServiceClient.MutateCustomerNegativeCriteriaAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCustomerNegativeCriteriaSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CustomerNegativeCriterionServiceSettings"/> object.</returns> public CustomerNegativeCriterionServiceSettings Clone() => new CustomerNegativeCriterionServiceSettings(this); } /// <summary> /// Builder class for <see cref="CustomerNegativeCriterionServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class CustomerNegativeCriterionServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerNegativeCriterionServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CustomerNegativeCriterionServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CustomerNegativeCriterionServiceClientBuilder() { UseJwtAccessWithScopes = CustomerNegativeCriterionServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CustomerNegativeCriterionServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerNegativeCriterionServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CustomerNegativeCriterionServiceClient Build() { CustomerNegativeCriterionServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CustomerNegativeCriterionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CustomerNegativeCriterionServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CustomerNegativeCriterionServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CustomerNegativeCriterionServiceClient.Create(callInvoker, Settings); } private async stt::Task<CustomerNegativeCriterionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CustomerNegativeCriterionServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CustomerNegativeCriterionServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerNegativeCriterionServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerNegativeCriterionServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CustomerNegativeCriterionService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage customer negative criteria. /// </remarks> public abstract partial class CustomerNegativeCriterionServiceClient { /// <summary> /// The default endpoint for the CustomerNegativeCriterionService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CustomerNegativeCriterionService scopes.</summary> /// <remarks> /// The default CustomerNegativeCriterionService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CustomerNegativeCriterionServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CustomerNegativeCriterionServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CustomerNegativeCriterionServiceClient"/>.</returns> public static stt::Task<CustomerNegativeCriterionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CustomerNegativeCriterionServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CustomerNegativeCriterionServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CustomerNegativeCriterionServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CustomerNegativeCriterionServiceClient"/>.</returns> public static CustomerNegativeCriterionServiceClient Create() => new CustomerNegativeCriterionServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CustomerNegativeCriterionServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CustomerNegativeCriterionServiceSettings"/>.</param> /// <returns>The created <see cref="CustomerNegativeCriterionServiceClient"/>.</returns> internal static CustomerNegativeCriterionServiceClient Create(grpccore::CallInvoker callInvoker, CustomerNegativeCriterionServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient grpcClient = new CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient(callInvoker); return new CustomerNegativeCriterionServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CustomerNegativeCriterionService client</summary> public virtual CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(GetCustomerNegativeCriterionRequest request, st::CancellationToken cancellationToken) => GetCustomerNegativeCriterionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerNegativeCriterion(new GetCustomerNegativeCriterionRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerNegativeCriterionAsync(new GetCustomerNegativeCriterionRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(string resourceName, st::CancellationToken cancellationToken) => GetCustomerNegativeCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(gagvr::CustomerNegativeCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerNegativeCriterion(new GetCustomerNegativeCriterionRequest { ResourceNameAsCustomerNegativeCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(gagvr::CustomerNegativeCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerNegativeCriterionAsync(new GetCustomerNegativeCriterionRequest { ResourceNameAsCustomerNegativeCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(gagvr::CustomerNegativeCriterionName resourceName, st::CancellationToken cancellationToken) => GetCustomerNegativeCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerNegativeCriteriaResponse MutateCustomerNegativeCriteria(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(MutateCustomerNegativeCriteriaRequest request, st::CancellationToken cancellationToken) => MutateCustomerNegativeCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose criteria are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual criteria. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerNegativeCriteriaResponse MutateCustomerNegativeCriteria(string customerId, scg::IEnumerable<CustomerNegativeCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerNegativeCriteria(new MutateCustomerNegativeCriteriaRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose criteria are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual criteria. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(string customerId, scg::IEnumerable<CustomerNegativeCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerNegativeCriteriaAsync(new MutateCustomerNegativeCriteriaRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose criteria are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual criteria. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(string customerId, scg::IEnumerable<CustomerNegativeCriterionOperation> operations, st::CancellationToken cancellationToken) => MutateCustomerNegativeCriteriaAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CustomerNegativeCriterionService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage customer negative criteria. /// </remarks> public sealed partial class CustomerNegativeCriterionServiceClientImpl : CustomerNegativeCriterionServiceClient { private readonly gaxgrpc::ApiCall<GetCustomerNegativeCriterionRequest, gagvr::CustomerNegativeCriterion> _callGetCustomerNegativeCriterion; private readonly gaxgrpc::ApiCall<MutateCustomerNegativeCriteriaRequest, MutateCustomerNegativeCriteriaResponse> _callMutateCustomerNegativeCriteria; /// <summary> /// Constructs a client wrapper for the CustomerNegativeCriterionService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="CustomerNegativeCriterionServiceSettings"/> used within this client. /// </param> public CustomerNegativeCriterionServiceClientImpl(CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient grpcClient, CustomerNegativeCriterionServiceSettings settings) { GrpcClient = grpcClient; CustomerNegativeCriterionServiceSettings effectiveSettings = settings ?? CustomerNegativeCriterionServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetCustomerNegativeCriterion = clientHelper.BuildApiCall<GetCustomerNegativeCriterionRequest, gagvr::CustomerNegativeCriterion>(grpcClient.GetCustomerNegativeCriterionAsync, grpcClient.GetCustomerNegativeCriterion, effectiveSettings.GetCustomerNegativeCriterionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetCustomerNegativeCriterion); Modify_GetCustomerNegativeCriterionApiCall(ref _callGetCustomerNegativeCriterion); _callMutateCustomerNegativeCriteria = clientHelper.BuildApiCall<MutateCustomerNegativeCriteriaRequest, MutateCustomerNegativeCriteriaResponse>(grpcClient.MutateCustomerNegativeCriteriaAsync, grpcClient.MutateCustomerNegativeCriteria, effectiveSettings.MutateCustomerNegativeCriteriaSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCustomerNegativeCriteria); Modify_MutateCustomerNegativeCriteriaApiCall(ref _callMutateCustomerNegativeCriteria); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetCustomerNegativeCriterionApiCall(ref gaxgrpc::ApiCall<GetCustomerNegativeCriterionRequest, gagvr::CustomerNegativeCriterion> call); partial void Modify_MutateCustomerNegativeCriteriaApiCall(ref gaxgrpc::ApiCall<MutateCustomerNegativeCriteriaRequest, MutateCustomerNegativeCriteriaResponse> call); partial void OnConstruction(CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient grpcClient, CustomerNegativeCriterionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CustomerNegativeCriterionService client</summary> public override CustomerNegativeCriterionService.CustomerNegativeCriterionServiceClient GrpcClient { get; } partial void Modify_GetCustomerNegativeCriterionRequest(ref GetCustomerNegativeCriterionRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateCustomerNegativeCriteriaRequest(ref MutateCustomerNegativeCriteriaRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::CustomerNegativeCriterion GetCustomerNegativeCriterion(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCustomerNegativeCriterionRequest(ref request, ref callSettings); return _callGetCustomerNegativeCriterion.Sync(request, callSettings); } /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::CustomerNegativeCriterion> GetCustomerNegativeCriterionAsync(GetCustomerNegativeCriterionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCustomerNegativeCriterionRequest(ref request, ref callSettings); return _callGetCustomerNegativeCriterion.Async(request, callSettings); } /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCustomerNegativeCriteriaResponse MutateCustomerNegativeCriteria(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerNegativeCriteriaRequest(ref request, ref callSettings); return _callMutateCustomerNegativeCriteria.Sync(request, callSettings); } /// <summary> /// Creates or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCustomerNegativeCriteriaResponse> MutateCustomerNegativeCriteriaAsync(MutateCustomerNegativeCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerNegativeCriteriaRequest(ref request, ref callSettings); return _callMutateCustomerNegativeCriteria.Async(request, callSettings); } } }
//--------------------------------------------------------------------- // Author: jachymko // // Description: Pings machines asynchronously. // // Creation date: Dec 14, 2006 //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Management.Automation; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; namespace Pscx.Commands.Net { internal sealed class PingExecutorAsync : PingExecutor { private readonly Queue<ErrorRecord> errors = new Queue<ErrorRecord>(); private readonly ManualResetEvent done = new ManualResetEvent(false); private readonly object syncRoot = new object(); private int remainingItems = 0; public PingExecutorAsync(PingHostCommand command) : base(command) { } public override void Dispose() { done.Set(); done.Close(); } internal override void BeginProcessing() { done.Reset(); errors.Clear(); } internal override void EndProcessing() { done.WaitOne(); if (!Command.Stopping) { foreach(ErrorRecord record in errors) { Command.WriteError(record); } Command.WriteObject(Statistics, true); } } internal override void StopProcessing() { Dispose(); } internal override void WriteInfo(PingHostInfo result) { lock (syncRoot) { Statistics.Add(result); } DecrementItemCount(); } internal override void WriteStatistics(IPAddress address) { ; } internal override void Send(string hostOrAddress, bool tryResolve) { if (tryResolve) { IncrementItemCount(); Dns.BeginGetHostEntry(hostOrAddress, OnGetHostEntryCompleted, hostOrAddress); } else { IPAddress address; if (IPAddress.TryParse(hostOrAddress, out address)) { Send(address, false); } else { IncrementItemCount(); errors.Enqueue(PscxErrorRecord.InvalidIPAddress(hostOrAddress)); DecrementItemCount(); } } } internal override void Send(IPAddress address, bool tryResolve) { if (tryResolve) { IncrementItemCount(); Dns.BeginGetHostEntry(address, OnGetHostEntryCompleted, address); } else { IncrementItemCount(new PingTaskAsync(this, address).SendAsync()); } } internal override void Send(IPHostEntry host) { IncrementItemCount(new PingTaskAsync(this, host).SendAsync()); } private void OnGetHostEntryCompleted(IAsyncResult ar) { IPHostEntry entry = null; SocketException error = null; try { try { entry = Dns.EndGetHostEntry(ar); } catch (SocketException exc) { error = exc; } if (entry != null) { Send(entry); } else { String str = ar.AsyncState as String; IPAddress address = ar.AsyncState as IPAddress; if ((address != null) || ((str != null) && IPAddress.TryParse(str, out address))) { Send(address, false); } else { errors.Enqueue(PscxErrorRecord.GetHostEntryError(ar.AsyncState.ToString(), error)); } } } finally { DecrementItemCount(); } } private void IncrementItemCount(int value) { Interlocked.Add(ref remainingItems, value); } private void IncrementItemCount() { Interlocked.Increment(ref remainingItems); } private void DecrementItemCount() { if(Interlocked.Decrement(ref remainingItems) <= 0) { done.Set(); } } } internal sealed class PingTaskAsync : PingTaskBase { public PingTaskAsync(PingExecutorAsync exec, IPHostEntry host) : base(exec, host) { } public PingTaskAsync(PingExecutorAsync exec, IPAddress address) : base (exec, address) { } public int SendAsync() { foreach (IPAddress ip in Addresses) { Ping ping = new Ping(); ping.PingCompleted += new PingCompletedEventHandler(OnPingCompleted); PingTaskState state = new PingTaskState(ping, ip, Count); SendAsyncInternal(state); } return Addresses.Length * Count; } private void SendAsyncInternal(PingTaskState state) { if (Executor.Command.Stopping) return; state.RemainingCount--; state.Ping.SendAsync(state.IPAddress, Timeout, Buffer, PingOptions, state); } private void OnPingCompleted(object sender, PingCompletedEventArgs e) { PingTaskState state = e.UserState as PingTaskState; if (state != null) { if (e.Cancelled || Executor.Command.Stopping) { state.Ping.Dispose(); return; } PingHostInfo result = new PingHostInfo(this, state.IPAddress, e.Reply, e.Error, Buffer.Length); Executor.WriteInfo(result); if (state.RemainingCount == 0) { state.Ping.Dispose(); } else { SendAsyncInternal(state); } } } private sealed class PingTaskState { public PingTaskState(Ping p, IPAddress ip, int count) { this.Ping = p; this.IPAddress = ip; this.RemainingCount = count; } public readonly Ping Ping; public readonly IPAddress IPAddress; public int RemainingCount; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Xml.Schema { using System; using System.Threading; using System.Collections; using Microsoft.Xml.Schema; using System.Runtime.Versioning; /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection"]/*' /> /// <devdoc> /// <para>The XmlSchemaCollection contains a set of namespace URI's. /// Each namespace also have an associated private data cache /// corresponding to the XML-Data Schema or W3C XML Schema. /// The XmlSchemaCollection will able to load XSD and XDR schemas, /// and compile them into an internal "cooked schema representation". /// The Validate method then uses this internal representation for /// efficient runtime validation of any given subtree.</para> /// </devdoc> [Obsolete("Use Microsoft.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")] public sealed class XmlSchemaCollection : ICollection { private Hashtable _collection; private XmlNameTable _nameTable; private SchemaNames _schemaNames; private ReaderWriterLockSlim _wLock; private int _timeout = Timeout.Infinite; private bool _isThreadSafe = true; private ValidationEventHandler _validationEventHandler = null; private XmlResolver _xmlResolver = null; /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.XmlSchemaCollection"]/*' /> /// <devdoc> /// <para>Construct a new empty schema collection.</para> /// </devdoc> public XmlSchemaCollection() : this(new NameTable()) { } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.XmlSchemaCollection1"]/*' /> /// <devdoc> /// <para>Construct a new empty schema collection with associated XmlNameTable. /// The XmlNameTable is used when loading schemas</para> /// </devdoc> public XmlSchemaCollection(XmlNameTable nametable) { if (nametable == null) { throw new ArgumentNullException("nametable"); } _nameTable = nametable; _collection = Hashtable.Synchronized(new Hashtable()); _xmlResolver = Microsoft.Xml.XmlConfiguration.XmlReaderSection.CreateDefaultResolver(); _isThreadSafe = true; if (_isThreadSafe) { _wLock = new ReaderWriterLockSlim(); } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Count"]/*' /> /// <devdoc> /// <para>Returns the number of namespaces defined in this collection /// (whether or not there is an actual schema associated with those namespaces or not).</para> /// </devdoc> public int Count { get { return _collection.Count; } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.NameTable"]/*' /> /// <devdoc> /// <para>The default XmlNameTable used by the XmlSchemaCollection when loading new schemas.</para> /// </devdoc> public XmlNameTable NameTable { get { return _nameTable; } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ValidationEventHandler"]/*' /> public event ValidationEventHandler ValidationEventHandler { add { _validationEventHandler += value; } remove { _validationEventHandler -= value; } } internal XmlResolver XmlResolver { set { _xmlResolver = value; } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add"]/*' /> /// <devdoc> /// <para>Add the schema located by the given URL into the schema collection. /// If the given schema references other namespaces, the schemas for those other /// namespaces are NOT automatically loaded.</para> /// </devdoc> // [ResourceConsumption(ResourceScope.Machine)] // [ResourceExposure(ResourceScope.Machine)] public XmlSchema Add(string ns, string uri) { if (uri == null || uri.Length == 0) throw new ArgumentNullException("uri"); XmlTextReader reader = new XmlTextReader(uri, _nameTable); reader.XmlResolver = _xmlResolver; XmlSchema schema = null; try { schema = Add(ns, reader, _xmlResolver); while (reader.Read()) ;// wellformness check } finally { reader.Close(); } return schema; } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add4"]/*' /> public XmlSchema Add(String ns, XmlReader reader) { return Add(ns, reader, _xmlResolver); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add1"]/*' /> /// <devdoc> /// <para>Add the given schema into the schema collection. /// If the given schema references other namespaces, the schemas for those /// other namespaces are NOT automatically loaded.</para> /// </devdoc> public XmlSchema Add(String ns, XmlReader reader, XmlResolver resolver) { if (reader == null) throw new ArgumentNullException("reader"); XmlNameTable readerNameTable = reader.NameTable; SchemaInfo schemaInfo = new SchemaInfo(); Parser parser = new Parser(SchemaType.None, readerNameTable, GetSchemaNames(readerNameTable), _validationEventHandler); parser.XmlResolver = resolver; SchemaType schemaType; try { schemaType = parser.Parse(reader, ns); } catch (XmlSchemaException e) { SendValidationEvent(e); return null; } if (schemaType == SchemaType.XSD) { schemaInfo.SchemaType = SchemaType.XSD; return Add(ns, schemaInfo, parser.XmlSchema, true, resolver); } else { SchemaInfo xdrSchema = parser.XdrSchema; return Add(ns, parser.XdrSchema, null, true, resolver); } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchema Add(XmlSchema schema) { return Add(schema, _xmlResolver); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add5"]/*' /> public XmlSchema Add(XmlSchema schema, XmlResolver resolver) { if (schema == null) throw new ArgumentNullException("schema"); SchemaInfo schemaInfo = new SchemaInfo(); schemaInfo.SchemaType = SchemaType.XSD; return Add(schema.TargetNamespace, schemaInfo, schema, true, resolver); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add3"]/*' /> /// <devdoc> /// <para>Adds all the namespaces defined in the given collection /// (including their associated schemas) to this collection.</para> /// </devdoc> public void Add(XmlSchemaCollection schema) { if (schema == null) throw new ArgumentNullException("schema"); if (this == schema) return; IDictionaryEnumerator enumerator = schema._collection.GetEnumerator(); while (enumerator.MoveNext()) { XmlSchemaCollectionNode node = (XmlSchemaCollectionNode)enumerator.Value; Add(node.NamespaceURI, node); } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.this"]/*' /> /// <devdoc> /// <para>Looks up the schema by it's associated namespace URI</para> /// </devdoc> public XmlSchema this[string ns] { get { XmlSchemaCollectionNode node = (XmlSchemaCollectionNode)_collection[(ns != null) ? ns : string.Empty]; return (node != null) ? node.Schema : null; } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Contains"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(XmlSchema schema) { if (schema == null) { throw new ArgumentNullException("schema"); } return this[schema.TargetNamespace] != null; } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Contains1"]/*' /> public bool Contains(string ns) { return _collection[(ns != null) ? ns : string.Empty] != null; } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> /// <devdoc> /// Get a IEnumerator of the XmlSchemaCollection. /// </devdoc> IEnumerator IEnumerable.GetEnumerator() { return new XmlSchemaCollectionEnumerator(_collection); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.GetEnumerator"]/*' /> public XmlSchemaCollectionEnumerator GetEnumerator() { return new XmlSchemaCollectionEnumerator(_collection); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.CopyTo"]/*' /> /// <internalonly/> void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < 0) throw new ArgumentOutOfRangeException("index"); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) { array.SetValue(e.Current, index++); } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.CopyTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void CopyTo(XmlSchema[] array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < 0) throw new ArgumentOutOfRangeException("index"); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) { XmlSchema schema = e.Current; if (schema != null) { if (index == array.Length) { throw new ArgumentOutOfRangeException("index"); } array[index++] = e.Current; } } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.IsSynchronized"]/*' /> /// <internalonly/> bool ICollection.IsSynchronized { get { return true; } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.SyncRoot"]/*' /> /// <internalonly/> object ICollection.SyncRoot { get { return this; } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.Count"]/*' /> /// <internalonly/> int ICollection.Count { get { return _collection.Count; } } internal SchemaInfo GetSchemaInfo(string ns) { XmlSchemaCollectionNode node = (XmlSchemaCollectionNode)_collection[(ns != null) ? ns : string.Empty]; return (node != null) ? node.SchemaInfo : null; } internal SchemaNames GetSchemaNames(XmlNameTable nt) { if (_nameTable != nt) { return new SchemaNames(nt); } else { if (_schemaNames == null) { _schemaNames = new SchemaNames(_nameTable); } return _schemaNames; } } internal XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile) { return Add(ns, schemaInfo, schema, compile, _xmlResolver); } private XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile, XmlResolver resolver) { int errorCount = 0; if (schema != null) { if (schema.ErrorCount == 0 && compile) { if (!schema.CompileSchema(this, resolver, schemaInfo, ns, _validationEventHandler, _nameTable, true)) { errorCount = 1; } ns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; } errorCount += schema.ErrorCount; } else { errorCount += schemaInfo.ErrorCount; //ns = ns == null? string.Empty : NameTable.Add(ns); ns = NameTable.Add(ns); //Added without checking for ns == null, since XDR cannot have null namespace } if (errorCount == 0) { XmlSchemaCollectionNode node = new XmlSchemaCollectionNode(); node.NamespaceURI = ns; node.SchemaInfo = schemaInfo; node.Schema = schema; Add(ns, node); return schema; } return null; } private void Add(string ns, XmlSchemaCollectionNode node) { if (_isThreadSafe) _wLock.TryEnterWriteLock(_timeout); //wLock.AcquireWriterLock(timeout); try { if (_collection[ns] != null) _collection.Remove(ns); _collection.Add(ns, node); } finally { if (_isThreadSafe) _wLock.ExitWriteLock(); //wLock.ReleaseWriterLock(); } } private void SendValidationEvent(XmlSchemaException e) { if (_validationEventHandler != null) { _validationEventHandler(this, new ValidationEventArgs(e)); } else { throw e; } } internal ValidationEventHandler EventHandler { get { return _validationEventHandler; } set { _validationEventHandler = value; } } }; internal sealed class XmlSchemaCollectionNode { private String _namespaceUri; private SchemaInfo _schemaInfo; private XmlSchema _schema; internal String NamespaceURI { get { return _namespaceUri; } set { _namespaceUri = value; } } internal SchemaInfo SchemaInfo { get { return _schemaInfo; } set { _schemaInfo = value; } } internal XmlSchema Schema { get { return _schema; } set { _schema = value; } } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public sealed class XmlSchemaCollectionEnumerator : IEnumerator { private IDictionaryEnumerator _enumerator; internal XmlSchemaCollectionEnumerator(Hashtable collection) { _enumerator = collection.GetEnumerator(); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.IEnumerator.Reset"]/*' /> /// <internalonly/> void IEnumerator.Reset() { _enumerator.Reset(); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.IEnumerator.MoveNext"]/*' /> /// <internalonly/> bool IEnumerator.MoveNext() { return _enumerator.MoveNext(); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.MoveNext"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool MoveNext() { return _enumerator.MoveNext(); } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.IEnumerator.Current"]/*' /> /// <internalonly/> object IEnumerator.Current { get { return this.Current; } } /// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.Current"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchema Current { get { XmlSchemaCollectionNode n = (XmlSchemaCollectionNode)_enumerator.Value; if (n != null) return n.Schema; else return null; } } internal XmlSchemaCollectionNode CurrentNode { get { XmlSchemaCollectionNode n = (XmlSchemaCollectionNode)_enumerator.Value; return n; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using Xunit; namespace System.Numerics.Tests { public class Matrix3x2Tests { static Matrix3x2 GenerateMatrixNumberFrom1To6() { Matrix3x2 a = new Matrix3x2(); a.M11 = 1.0f; a.M12 = 2.0f; a.M21 = 3.0f; a.M22 = 4.0f; a.M31 = 5.0f; a.M32 = 6.0f; return a; } static Matrix3x2 GenerateTestMatrix() { Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f)); m.Translation = new Vector2(111.0f, 222.0f); return m; } // A test for Identity [Fact] public void Matrix3x2IdentityTest() { Matrix3x2 val = new Matrix3x2(); val.M11 = val.M22 = 1.0f; Assert.True(MathHelper.Equal(val, Matrix3x2.Identity), "Matrix3x2.Indentity was not set correctly."); } // A test for Determinant [Fact] public void Matrix3x2DeterminantTest() { Matrix3x2 target = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f)); float val = 1.0f; float det = target.GetDeterminant(); Assert.True(MathHelper.Equal(val, det), "Matrix3x2.Determinant was not set correctly."); } // A test for Determinant // Determinant test |A| = 1 / |A'| [Fact] public void Matrix3x2DeterminantTest1() { Matrix3x2 a = new Matrix3x2(); a.M11 = 5.0f; a.M12 = 2.0f; a.M21 = 12.0f; a.M22 = 6.8f; a.M31 = 6.5f; a.M32 = 1.0f; Matrix3x2 i; Assert.True(Matrix3x2.Invert(a, out i)); float detA = a.GetDeterminant(); float detI = i.GetDeterminant(); float t = 1.0f / detI; // only accurate to 3 precision Assert.True(System.Math.Abs(detA - t) < 1e-3, "Matrix3x2.Determinant was not set correctly."); // sanity check against 4x4 version Assert.Equal(new Matrix4x4(a).GetDeterminant(), detA); Assert.Equal(new Matrix4x4(i).GetDeterminant(), detI); } // A test for Invert (Matrix3x2) [Fact] public void Matrix3x2InvertTest() { Matrix3x2 mtx = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f)); Matrix3x2 expected = new Matrix3x2(); expected.M11 = 0.8660254f; expected.M12 = -0.5f; expected.M21 = 0.5f; expected.M22 = 0.8660254f; expected.M31 = 0; expected.M32 = 0; Matrix3x2 actual; Assert.True(Matrix3x2.Invert(mtx, out actual)); Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Invert did not return the expected value."); Matrix3x2 i = mtx * actual; Assert.True(MathHelper.Equal(i, Matrix3x2.Identity), "Matrix3x2.Invert did not return the expected value."); } // A test for Invert (Matrix3x2) [Fact] public void Matrix3x2InvertIdentityTest() { Matrix3x2 mtx = Matrix3x2.Identity; Matrix3x2 actual; Assert.True(Matrix3x2.Invert(mtx, out actual)); Assert.True(MathHelper.Equal(actual, Matrix3x2.Identity)); } // A test for Invert (Matrix3x2) [Fact] public void Matrix3x2InvertTranslationTest() { Matrix3x2 mtx = Matrix3x2.CreateTranslation(23, 42); Matrix3x2 actual; Assert.True(Matrix3x2.Invert(mtx, out actual)); Matrix3x2 i = mtx * actual; Assert.True(MathHelper.Equal(i, Matrix3x2.Identity)); } // A test for Invert (Matrix3x2) [Fact] public void Matrix3x2InvertRotationTest() { Matrix3x2 mtx = Matrix3x2.CreateRotation(2); Matrix3x2 actual; Assert.True(Matrix3x2.Invert(mtx, out actual)); Matrix3x2 i = mtx * actual; Assert.True(MathHelper.Equal(i, Matrix3x2.Identity)); } // A test for Invert (Matrix3x2) [Fact] public void Matrix3x2InvertScaleTest() { Matrix3x2 mtx = Matrix3x2.CreateScale(23, -42); Matrix3x2 actual; Assert.True(Matrix3x2.Invert(mtx, out actual)); Matrix3x2 i = mtx * actual; Assert.True(MathHelper.Equal(i, Matrix3x2.Identity)); } // A test for Invert (Matrix3x2) [Fact] public void Matrix3x2InvertAffineTest() { Matrix3x2 mtx = Matrix3x2.CreateRotation(2) * Matrix3x2.CreateScale(23, -42) * Matrix3x2.CreateTranslation(17, 53); Matrix3x2 actual; Assert.True(Matrix3x2.Invert(mtx, out actual)); Matrix3x2 i = mtx * actual; Assert.True(MathHelper.Equal(i, Matrix3x2.Identity)); } // A test for CreateRotation (float) [Fact] public void Matrix3x2CreateRotationTest() { float radians = MathHelper.ToRadians(50.0f); Matrix3x2 expected = new Matrix3x2(); expected.M11 = 0.642787635f; expected.M12 = 0.766044438f; expected.M21 = -0.766044438f; expected.M22 = 0.642787635f; Matrix3x2 actual; actual = Matrix3x2.CreateRotation(radians); Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.CreateRotation did not return the expected value."); } // A test for CreateRotation (float, Vector2f) [Fact] public void Matrix3x2CreateRotationCenterTest() { float radians = MathHelper.ToRadians(30.0f); Vector2 center = new Vector2(23, 42); Matrix3x2 rotateAroundZero = Matrix3x2.CreateRotation(radians, Vector2.Zero); Matrix3x2 rotateAroundZeroExpected = Matrix3x2.CreateRotation(radians); Assert.True(MathHelper.Equal(rotateAroundZero, rotateAroundZeroExpected)); Matrix3x2 rotateAroundCenter = Matrix3x2.CreateRotation(radians, center); Matrix3x2 rotateAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateRotation(radians) * Matrix3x2.CreateTranslation(center); Assert.True(MathHelper.Equal(rotateAroundCenter, rotateAroundCenterExpected)); } // A test for CreateRotation (float) [Fact] public void Matrix3x2CreateRotationRightAngleTest() { // 90 degree rotations must be exact! Matrix3x2 actual = Matrix3x2.CreateRotation(0); Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2); Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi); Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2); Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2); Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2); Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual); actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2); Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual); // But merely close-to-90 rotations should not be excessively clamped. float delta = MathHelper.ToRadians(0.01f); actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta); Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual)); actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta); Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual)); } // A test for CreateRotation (float, Vector2f) [Fact] public void Matrix3x2CreateRotationRightAngleCenterTest() { Vector2 center = new Vector2(3, 7); // 90 degree rotations must be exact! Matrix3x2 actual = Matrix3x2.CreateRotation(0, center); Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2, center); Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi, center); Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2, center); Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2, center); Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual); actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2, center); Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual); actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2, center); Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual); // But merely close-to-90 rotations should not be excessively clamped. float delta = MathHelper.ToRadians(0.01f); actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta, center); Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual)); actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta, center); Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual)); } // A test for Invert (Matrix3x2) // Non invertible matrix - determinant is zero - singular matrix [Fact] public void Matrix3x2InvertTest1() { Matrix3x2 a = new Matrix3x2(); a.M11 = 0.0f; a.M12 = 2.0f; a.M21 = 0.0f; a.M22 = 4.0f; a.M31 = 5.0f; a.M32 = 6.0f; float detA = a.GetDeterminant(); Assert.True(MathHelper.Equal(detA, 0.0f), "Matrix3x2.Invert did not return the expected value."); Matrix3x2 actual; Assert.False(Matrix3x2.Invert(a, out actual)); // all the elements in Actual is NaN Assert.True( float.IsNaN(actual.M11) && float.IsNaN(actual.M12) && float.IsNaN(actual.M21) && float.IsNaN(actual.M22) && float.IsNaN(actual.M31) && float.IsNaN(actual.M32) , "Matrix3x2.Invert did not return the expected value."); } // A test for Lerp (Matrix3x2, Matrix3x2, float) [Fact] public void Matrix3x2LerpTest() { Matrix3x2 a = new Matrix3x2(); a.M11 = 11.0f; a.M12 = 12.0f; a.M21 = 21.0f; a.M22 = 22.0f; a.M31 = 31.0f; a.M32 = 32.0f; Matrix3x2 b = GenerateMatrixNumberFrom1To6(); float t = 0.5f; Matrix3x2 expected = new Matrix3x2(); expected.M11 = a.M11 + (b.M11 - a.M11) * t; expected.M12 = a.M12 + (b.M12 - a.M12) * t; expected.M21 = a.M21 + (b.M21 - a.M21) * t; expected.M22 = a.M22 + (b.M22 - a.M22) * t; expected.M31 = a.M31 + (b.M31 - a.M31) * t; expected.M32 = a.M32 + (b.M32 - a.M32) * t; Matrix3x2 actual; actual = Matrix3x2.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Lerp did not return the expected value."); } // A test for operator - (Matrix3x2) [Fact] public void Matrix3x2UnaryNegationTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); expected.M11 = -1.0f; expected.M12 = -2.0f; expected.M21 = -3.0f; expected.M22 = -4.0f; expected.M31 = -5.0f; expected.M32 = -6.0f; Matrix3x2 actual = -a; Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value."); } // A test for operator - (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2SubtractionTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); Matrix3x2 actual = a - b; Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value."); } // A test for operator * (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2MultiplyTest1() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); expected.M11 = a.M11 * b.M11 + a.M12 * b.M21; expected.M12 = a.M11 * b.M12 + a.M12 * b.M22; expected.M21 = a.M21 * b.M11 + a.M22 * b.M21; expected.M22 = a.M21 * b.M12 + a.M22 * b.M22; expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31; expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32; Matrix3x2 actual = a * b; Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value."); // Sanity check by comparison with 4x4 multiply. a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42); b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1); actual = a * b; Matrix4x4 a44 = new Matrix4x4(a); Matrix4x4 b44 = new Matrix4x4(b); Matrix4x4 expected44 = a44 * b44; Matrix4x4 actual44 = new Matrix4x4(actual); Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.operator * did not return the expected value."); } // A test for operator * (Matrix3x2, Matrix3x2) // Multiply with identity matrix [Fact] public void Matrix3x2MultiplyTest4() { Matrix3x2 a = new Matrix3x2(); a.M11 = 1.0f; a.M12 = 2.0f; a.M21 = 5.0f; a.M22 = -6.0f; a.M31 = 9.0f; a.M32 = 10.0f; Matrix3x2 b = new Matrix3x2(); b = Matrix3x2.Identity; Matrix3x2 expected = a; Matrix3x2 actual = a * b; Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value."); } // A test for operator + (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2AdditionTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); expected.M11 = a.M11 + b.M11; expected.M12 = a.M12 + b.M12; expected.M21 = a.M21 + b.M21; expected.M22 = a.M22 + b.M22; expected.M31 = a.M31 + b.M31; expected.M32 = a.M32 + b.M32; Matrix3x2 actual; actual = a + b; Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator + did not return the expected value."); } // A test for ToString () [Fact] public void Matrix3x2ToStringTest() { Matrix3x2 a = new Matrix3x2(); a.M11 = 11.0f; a.M12 = -12.0f; a.M21 = 21.0f; a.M22 = 22.0f; a.M31 = 31.0f; a.M32 = 32.0f; string expected = "{ {M11:11 M12:-12} " + "{M21:21 M22:22} " + "{M31:31 M32:32} }"; string actual; actual = a.ToString(); Assert.Equal(expected, actual); } // A test for Add (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2AddTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); expected.M11 = a.M11 + b.M11; expected.M12 = a.M12 + b.M12; expected.M21 = a.M21 + b.M21; expected.M22 = a.M22 + b.M22; expected.M31 = a.M31 + b.M31; expected.M32 = a.M32 + b.M32; Matrix3x2 actual; actual = Matrix3x2.Add(a, b); Assert.Equal(expected, actual); } // A test for Equals (object) [Fact] public void Matrix3x2EqualsTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.Equal(expected, actual); // case 2: compare between different values b.M11 = 11.0f; obj = b; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare between different types. obj = new Vector4(); expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); } // A test for GetHashCode () [Fact] public void Matrix3x2GetHashCodeTest() { Matrix3x2 target = GenerateMatrixNumberFrom1To6(); int expected = target.M11.GetHashCode() + target.M12.GetHashCode() + target.M21.GetHashCode() + target.M22.GetHashCode() + target.M31.GetHashCode() + target.M32.GetHashCode(); int actual; actual = target.GetHashCode(); Assert.Equal(expected, actual); } // A test for Multiply (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2MultiplyTest3() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); expected.M11 = a.M11 * b.M11 + a.M12 * b.M21; expected.M12 = a.M11 * b.M12 + a.M12 * b.M22; expected.M21 = a.M21 * b.M11 + a.M22 * b.M21; expected.M22 = a.M21 * b.M12 + a.M22 * b.M22; expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31; expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32; Matrix3x2 actual; actual = Matrix3x2.Multiply(a, b); Assert.Equal(expected, actual); // Sanity check by comparison with 4x4 multiply. a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42); b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1); actual = Matrix3x2.Multiply(a, b); Matrix4x4 a44 = new Matrix4x4(a); Matrix4x4 b44 = new Matrix4x4(b); Matrix4x4 expected44 = Matrix4x4.Multiply(a44, b44); Matrix4x4 actual44 = new Matrix4x4(actual); Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.Multiply did not return the expected value."); } // A test for Multiply (Matrix3x2, float) [Fact] public void Matrix3x2MultiplyTest5() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18); Matrix3x2 actual = Matrix3x2.Multiply(a, 3); Assert.Equal(expected, actual); } // A test for Multiply (Matrix3x2, float) [Fact] public void Matrix3x2MultiplyTest6() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18); Matrix3x2 actual = a * 3; Assert.Equal(expected, actual); } // A test for Negate (Matrix3x2) [Fact] public void Matrix3x2NegateTest() { Matrix3x2 m = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); expected.M11 = -1.0f; expected.M12 = -2.0f; expected.M21 = -3.0f; expected.M22 = -4.0f; expected.M31 = -5.0f; expected.M32 = -6.0f; Matrix3x2 actual; actual = Matrix3x2.Negate(m); Assert.Equal(expected, actual); } // A test for operator != (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2InequalityTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.Equal(expected, actual); // case 2: compare between different values b.M11 = 11.0f; expected = true; actual = a != b; Assert.Equal(expected, actual); } // A test for operator == (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2EqualityTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.Equal(expected, actual); // case 2: compare between different values b.M11 = 11.0f; expected = false; actual = a == b; Assert.Equal(expected, actual); } // A test for Subtract (Matrix3x2, Matrix3x2) [Fact] public void Matrix3x2SubtractTest() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); Matrix3x2 expected = new Matrix3x2(); Matrix3x2 actual; actual = Matrix3x2.Subtract(a, b); Assert.Equal(expected, actual); } // A test for CreateScale (Vector2f) [Fact] public void Matrix3x2CreateScaleTest1() { Vector2 scales = new Vector2(2.0f, 3.0f); Matrix3x2 expected = new Matrix3x2( 2.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f); Matrix3x2 actual = Matrix3x2.CreateScale(scales); Assert.Equal(expected, actual); } // A test for CreateScale (Vector2f, Vector2f) [Fact] public void Matrix3x2CreateScaleCenterTest1() { Vector2 scale = new Vector2(3, 4); Vector2 center = new Vector2(23, 42); Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero); Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale); Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected)); Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center); Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center); Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected)); } // A test for CreateScale (float) [Fact] public void Matrix3x2CreateScaleTest2() { float scale = 2.0f; Matrix3x2 expected = new Matrix3x2( 2.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f); Matrix3x2 actual = Matrix3x2.CreateScale(scale); Assert.Equal(expected, actual); } // A test for CreateScale (float, Vector2f) [Fact] public void Matrix3x2CreateScaleCenterTest2() { float scale = 5; Vector2 center = new Vector2(23, 42); Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero); Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale); Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected)); Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center); Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center); Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected)); } // A test for CreateScale (float, float) [Fact] public void Matrix3x2CreateScaleTest3() { float xScale = 2.0f; float yScale = 3.0f; Matrix3x2 expected = new Matrix3x2( 2.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f); Matrix3x2 actual = Matrix3x2.CreateScale(xScale, yScale); Assert.Equal(expected, actual); } // A test for CreateScale (float, float, Vector2f) [Fact] public void Matrix3x2CreateScaleCenterTest3() { Vector2 scale = new Vector2(3, 4); Vector2 center = new Vector2(23, 42); Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale.X, scale.Y, Vector2.Zero); Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale.X, scale.Y); Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected)); Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale.X, scale.Y, center); Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale.X, scale.Y) * Matrix3x2.CreateTranslation(center); Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected)); } // A test for CreateTranslation (Vector2f) [Fact] public void Matrix3x2CreateTranslationTest1() { Vector2 position = new Vector2(2.0f, 3.0f); Matrix3x2 expected = new Matrix3x2( 1.0f, 0.0f, 0.0f, 1.0f, 2.0f, 3.0f); Matrix3x2 actual = Matrix3x2.CreateTranslation(position); Assert.Equal(expected, actual); } // A test for CreateTranslation (float, float) [Fact] public void Matrix3x2CreateTranslationTest2() { float xPosition = 2.0f; float yPosition = 3.0f; Matrix3x2 expected = new Matrix3x2( 1.0f, 0.0f, 0.0f, 1.0f, 2.0f, 3.0f); Matrix3x2 actual = Matrix3x2.CreateTranslation(xPosition, yPosition); Assert.Equal(expected, actual); } // A test for Translation [Fact] public void Matrix3x2TranslationTest() { Matrix3x2 a = GenerateTestMatrix(); Matrix3x2 b = a; // Transfomed vector that has same semantics of property must be same. Vector2 val = new Vector2(a.M31, a.M32); Assert.Equal(val, a.Translation); // Set value and get value must be same. val = new Vector2(1.0f, 2.0f); a.Translation = val; Assert.Equal(val, a.Translation); // Make sure it only modifies expected value of matrix. Assert.True( a.M11 == b.M11 && a.M12 == b.M12 && a.M21 == b.M21 && a.M22 == b.M22 && a.M31 != b.M31 && a.M32 != b.M32, "Matrix3x2.Translation modified unexpected value of matrix."); } // A test for Equals (Matrix3x2) [Fact] public void Matrix3x2EqualsTest1() { Matrix3x2 a = GenerateMatrixNumberFrom1To6(); Matrix3x2 b = GenerateMatrixNumberFrom1To6(); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.Equal(expected, actual); // case 2: compare between different values b.M11 = 11.0f; expected = false; actual = a.Equals(b); Assert.Equal(expected, actual); } // A test for CreateSkew (float, float) [Fact] public void Matrix3x2CreateSkewIdentityTest() { Matrix3x2 expected = Matrix3x2.Identity; Matrix3x2 actual = Matrix3x2.CreateSkew(0, 0); Assert.Equal(expected, actual); } // A test for CreateSkew (float, float) [Fact] public void Matrix3x2CreateSkewXTest() { Matrix3x2 expected = new Matrix3x2(1, 0, -0.414213562373095f, 1, 0, 0); Matrix3x2 actual = Matrix3x2.CreateSkew(-MathHelper.Pi / 8, 0); Assert.True(MathHelper.Equal(expected, actual)); expected = new Matrix3x2(1, 0, 0.414213562373095f, 1, 0, 0); actual = Matrix3x2.CreateSkew(MathHelper.Pi / 8, 0); Assert.True(MathHelper.Equal(expected, actual)); Vector2 result = Vector2.Transform(new Vector2(0, 0), actual); Assert.True(MathHelper.Equal(new Vector2(0, 0), result)); result = Vector2.Transform(new Vector2(0, 1), actual); Assert.True(MathHelper.Equal(new Vector2(0.414213568f, 1), result)); result = Vector2.Transform(new Vector2(0, -1), actual); Assert.True(MathHelper.Equal(new Vector2(-0.414213568f, -1), result)); result = Vector2.Transform(new Vector2(3, 10), actual); Assert.True(MathHelper.Equal(new Vector2(7.14213568f, 10), result)); } // A test for CreateSkew (float, float) [Fact] public void Matrix3x2CreateSkewYTest() { Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 0, 1, 0, 0); Matrix3x2 actual = Matrix3x2.CreateSkew(0, -MathHelper.Pi / 8); Assert.True(MathHelper.Equal(expected, actual)); expected = new Matrix3x2(1, 0.414213562373095f, 0, 1, 0, 0); actual = Matrix3x2.CreateSkew(0, MathHelper.Pi / 8); Assert.True(MathHelper.Equal(expected, actual)); Vector2 result = Vector2.Transform(new Vector2(0, 0), actual); Assert.True(MathHelper.Equal(new Vector2(0, 0), result)); result = Vector2.Transform(new Vector2(1, 0), actual); Assert.True(MathHelper.Equal(new Vector2(1, 0.414213568f), result)); result = Vector2.Transform(new Vector2(-1, 0), actual); Assert.True(MathHelper.Equal(new Vector2(-1, -0.414213568f), result)); result = Vector2.Transform(new Vector2(10, 3), actual); Assert.True(MathHelper.Equal(new Vector2(10, 7.14213568f), result)); } // A test for CreateSkew (float, float) [Fact] public void Matrix3x2CreateSkewXYTest() { Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 1, 1, 0, 0); Matrix3x2 actual = Matrix3x2.CreateSkew(MathHelper.Pi / 4, -MathHelper.Pi / 8); Assert.True(MathHelper.Equal(expected, actual)); Vector2 result = Vector2.Transform(new Vector2(0, 0), actual); Assert.True(MathHelper.Equal(new Vector2(0, 0), result)); result = Vector2.Transform(new Vector2(1, 0), actual); Assert.True(MathHelper.Equal(new Vector2(1, -0.414213562373095f), result)); result = Vector2.Transform(new Vector2(0, 1), actual); Assert.True(MathHelper.Equal(new Vector2(1, 1), result)); result = Vector2.Transform(new Vector2(1, 1), actual); Assert.True(MathHelper.Equal(new Vector2(2, 0.585786437626905f), result)); } // A test for CreateSkew (float, float, Vector2f) [Fact] public void Matrix3x2CreateSkewCenterTest() { float skewX = 1, skewY = 2; Vector2 center = new Vector2(23, 42); Matrix3x2 skewAroundZero = Matrix3x2.CreateSkew(skewX, skewY, Vector2.Zero); Matrix3x2 skewAroundZeroExpected = Matrix3x2.CreateSkew(skewX, skewY); Assert.True(MathHelper.Equal(skewAroundZero, skewAroundZeroExpected)); Matrix3x2 skewAroundCenter = Matrix3x2.CreateSkew(skewX, skewY, center); Matrix3x2 skewAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateSkew(skewX, skewY) * Matrix3x2.CreateTranslation(center); Assert.True(MathHelper.Equal(skewAroundCenter, skewAroundCenterExpected)); } // A test for IsIdentity [Fact] public void Matrix3x2IsIdentityTest() { Assert.True(Matrix3x2.Identity.IsIdentity); Assert.True(new Matrix3x2(1, 0, 0, 1, 0, 0).IsIdentity); Assert.False(new Matrix3x2(0, 0, 0, 1, 0, 0).IsIdentity); Assert.False(new Matrix3x2(1, 1, 0, 1, 0, 0).IsIdentity); Assert.False(new Matrix3x2(1, 0, 1, 1, 0, 0).IsIdentity); Assert.False(new Matrix3x2(1, 0, 0, 0, 0, 0).IsIdentity); Assert.False(new Matrix3x2(1, 0, 0, 1, 1, 0).IsIdentity); Assert.False(new Matrix3x2(1, 0, 0, 1, 0, 1).IsIdentity); } // A test for Matrix3x2 comparison involving NaN values [Fact] public void Matrix3x2EqualsNanTest() { Matrix3x2 a = new Matrix3x2(float.NaN, 0, 0, 0, 0, 0); Matrix3x2 b = new Matrix3x2(0, float.NaN, 0, 0, 0, 0); Matrix3x2 c = new Matrix3x2(0, 0, float.NaN, 0, 0, 0); Matrix3x2 d = new Matrix3x2(0, 0, 0, float.NaN, 0, 0); Matrix3x2 e = new Matrix3x2(0, 0, 0, 0, float.NaN, 0); Matrix3x2 f = new Matrix3x2(0, 0, 0, 0, 0, float.NaN); Assert.False(a == new Matrix3x2()); Assert.False(b == new Matrix3x2()); Assert.False(c == new Matrix3x2()); Assert.False(d == new Matrix3x2()); Assert.False(e == new Matrix3x2()); Assert.False(f == new Matrix3x2()); Assert.True(a != new Matrix3x2()); Assert.True(b != new Matrix3x2()); Assert.True(c != new Matrix3x2()); Assert.True(d != new Matrix3x2()); Assert.True(e != new Matrix3x2()); Assert.True(f != new Matrix3x2()); Assert.False(a.Equals(new Matrix3x2())); Assert.False(b.Equals(new Matrix3x2())); Assert.False(c.Equals(new Matrix3x2())); Assert.False(d.Equals(new Matrix3x2())); Assert.False(e.Equals(new Matrix3x2())); Assert.False(f.Equals(new Matrix3x2())); Assert.False(a.IsIdentity); Assert.False(b.IsIdentity); Assert.False(c.IsIdentity); Assert.False(d.IsIdentity); Assert.False(e.IsIdentity); Assert.False(f.IsIdentity); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.False(a.Equals(a)); Assert.False(b.Equals(b)); Assert.False(c.Equals(c)); Assert.False(d.Equals(d)); Assert.False(e.Equals(e)); Assert.False(f.Equals(f)); } // A test to make sure these types are blittable directly into GPU buffer memory layouts [Fact] public unsafe void Matrix3x2SizeofTest() { Assert.Equal(24, sizeof(Matrix3x2)); Assert.Equal(48, sizeof(Matrix3x2_2x)); Assert.Equal(28, sizeof(Matrix3x2PlusFloat)); Assert.Equal(56, sizeof(Matrix3x2PlusFloat_2x)); } [StructLayout(LayoutKind.Sequential)] struct Matrix3x2_2x { private Matrix3x2 _a; private Matrix3x2 _b; } [StructLayout(LayoutKind.Sequential)] struct Matrix3x2PlusFloat { private Matrix3x2 _v; private float _f; } [StructLayout(LayoutKind.Sequential)] struct Matrix3x2PlusFloat_2x { private Matrix3x2PlusFloat _a; private Matrix3x2PlusFloat _b; } // A test to make sure the fields are laid out how we expect [Fact] public unsafe void Matrix3x2FieldOffsetTest() { Matrix3x2* ptr = (Matrix3x2*)0; Assert.Equal(new IntPtr(0), new IntPtr(&ptr->M11)); Assert.Equal(new IntPtr(4), new IntPtr(&ptr->M12)); Assert.Equal(new IntPtr(8), new IntPtr(&ptr->M21)); Assert.Equal(new IntPtr(12), new IntPtr(&ptr->M22)); Assert.Equal(new IntPtr(16), new IntPtr(&ptr->M31)); Assert.Equal(new IntPtr(20), new IntPtr(&ptr->M32)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Reflection; //test namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class LoadingMethods : CSharpTestBase { [Fact] public void Test1() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { TestReferences.SymbolsTests.MDTestLib1, TestReferences.SymbolsTests.MDTestLib2, TestReferences.SymbolsTests.Methods.CSMethods, TestReferences.SymbolsTests.Methods.VBMethods, TestReferences.NetFx.v4_0_21006.mscorlib, TestReferences.SymbolsTests.Methods.ByRefReturn }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var module1 = assemblies[0].Modules[0]; var module2 = assemblies[1].Modules[0]; var module3 = assemblies[2].Modules[0]; var module4 = assemblies[3].Modules[0]; var module5 = assemblies[4].Modules[0]; var byrefReturn = assemblies[5].Modules[0]; var varTC10 = module2.GlobalNamespace.GetTypeMembers("TC10").Single(); Assert.Equal(6, varTC10.GetMembers().Length); var localM1 = (MethodSymbol)varTC10.GetMembers("M1").Single(); var localM2 = (MethodSymbol)varTC10.GetMembers("M2").Single(); var localM3 = (MethodSymbol)varTC10.GetMembers("M3").Single(); var localM4 = (MethodSymbol)varTC10.GetMembers("M4").Single(); var localM5 = (MethodSymbol)varTC10.GetMembers("M5").Single(); Assert.Equal("void TC10.M1()", localM1.ToTestDisplayString()); Assert.True(localM1.ReturnsVoid); Assert.Equal(Accessibility.Public, localM1.DeclaredAccessibility); Assert.Same(module2, localM1.Locations.Single().MetadataModule); Assert.Equal("void TC10.M2(System.Int32 m1_1)", localM2.ToTestDisplayString()); Assert.True(localM2.ReturnsVoid); Assert.Equal(Accessibility.Protected, localM2.DeclaredAccessibility); var localM1_1 = localM2.Parameters[0]; Assert.IsType<PEParameterSymbol>(localM1_1); Assert.Same(localM1_1.ContainingSymbol, localM2); Assert.Equal(SymbolKind.Parameter, localM1_1.Kind); Assert.Equal(Accessibility.NotApplicable, localM1_1.DeclaredAccessibility); Assert.False(localM1_1.IsAbstract); Assert.False(localM1_1.IsSealed); Assert.False(localM1_1.IsVirtual); Assert.False(localM1_1.IsOverride); Assert.False(localM1_1.IsStatic); Assert.False(localM1_1.IsExtern); Assert.Equal(0, localM1_1.CustomModifiers.Length); Assert.Equal("TC8 TC10.M3()", localM3.ToTestDisplayString()); Assert.False(localM3.ReturnsVoid); Assert.Equal(Accessibility.Protected, localM3.DeclaredAccessibility); Assert.Equal("C1<System.Type> TC10.M4(ref C1<System.Type> x, ref TC8 y)", localM4.ToTestDisplayString()); Assert.False(localM4.ReturnsVoid); Assert.Equal(Accessibility.Internal, localM4.DeclaredAccessibility); Assert.Equal("void TC10.M5(ref C1<System.Type>[,,] x, ref TC8[] y)", localM5.ToTestDisplayString()); Assert.True(localM5.ReturnsVoid); Assert.Equal(Accessibility.ProtectedOrInternal, localM5.DeclaredAccessibility); var localM6 = varTC10.GetMembers("M6"); Assert.Equal(0, localM6.Length); var localC107 = module1.GlobalNamespace.GetTypeMembers("C107").Single(); var varC108 = localC107.GetMembers("C108").Single(); Assert.Equal(SymbolKind.NamedType, varC108.Kind); var csharpC1 = module3.GlobalNamespace.GetTypeMembers("C1").Single(); var sameName1 = csharpC1.GetMembers("SameName").Single(); var sameName2 = csharpC1.GetMembers("sameName").Single(); Assert.Equal(SymbolKind.NamedType, sameName1.Kind); Assert.Equal("SameName", sameName1.Name); Assert.Equal(SymbolKind.Method, sameName2.Kind); Assert.Equal("sameName", sameName2.Name); Assert.Equal(2, csharpC1.GetMembers("SameName2").Length); Assert.Equal(1, csharpC1.GetMembers("sameName2").Length); Assert.Equal(0, csharpC1.GetMembers("DoesntExist").Length); var basicC1 = module4.GlobalNamespace.GetTypeMembers("C1").Single(); var basicC1_M1 = (MethodSymbol)basicC1.GetMembers("M1").Single(); var basicC1_M2 = (MethodSymbol)basicC1.GetMembers("M2").Single(); var basicC1_M3 = (MethodSymbol)basicC1.GetMembers("M3").Single(); var basicC1_M4 = (MethodSymbol)basicC1.GetMembers("M4").Single(); Assert.False(basicC1_M1.Parameters[0].IsOptional); Assert.False(basicC1_M1.Parameters[0].HasExplicitDefaultValue); Assert.Same(module4, basicC1_M1.Parameters[0].Locations.Single().MetadataModule); Assert.True(basicC1_M2.Parameters[0].IsOptional); Assert.False(basicC1_M2.Parameters[0].HasExplicitDefaultValue); Assert.True(basicC1_M3.Parameters[0].IsOptional); Assert.True(basicC1_M3.Parameters[0].HasExplicitDefaultValue); Assert.True(basicC1_M4.Parameters[0].IsOptional); Assert.False(basicC1_M4.Parameters[0].HasExplicitDefaultValue); var emptyStructure = module4.GlobalNamespace.GetTypeMembers("EmptyStructure").Single(); Assert.Equal(1, emptyStructure.GetMembers().Length); //synthesized parameterless constructor Assert.Equal(0, emptyStructure.GetMembers("NoMembersOrTypes").Length); var basicC1_M5 = (MethodSymbol)basicC1.GetMembers("M5").Single(); var basicC1_M6 = (MethodSymbol)basicC1.GetMembers("M6").Single(); var basicC1_M7 = (MethodSymbol)basicC1.GetMembers("M7").Single(); var basicC1_M8 = (MethodSymbol)basicC1.GetMembers("M8").Single(); var basicC1_M9 = basicC1.GetMembers("M9").OfType<MethodSymbol>().ToArray(); Assert.False(basicC1_M5.IsGenericMethod); // Check genericity before cracking signature Assert.True(basicC1_M6.ReturnsVoid); Assert.False(basicC1_M6.IsGenericMethod); // Check genericity after cracking signature Assert.True(basicC1_M7.IsGenericMethod); // Check genericity before cracking signature Assert.Equal("void C1.M7<T>(System.Int32 x)", basicC1_M7.ToTestDisplayString()); Assert.True(basicC1_M6.ReturnsVoid); Assert.True(basicC1_M8.IsGenericMethod); // Check genericity after cracking signature Assert.Equal("void C1.M8<T>(System.Int32 x)", basicC1_M8.ToTestDisplayString()); Assert.Equal(2, basicC1_M9.Count()); Assert.Equal(1, basicC1_M9.Count(m => m.IsGenericMethod)); Assert.Equal(1, basicC1_M9.Count(m => !m.IsGenericMethod)); var basicC1_M10 = (MethodSymbol)basicC1.GetMembers("M10").Single(); Assert.Equal("void C1.M10<T1>(T1 x)", basicC1_M10.ToTestDisplayString()); var basicC1_M11 = (MethodSymbol)basicC1.GetMembers("M11").Single(); Assert.Equal("T3 C1.M11<T2, T3>(T2 x)", basicC1_M11.ToTestDisplayString()); Assert.Equal(0, basicC1_M11.TypeParameters[0].ConstraintTypes.Length); Assert.Same(basicC1, basicC1_M11.TypeParameters[1].ConstraintTypes.Single()); var basicC1_M12 = (MethodSymbol)basicC1.GetMembers("M12").Single(); Assert.Equal(0, basicC1_M12.TypeArguments.Length); Assert.False(basicC1_M12.IsVararg); Assert.False(basicC1_M12.IsExtern); Assert.False(basicC1_M12.IsStatic); var loadLibrary = (MethodSymbol)basicC1.GetMembers("LoadLibrary").Single(); Assert.True(loadLibrary.IsExtern); var basicC2 = module4.GlobalNamespace.GetTypeMembers("C2").Single(); var basicC2_M1 = (MethodSymbol)basicC2.GetMembers("M1").Single(); Assert.Equal("void C2<T4>.M1<T5>(T5 x, T4 y)", basicC2_M1.ToTestDisplayString()); var console = module5.GlobalNamespace.GetMembers("System").OfType<NamespaceSymbol>().Single(). GetTypeMembers("Console").Single(); Assert.Equal(1, console.GetMembers("WriteLine").OfType<MethodSymbol>().Count(m => m.IsVararg)); Assert.True(console.GetMembers("WriteLine").OfType<MethodSymbol>().Single(m => m.IsVararg).IsStatic); var basicModifiers1 = module4.GlobalNamespace.GetTypeMembers("Modifiers1").Single(); var basicModifiers1_M1 = (MethodSymbol)basicModifiers1.GetMembers("M1").Single(); var basicModifiers1_M2 = (MethodSymbol)basicModifiers1.GetMembers("M2").Single(); var basicModifiers1_M3 = (MethodSymbol)basicModifiers1.GetMembers("M3").Single(); var basicModifiers1_M4 = (MethodSymbol)basicModifiers1.GetMembers("M4").Single(); var basicModifiers1_M5 = (MethodSymbol)basicModifiers1.GetMembers("M5").Single(); var basicModifiers1_M6 = (MethodSymbol)basicModifiers1.GetMembers("M6").Single(); var basicModifiers1_M7 = (MethodSymbol)basicModifiers1.GetMembers("M7").Single(); var basicModifiers1_M8 = (MethodSymbol)basicModifiers1.GetMembers("M8").Single(); var basicModifiers1_M9 = (MethodSymbol)basicModifiers1.GetMembers("M9").Single(); Assert.True(basicModifiers1_M1.IsAbstract); Assert.False(basicModifiers1_M1.IsVirtual); Assert.False(basicModifiers1_M1.IsSealed); Assert.True(basicModifiers1_M1.HidesBaseMethodsByName); Assert.False(basicModifiers1_M1.IsOverride); Assert.False(basicModifiers1_M2.IsAbstract); Assert.True(basicModifiers1_M2.IsVirtual); Assert.False(basicModifiers1_M2.IsSealed); Assert.True(basicModifiers1_M2.HidesBaseMethodsByName); Assert.False(basicModifiers1_M2.IsOverride); Assert.False(basicModifiers1_M3.IsAbstract); Assert.False(basicModifiers1_M3.IsVirtual); Assert.False(basicModifiers1_M3.IsSealed); Assert.False(basicModifiers1_M3.HidesBaseMethodsByName); Assert.False(basicModifiers1_M3.IsOverride); Assert.False(basicModifiers1_M4.IsAbstract); Assert.False(basicModifiers1_M4.IsVirtual); Assert.False(basicModifiers1_M4.IsSealed); Assert.True(basicModifiers1_M4.HidesBaseMethodsByName); Assert.False(basicModifiers1_M4.IsOverride); Assert.False(basicModifiers1_M5.IsAbstract); Assert.False(basicModifiers1_M5.IsVirtual); Assert.False(basicModifiers1_M5.IsSealed); Assert.True(basicModifiers1_M5.HidesBaseMethodsByName); Assert.False(basicModifiers1_M5.IsOverride); Assert.True(basicModifiers1_M6.IsAbstract); Assert.False(basicModifiers1_M6.IsVirtual); Assert.False(basicModifiers1_M6.IsSealed); Assert.False(basicModifiers1_M6.HidesBaseMethodsByName); Assert.False(basicModifiers1_M6.IsOverride); Assert.False(basicModifiers1_M7.IsAbstract); Assert.True(basicModifiers1_M7.IsVirtual); Assert.False(basicModifiers1_M7.IsSealed); Assert.False(basicModifiers1_M7.HidesBaseMethodsByName); Assert.False(basicModifiers1_M7.IsOverride); Assert.True(basicModifiers1_M8.IsAbstract); Assert.False(basicModifiers1_M8.IsVirtual); Assert.False(basicModifiers1_M8.IsSealed); Assert.True(basicModifiers1_M8.HidesBaseMethodsByName); Assert.False(basicModifiers1_M8.IsOverride); Assert.False(basicModifiers1_M9.IsAbstract); Assert.True(basicModifiers1_M9.IsVirtual); Assert.False(basicModifiers1_M9.IsSealed); Assert.True(basicModifiers1_M9.HidesBaseMethodsByName); Assert.False(basicModifiers1_M9.IsOverride); var basicModifiers2 = module4.GlobalNamespace.GetTypeMembers("Modifiers2").Single(); var basicModifiers2_M1 = (MethodSymbol)basicModifiers2.GetMembers("M1").Single(); var basicModifiers2_M2 = (MethodSymbol)basicModifiers2.GetMembers("M2").Single(); var basicModifiers2_M6 = (MethodSymbol)basicModifiers2.GetMembers("M6").Single(); var basicModifiers2_M7 = (MethodSymbol)basicModifiers2.GetMembers("M7").Single(); Assert.True(basicModifiers2_M1.IsAbstract); Assert.False(basicModifiers2_M1.IsVirtual); Assert.False(basicModifiers2_M1.IsSealed); Assert.True(basicModifiers2_M1.HidesBaseMethodsByName); Assert.True(basicModifiers2_M1.IsOverride); Assert.False(basicModifiers2_M2.IsAbstract); Assert.False(basicModifiers2_M2.IsVirtual); Assert.True(basicModifiers2_M2.IsSealed); Assert.True(basicModifiers2_M2.HidesBaseMethodsByName); Assert.True(basicModifiers2_M2.IsOverride); Assert.True(basicModifiers2_M6.IsAbstract); Assert.False(basicModifiers2_M6.IsVirtual); Assert.False(basicModifiers2_M6.IsSealed); Assert.False(basicModifiers2_M6.HidesBaseMethodsByName); Assert.True(basicModifiers2_M6.IsOverride); Assert.False(basicModifiers2_M7.IsAbstract); Assert.False(basicModifiers2_M7.IsVirtual); Assert.True(basicModifiers2_M7.IsSealed); Assert.False(basicModifiers2_M7.HidesBaseMethodsByName); Assert.True(basicModifiers2_M7.IsOverride); var basicModifiers3 = module4.GlobalNamespace.GetTypeMembers("Modifiers3").Single(); var basicModifiers3_M1 = (MethodSymbol)basicModifiers3.GetMembers("M1").Single(); var basicModifiers3_M6 = (MethodSymbol)basicModifiers3.GetMembers("M6").Single(); Assert.False(basicModifiers3_M1.IsAbstract); Assert.False(basicModifiers3_M1.IsVirtual); Assert.False(basicModifiers3_M1.IsSealed); Assert.True(basicModifiers3_M1.HidesBaseMethodsByName); Assert.True(basicModifiers3_M1.IsOverride); Assert.False(basicModifiers3_M6.IsAbstract); Assert.False(basicModifiers3_M6.IsVirtual); Assert.False(basicModifiers3_M6.IsSealed); Assert.False(basicModifiers3_M6.HidesBaseMethodsByName); Assert.True(basicModifiers3_M6.IsOverride); var csharpModifiers1 = module3.GlobalNamespace.GetTypeMembers("Modifiers1").Single(); var csharpModifiers1_M1 = (MethodSymbol)csharpModifiers1.GetMembers("M1").Single(); var csharpModifiers1_M2 = (MethodSymbol)csharpModifiers1.GetMembers("M2").Single(); var csharpModifiers1_M3 = (MethodSymbol)csharpModifiers1.GetMembers("M3").Single(); var csharpModifiers1_M4 = (MethodSymbol)csharpModifiers1.GetMembers("M4").Single(); Assert.True(csharpModifiers1_M1.IsAbstract); Assert.False(csharpModifiers1_M1.IsVirtual); Assert.False(csharpModifiers1_M1.IsSealed); Assert.False(csharpModifiers1_M1.HidesBaseMethodsByName); Assert.False(csharpModifiers1_M1.IsOverride); Assert.False(csharpModifiers1_M2.IsAbstract); Assert.True(csharpModifiers1_M2.IsVirtual); Assert.False(csharpModifiers1_M2.IsSealed); Assert.False(csharpModifiers1_M2.HidesBaseMethodsByName); Assert.False(csharpModifiers1_M2.IsOverride); Assert.False(csharpModifiers1_M3.IsAbstract); Assert.False(csharpModifiers1_M3.IsVirtual); Assert.False(csharpModifiers1_M3.IsSealed); Assert.False(csharpModifiers1_M3.HidesBaseMethodsByName); Assert.False(csharpModifiers1_M3.IsOverride); Assert.False(csharpModifiers1_M4.IsAbstract); Assert.True(csharpModifiers1_M4.IsVirtual); Assert.False(csharpModifiers1_M4.IsSealed); Assert.False(csharpModifiers1_M4.HidesBaseMethodsByName); Assert.False(csharpModifiers1_M4.IsOverride); var csharpModifiers2 = module3.GlobalNamespace.GetTypeMembers("Modifiers2").Single(); var csharpModifiers2_M1 = (MethodSymbol)csharpModifiers2.GetMembers("M1").Single(); var csharpModifiers2_M2 = (MethodSymbol)csharpModifiers2.GetMembers("M2").Single(); var csharpModifiers2_M3 = (MethodSymbol)csharpModifiers2.GetMembers("M3").Single(); Assert.False(csharpModifiers2_M1.IsAbstract); Assert.False(csharpModifiers2_M1.IsVirtual); Assert.True(csharpModifiers2_M1.IsSealed); Assert.False(csharpModifiers2_M1.HidesBaseMethodsByName); Assert.True(csharpModifiers2_M1.IsOverride); Assert.True(csharpModifiers2_M2.IsAbstract); Assert.False(csharpModifiers2_M2.IsVirtual); Assert.False(csharpModifiers2_M2.IsSealed); Assert.False(csharpModifiers2_M2.HidesBaseMethodsByName); Assert.True(csharpModifiers2_M2.IsOverride); Assert.False(csharpModifiers2_M3.IsAbstract); Assert.True(csharpModifiers2_M3.IsVirtual); Assert.False(csharpModifiers2_M3.IsSealed); Assert.False(csharpModifiers2_M3.HidesBaseMethodsByName); Assert.False(csharpModifiers2_M3.IsOverride); var csharpModifiers3 = module3.GlobalNamespace.GetTypeMembers("Modifiers3").Single(); var csharpModifiers3_M1 = (MethodSymbol)csharpModifiers3.GetMembers("M1").Single(); var csharpModifiers3_M3 = (MethodSymbol)csharpModifiers3.GetMembers("M3").Single(); var csharpModifiers3_M4 = (MethodSymbol)csharpModifiers3.GetMembers("M4").Single(); Assert.False(csharpModifiers3_M1.IsAbstract); Assert.False(csharpModifiers3_M1.IsVirtual); Assert.False(csharpModifiers3_M1.IsSealed); Assert.False(csharpModifiers3_M1.HidesBaseMethodsByName); Assert.True(csharpModifiers3_M1.IsOverride); Assert.False(csharpModifiers3_M3.IsAbstract); Assert.False(csharpModifiers3_M3.IsVirtual); Assert.False(csharpModifiers3_M3.IsSealed); Assert.False(csharpModifiers3_M3.HidesBaseMethodsByName); Assert.False(csharpModifiers3_M3.IsOverride); Assert.True(csharpModifiers3_M4.IsAbstract); Assert.False(csharpModifiers3_M4.IsVirtual); Assert.False(csharpModifiers3_M4.IsSealed); Assert.False(csharpModifiers3_M4.HidesBaseMethodsByName); Assert.False(csharpModifiers3_M4.IsOverride); var byrefReturnMethod = byrefReturn.GlobalNamespace.GetTypeMembers("ByRefReturn").Single().GetMembers("M").OfType<MethodSymbol>().Single(); Assert.Equal(RefKind.Ref, byrefReturnMethod.RefKind); Assert.Equal(TypeKind.Struct, byrefReturnMethod.ReturnType.TypeKind); } [Fact] public void TestExplicitImplementationSimple() { var assembly = MetadataTestHelpers.GetSymbolForReference( TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp); var globalNamespace = assembly.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Class").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces.Contains(@interface)); var classMethod = (MethodSymbol)@class.GetMembers("Interface.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, explicitImpl); } [Fact] public void TestExplicitImplementationMultiple() { var assembly = MetadataTestHelpers.GetSymbolForReference( TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL); var globalNamespace = assembly.GlobalNamespace; var interface1 = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I1").Single(); Assert.Equal(TypeKind.Interface, interface1.TypeKind); var interface1Method = (MethodSymbol)interface1.GetMembers("Method1").Single(); var interface2 = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I2").Single(); Assert.Equal(TypeKind.Interface, interface2.TypeKind); var interface2Method = (MethodSymbol)interface2.GetMembers("Method2").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("C").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces.Contains(interface1)); Assert.True(@class.Interfaces.Contains(interface2)); var classMethod = (MethodSymbol)@class.GetMembers("Method").Single(); // the method is considered to be Ordinary Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind); // because it has name without '.' var explicitImpls = classMethod.ExplicitInterfaceImplementations; Assert.Equal(2, explicitImpls.Length); Assert.Equal(interface1Method, explicitImpls[0]); Assert.Equal(interface2Method, explicitImpls[1]); } [Fact] public void TestExplicitImplementationGeneric() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences( mrefs: new[] { TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp, }); var globalNamespace = assemblies.ElementAt(1).GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Last(); //this assumes decl order Assert.Equal("void IGeneric<T>.Method<U>(T t, U u)", interfaceMethod.ToTestDisplayString()); //make sure we got the one we expected var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Generic").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var substitutedInterface = @class.Interfaces.Single(); Assert.Equal(@interface, substitutedInterface.ConstructedFrom); var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Last(); //this assumes decl order Assert.Equal("void IGeneric<S>.Method<U>(S t, U u)", substitutedInterfaceMethod.ToTestDisplayString()); //make sure we got the one we expected Assert.Equal(interfaceMethod, substitutedInterfaceMethod.OriginalDefinition); var classMethod = (MethodSymbol)@class.GetMembers("IGeneric<S>.Method").Last(); //this assumes decl order Assert.Equal("void Generic<S>.IGeneric<S>.Method<V>(S s, V v)", classMethod.ToTestDisplayString()); //make sure we got the one we expected Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(substitutedInterfaceMethod, explicitImpl); } [Fact] public void TestExplicitImplementationConstructed() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences( new[] { TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp, }); var globalNamespace = assemblies.ElementAt(1).GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single(); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var interfaceMethod = (MethodSymbol)@interface.GetMembers("Method").Last(); //this assumes decl order Assert.Equal("void IGeneric<T>.Method<U>(T t, U u)", interfaceMethod.ToTestDisplayString()); //make sure we got the one we expected var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Constructed").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var substitutedInterface = @class.Interfaces.Single(); Assert.Equal(@interface, substitutedInterface.ConstructedFrom); var substitutedInterfaceMethod = (MethodSymbol)substitutedInterface.GetMembers("Method").Last(); //this assumes decl order Assert.Equal("void IGeneric<System.Int32>.Method<U>(System.Int32 t, U u)", substitutedInterfaceMethod.ToTestDisplayString()); //make sure we got the one we expected Assert.Equal(interfaceMethod, substitutedInterfaceMethod.OriginalDefinition); var classMethod = (MethodSymbol)@class.GetMembers("IGeneric<System.Int32>.Method").Last(); //this assumes decl order Assert.Equal("void Constructed.IGeneric<System.Int32>.Method<W>(System.Int32 i, W w)", classMethod.ToTestDisplayString()); //make sure we got the one we expected Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(substitutedInterfaceMethod, explicitImpl); } [Fact] public void TestExplicitImplementationInterfaceCycleSuccess() { var assembly = MetadataTestHelpers.GetSymbolForReference( TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL); var globalNamespace = assembly.GlobalNamespace; var cyclicInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ImplementsSelf").Single(); Assert.Equal(TypeKind.Interface, cyclicInterface.TypeKind); var implementedInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("I1").Single(); Assert.Equal(TypeKind.Interface, implementedInterface.TypeKind); var interface2Method = (MethodSymbol)implementedInterface.GetMembers("Method1").Single(); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("InterfaceCycleSuccess").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces.Contains(cyclicInterface)); Assert.True(@class.Interfaces.Contains(implementedInterface)); var classMethod = (MethodSymbol)@class.GetMembers("Method").Single(); // the method is considered to be Ordinary Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind); // because it has name without '.' var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interface2Method, explicitImpl); } [Fact] public void TestExplicitImplementationInterfaceCycleFailure() { var assembly = MetadataTestHelpers.GetSymbolForReference( TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL); var globalNamespace = assembly.GlobalNamespace; var cyclicInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ImplementsSelf").Single(); Assert.Equal(TypeKind.Interface, cyclicInterface.TypeKind); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("InterfaceCycleFailure").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.True(@class.Interfaces.Contains(cyclicInterface)); var classMethod = (MethodSymbol)@class.GetMembers("Method").Single(); //we couldn't find an interface method that's explicitly implemented, so we have no reason to believe the method isn't ordinary Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind); var explicitImpls = classMethod.ExplicitInterfaceImplementations; Assert.False(explicitImpls.Any()); } /// <summary> /// A type def explicitly implements an interface, also a type def, but only /// indirectly, via a type ref. /// </summary> [Fact] public void TestExplicitImplementationDefRefDef() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences( new[] { TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp, }); var globalNamespace = assemblies.ElementAt(1).GlobalNamespace; var defInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single(); Assert.Equal(TypeKind.Interface, defInterface.TypeKind); var defInterfaceMethod = (MethodSymbol)defInterface.GetMembers("Method").Single(); var refInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGenericInterface").Single(); Assert.Equal(TypeKind.Interface, defInterface.TypeKind); Assert.True(refInterface.Interfaces.Contains(defInterface)); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IndirectImplementation").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); var classInterfacesConstructedFrom = @class.Interfaces.Select(i => i.ConstructedFrom); Assert.Equal(2, classInterfacesConstructedFrom.Count()); Assert.Contains(defInterface, classInterfacesConstructedFrom); Assert.Contains(refInterface, classInterfacesConstructedFrom); var classMethod = (MethodSymbol)@class.GetMembers("Interface.Method").Single(); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, classMethod.MethodKind); var explicitImpl = classMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(defInterfaceMethod, explicitImpl); } /// <summary> /// IL type explicitly overrides a class (vs interface) method. /// ExplicitInterfaceImplementations should be empty. /// </summary> [Fact] public void TestExplicitImplementationOfClassMethod() { var assembly = MetadataTestHelpers.GetSymbolForReference( TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL); var globalNamespace = assembly.GlobalNamespace; var baseClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementedClass").Single(); Assert.Equal(TypeKind.Class, baseClass.TypeKind); var derivedClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementsAClass").Single(); Assert.Equal(TypeKind.Class, derivedClass.TypeKind); Assert.Equal(baseClass, derivedClass.BaseType); var derivedClassMethod = (MethodSymbol)derivedClass.GetMembers("Method").Single(); Assert.Equal(MethodKind.Ordinary, derivedClassMethod.MethodKind); Assert.Equal(0, derivedClassMethod.ExplicitInterfaceImplementations.Length); } /// <summary> /// IL type explicitly overrides an interface method on an unrelated interface. /// ExplicitInterfaceImplementations should be empty. /// </summary> [Fact] public void TestExplicitImplementationOfUnrelatedInterfaceMethod() { var assembly = MetadataTestHelpers.GetSymbolForReference( TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL); var globalNamespace = assembly.GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IUnrelated").First(); //decl order Assert.Equal(0, @interface.Arity); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementsUnrelatedInterfaceMethods").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.Equal(0, @class.AllInterfaces.Length); var classMethod = (MethodSymbol)@class.GetMembers("Method1").Single(); Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind); Assert.Equal(0, classMethod.ExplicitInterfaceImplementations.Length); var classGenericMethod = (MethodSymbol)@class.GetMembers("Method1").Single(); Assert.Equal(MethodKind.Ordinary, classGenericMethod.MethodKind); Assert.Equal(0, classGenericMethod.ExplicitInterfaceImplementations.Length); } /// <summary> /// IL type explicitly overrides an interface method on an unrelated generic interface. /// ExplicitInterfaceImplementations should be empty. /// </summary> [Fact] public void TestExplicitImplementationOfUnrelatedGenericInterfaceMethod() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences( new[] { TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.IL, }); var globalNamespace = assemblies.ElementAt(1).GlobalNamespace; var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IUnrelated").Last(); //decl order Assert.Equal(1, @interface.Arity); Assert.Equal(TypeKind.Interface, @interface.TypeKind); var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("ExplicitlyImplementsUnrelatedInterfaceMethods").Single(); Assert.Equal(TypeKind.Class, @class.TypeKind); Assert.Equal(0, @class.AllInterfaces.Length); var classMethod = (MethodSymbol)@class.GetMembers("Method2").Single(); Assert.Equal(MethodKind.Ordinary, classMethod.MethodKind); Assert.Equal(0, classMethod.ExplicitInterfaceImplementations.Length); var classGenericMethod = (MethodSymbol)@class.GetMembers("Method2").Single(); Assert.Equal(MethodKind.Ordinary, classGenericMethod.MethodKind); Assert.Equal(0, classGenericMethod.ExplicitInterfaceImplementations.Length); } /// <summary> /// In metadata, nested types implicitly share all type parameters of their containing types. /// This results in some extra computations when mapping a type parameter position to a type /// parameter symbol. /// </summary> [Fact] public void TestTypeParameterPositions() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences( new[] { TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Methods.CSharp, }); var globalNamespace = assemblies.ElementAt(1).GlobalNamespace; var outerInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric2").Single(); Assert.Equal(1, outerInterface.Arity); Assert.Equal(TypeKind.Interface, outerInterface.TypeKind); var outerInterfaceMethod = outerInterface.GetMembers().Single(); var outerClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Outer").Single(); Assert.Equal(1, outerClass.Arity); Assert.Equal(TypeKind.Class, outerClass.TypeKind); var innerInterface = (NamedTypeSymbol)outerClass.GetTypeMembers("IInner").Single(); Assert.Equal(1, innerInterface.Arity); Assert.Equal(TypeKind.Interface, innerInterface.TypeKind); var innerInterfaceMethod = innerInterface.GetMembers().Single(); var innerClass1 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner1").Single(); CheckInnerClassHelper(innerClass1, "IGeneric2<A>.Method", outerInterfaceMethod); var innerClass2 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner2").Single(); CheckInnerClassHelper(innerClass2, "IGeneric2<T>.Method", outerInterfaceMethod); var innerClass3 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner3").Single(); CheckInnerClassHelper(innerClass3, "Outer<T>.IInner<C>.Method", innerInterfaceMethod); var innerClass4 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner4").Single(); CheckInnerClassHelper(innerClass4, "Outer<T>.IInner<T>.Method", innerInterfaceMethod); } private static void CheckInnerClassHelper(NamedTypeSymbol innerClass, string methodName, Symbol interfaceMethod) { var @interface = interfaceMethod.ContainingType; Assert.Equal(1, innerClass.Arity); Assert.Equal(TypeKind.Class, innerClass.TypeKind); Assert.Equal(@interface, innerClass.Interfaces.Single().ConstructedFrom); var innerClassMethod = (MethodSymbol)innerClass.GetMembers(methodName).Single(); var innerClassImplementingMethod = innerClassMethod.ExplicitInterfaceImplementations.Single(); Assert.Equal(interfaceMethod, innerClassImplementingMethod.OriginalDefinition); Assert.Equal(@interface, innerClassImplementingMethod.ContainingType.ConstructedFrom); } [Fact] public void TestVirtualnessFlags_Invoke() { var source = @" class Invoke { void Foo(MetadataModifiers m) { m.M00(); m.M01(); m.M02(); m.M03(); m.M04(); m.M05(); m.M06(); m.M07(); m.M08(); m.M09(); m.M10(); m.M11(); m.M12(); m.M13(); m.M14(); m.M15(); } } "; var compilation = CreateStandardCompilation(source, new[] { TestReferences.SymbolsTests.Methods.ILMethods }); compilation.VerifyDiagnostics(); // No errors, as in Dev10 } [Fact] public void TestVirtualnessFlags_NoOverride() { var source = @" class Abstract : MetadataModifiers { //CS0534 for methods 2, 5, 8, 9, 11, 12, 14, 15 } "; var compilation = CreateStandardCompilation(source, new[] { TestReferences.SymbolsTests.Methods.ILMethods }); compilation.VerifyDiagnostics( // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M02()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M02()"), // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M05()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M05()"), // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M08()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M08()"), // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M09()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M09()"), // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M11()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M11()"), // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M12()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M12()"), // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M14()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M14()"), // (2,7): error CS0534: 'Abstract' does not implement inherited abstract member 'MetadataModifiers.M15()' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Abstract").WithArguments("Abstract", "MetadataModifiers.M15()")); } [Fact] public void TestVirtualnessFlags_Override() { var source = @" class Override : MetadataModifiers { public override void M00() { } //CS0506 public override void M01() { } //CS0506 public override void M02() { } public override void M03() { } public override void M04() { } //CS0506 public override void M05() { } public override void M06() { } public override void M07() { } //CS0506 public override void M08() { } public override void M09() { } public override void M10() { } //CS0239 (Dev10 reports CS0506, presumably because MetadataModifiers.M10 isn't overriding anything) public override void M11() { } public override void M12() { } public override void M13() { } //CS0506 public override void M14() { } public override void M15() { } } "; var compilation = CreateStandardCompilation(source, new[] { TestReferences.SymbolsTests.Methods.ILMethods }); compilation.VerifyDiagnostics( // (4,26): error CS0506: 'Override.M00()': cannot override inherited member 'MetadataModifiers.M00()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M00").WithArguments("Override.M00()", "MetadataModifiers.M00()"), // (5,26): error CS0506: 'Override.M01()': cannot override inherited member 'MetadataModifiers.M01()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M01").WithArguments("Override.M01()", "MetadataModifiers.M01()"), // (8,26): error CS0506: 'Override.M04()': cannot override inherited member 'MetadataModifiers.M04()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M04").WithArguments("Override.M04()", "MetadataModifiers.M04()"), // (11,26): error CS0506: 'Override.M07()': cannot override inherited member 'MetadataModifiers.M07()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M07").WithArguments("Override.M07()", "MetadataModifiers.M07()"), // (14,26): error CS0239: 'Override.M10()': cannot override inherited member 'MetadataModifiers.M10()' because it is sealed Diagnostic(ErrorCode.ERR_CantOverrideSealed, "M10").WithArguments("Override.M10()", "MetadataModifiers.M10()"), // (17,26): error CS0506: 'Override.M13()': cannot override inherited member 'MetadataModifiers.M13()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M13").WithArguments("Override.M13()", "MetadataModifiers.M13()")); } [ClrOnlyFact] public void TestVirtualnessFlags_CSharpRepresentation() { // All combinations of VirtualContract, NewSlotVTable, AbstractImpl, and FinalContract - without explicit overriding // NOTE: some won't peverify (newslot/final/abstract without virtual, abstract with final) CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, 0, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Override, MethodAttributes.Virtual, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.Final, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Virtual, MethodAttributes.Virtual | MethodAttributes.NewSlot, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.SealedOverride, MethodAttributes.Virtual | MethodAttributes.Final, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: false); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: false); // All combinations of VirtualContract, NewSlotVTable, AbstractImpl, and FinalContract - with explicit overriding CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, 0, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.Override, MethodAttributes.Virtual, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.Final, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.Override, MethodAttributes.Virtual | MethodAttributes.NewSlot, isExplicitOverride: true); //differs from above CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.SealedOverride, MethodAttributes.Virtual | MethodAttributes.Final, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.NonVirtual, MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.Abstract, MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true); CheckLoadingVirtualnessFlags(SymbolVirtualness.SealedOverride, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Final, isExplicitOverride: true); //differs from above CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract, isExplicitOverride: true); //differs from above CheckLoadingVirtualnessFlags(SymbolVirtualness.AbstractOverride, MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Abstract | MethodAttributes.Final, isExplicitOverride: true); //differs from above } private void CheckLoadingVirtualnessFlags(SymbolVirtualness expectedVirtualness, MethodAttributes flags, bool isExplicitOverride) { const string ilTemplate = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object {{ .method public hidebysig newslot virtual instance void M() cil managed {{ ret }} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed {{ ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret }} }} // end of class Base .class public abstract auto ansi beforefieldinit Derived extends Base {{ .method public hidebysig{0} instance void M() cil managed {{ {1} {2} }} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed {{ ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret }} }} // end of class Derived "; string modifiers = ""; if ((flags & MethodAttributes.NewSlot) != 0) { modifiers += " newslot"; } if ((flags & MethodAttributes.Abstract) != 0) { modifiers += " abstract"; } if ((flags & MethodAttributes.Virtual) != 0) { modifiers += " virtual"; } if ((flags & MethodAttributes.Final) != 0) { modifiers += " final"; } string explicitOverride = isExplicitOverride ? ".override Base::M" : ""; string body = ((flags & MethodAttributes.Abstract) != 0) ? "" : "ret"; CompileWithCustomILSource("", string.Format(ilTemplate, modifiers, explicitOverride, body), compilation => { var derivedClass = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("Derived"); var method = derivedClass.GetMember<MethodSymbol>("M"); switch (expectedVirtualness) { case SymbolVirtualness.NonVirtual: Assert.False(method.IsVirtual); Assert.False(method.IsOverride); Assert.False(method.IsAbstract); Assert.False(method.IsSealed); break; case SymbolVirtualness.Virtual: Assert.True(method.IsVirtual); Assert.False(method.IsOverride); Assert.False(method.IsAbstract); Assert.False(method.IsSealed); break; case SymbolVirtualness.Override: Assert.False(method.IsVirtual); Assert.True(method.IsOverride); Assert.False(method.IsAbstract); Assert.False(method.IsSealed); break; case SymbolVirtualness.SealedOverride: Assert.False(method.IsVirtual); Assert.True(method.IsOverride); Assert.False(method.IsAbstract); Assert.True(method.IsSealed); break; case SymbolVirtualness.Abstract: Assert.False(method.IsVirtual); Assert.False(method.IsOverride); Assert.True(method.IsAbstract); Assert.False(method.IsSealed); break; case SymbolVirtualness.AbstractOverride: Assert.False(method.IsVirtual); Assert.True(method.IsOverride); Assert.True(method.IsAbstract); Assert.False(method.IsSealed); break; default: Assert.False(true, "Unexpected enum value " + expectedVirtualness); break; } }); } // Note that not all combinations are possible. private enum SymbolVirtualness { NonVirtual, Virtual, Override, SealedOverride, Abstract, AbstractOverride, } [Fact] public void Constructors1() { string ilSource = @" .class private auto ansi cls1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public specialname rtspecialname static void .cctor() cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } } .class private auto ansi Instance_vs_Static extends [mscorlib]System.Object { .method public specialname rtspecialname static void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public specialname rtspecialname instance void .cctor() cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } } .class private auto ansi ReturnAValue1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance int32 .ctor(int32 x) cil managed { // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } .method private specialname rtspecialname static int32 .cctor() cil managed { // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } } .class private auto ansi ReturnAValue2 extends [mscorlib]System.Object { .method public specialname rtspecialname static int32 .cctor() cil managed { // Code size 6 (0x6) .maxstack 1 .locals init (int32 V_0) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0004 IL_0004: ldloc.0 IL_0005: ret } } .class private auto ansi Generic1 extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor<T>() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method private specialname rtspecialname static void .cctor<T>() cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } } .class private auto ansi Generic2 extends [mscorlib]System.Object { .method public specialname rtspecialname static void .cctor<T>() cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } } .class private auto ansi HasParameter extends [mscorlib]System.Object { .method public specialname rtspecialname static void .cctor(int32 x) cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } } .class private auto ansi Virtual extends [mscorlib]System.Object { .method public newslot strict virtual specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } "; var compilation = CreateCompilationWithCustomILSource("", ilSource); foreach (var m in compilation.GetTypeByMetadataName("cls1").GetMembers()) { Assert.Equal(m.Name == ".cctor" ? MethodKind.StaticConstructor : MethodKind.Constructor, ((MethodSymbol)m).MethodKind); } foreach (var m in compilation.GetTypeByMetadataName("Instance_vs_Static").GetMembers()) { Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind); } foreach (var m in compilation.GetTypeByMetadataName("ReturnAValue1").GetMembers()) { Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind); } foreach (var m in compilation.GetTypeByMetadataName("ReturnAValue2").GetMembers()) { Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind); } foreach (var m in compilation.GetTypeByMetadataName("Generic1").GetMembers()) { Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind); } foreach (var m in compilation.GetTypeByMetadataName("Generic2").GetMembers()) { Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind); } foreach (var m in compilation.GetTypeByMetadataName("HasParameter").GetMembers()) { Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind); } foreach (var m in compilation.GetTypeByMetadataName("Virtual").GetMembers()) { Assert.Equal(MethodKind.Ordinary, ((MethodSymbol)m).MethodKind); } } [Fact] public void OverridesAndLackOfNewSlot() { string ilSource = @" .class interface public abstract auto ansi serializable Microsoft.FSharp.Control.IDelegateEvent`1<([mscorlib]System.Delegate) TDelegate> { .method public hidebysig abstract virtual instance void AddHandler(!TDelegate 'handler') cil managed { } // end of method IDelegateEvent`1::AddHandler .method public hidebysig abstract virtual instance void RemoveHandler(!TDelegate 'handler') cil managed { } // end of method IDelegateEvent`1::RemoveHandler } // end of class Microsoft.FSharp.Control.IDelegateEvent`1 "; var compilation = CreateCompilationWithCustomILSource("", ilSource); foreach (var m in compilation.GetTypeByMetadataName("Microsoft.FSharp.Control.IDelegateEvent`1").GetMembers()) { Assert.False(((MethodSymbol)m).IsVirtual); Assert.True(((MethodSymbol)m).IsAbstract); Assert.False(((MethodSymbol)m).IsOverride); } } [Fact] public void MemberSignature_LongFormType() { string source = @" public class D { public static void Main() { string s = C.RT(); double d = C.VT(); } } "; var longFormRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.LongTypeFormInSignature); var c = CreateStandardCompilation(source, new[] { longFormRef }); c.VerifyDiagnostics( // (6,20): error CS0570: 'C.RT()' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "RT").WithArguments("C.RT()"), // (7,20): error CS0570: 'C.VT()' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "VT").WithArguments("C.VT()")); } [WorkItem(7971, "https://github.com/dotnet/roslyn/issues/7971")] [Fact(Skip = "7971")] public void MemberSignature_CycleTrhuTypeSpecInCustomModifiers() { string source = @" class P { static void Main() { User.X(new Extender()); } } "; var lib = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.Signatures.SignatureCycle2); var c = CreateStandardCompilation(source, new[] { lib }); c.VerifyDiagnostics(); } [WorkItem(7970, "https://github.com/dotnet/roslyn/issues/7970")] [Fact] public void MemberSignature_TypeSpecInWrongPlace() { string source = @" class P { static void Main() { User.X(new System.Collections.Generic.List<int>()); } } "; var lib = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.Signatures.TypeSpecInWrongPlace); var c = CreateStandardCompilation(source, new[] { lib }); c.VerifyDiagnostics( // (6,14): error CS0570: 'User.X(?)' is not supported by the language // User.X(new System.Collections.Generic.List<int>()); Diagnostic(ErrorCode.ERR_BindToBogus, "X").WithArguments("User.X(?)")); } [WorkItem(666162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666162")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void Repro666162() { var il = @" .assembly extern mscorlib { } .assembly extern Missing { } .assembly Lib { } .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig instance class Test modreq (bool)& M() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Test "; var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateCompilation("", new[] { ilRef }); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method = type.GetMember<MethodSymbol>("M"); Assert.NotNull(method.ReturnType); } [Fact, WorkItem(217681, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217681")] public void LoadingMethodWithPublicAndPrivateAccessibility() { string source = @" public class D { public static void Main() { new C().M(); System.Console.WriteLine(new C().F); new C.C2().M2(); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.PublicAndPrivateFlags) }; var comp = CreateStandardCompilation(source, references: references); // The method, field and nested type with public and private accessibility flags get loaded as private. comp.VerifyDiagnostics( // (6,15): error CS0122: 'C.M()' is inaccessible due to its protection level // new C().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("C.M()").WithLocation(6, 15), // (7,40): error CS0122: 'C.F' is inaccessible due to its protection level // System.Console.WriteLine(new C().F); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("C.F").WithLocation(7, 40), // (8,13): error CS0122: 'C.C2' is inaccessible due to its protection level // new C.C2().M2(); Diagnostic(ErrorCode.ERR_BadAccess, "C2").WithArguments("C.C2").WithLocation(8, 13) ); } } }
// 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.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddInt32() { var test = new SimpleBinaryOpTest__AddInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.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 (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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__AddInt32 { 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(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (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<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, 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<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddInt32 testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddInt32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleBinaryOpTest__AddInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_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 = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_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(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(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<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddInt32(); var result = AdvSimd.Add(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__AddInt32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(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 = AdvSimd.Add(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 = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&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<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<Int32>(Vector128<Int32>, Vector128<Int32>): {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 Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace CRMWeb { public static class TokenHelper { #region public methods /// <summary> /// Configures .Net to trust all certificates when making network calls. This is used so that calls /// to an https SharePoint server without a valid certificate are not rejected. This should only be used during /// testing, and should never be used in a production app. /// </summary> public static void TrustAllCertificates() { //Trust all certificates ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName]; if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName]; } return null; } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName]; if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName]; } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (ClientCertificate != null) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (ClientCertificate != null) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; const string bearer = "Bearer realm=\""; int realmIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal) + bearer.Length; if (bearerResponseHeader.Length > realmIndex) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } #endregion #region private fields // // Configuration Constants // private const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; private const int TokenLifetimeMinutes = 1000000; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.AddMinutes(TokenLifetimeMinutes), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } private static string EnsureTrailingSlash(string url) { if (!String.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } public class OAuthTokenPair { public string AccessToken; public string RefreshToken; } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
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 SINF_proj.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // 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. // namespace NLog.UnitTests.Conditions { using System; using System.Globalization; using System.IO; #if !SILVERLIGHT using System.Runtime.Serialization.Formatters.Binary; #endif using NLog.Conditions; using NLog.Config; using Xunit; public class ConditionEvaluatorTests : NLogTestBase { [Fact] public void BooleanOperatorTest() { AssertEvaluationResult(false, "false or false"); AssertEvaluationResult(true, "false or true"); AssertEvaluationResult(true, "true or false"); AssertEvaluationResult(true, "true or true"); AssertEvaluationResult(false, "false and false"); AssertEvaluationResult(false, "false and true"); AssertEvaluationResult(false, "true and false"); AssertEvaluationResult(true, "true and true"); AssertEvaluationResult(false, "not true"); AssertEvaluationResult(true, "not false"); AssertEvaluationResult(false, "not not false"); AssertEvaluationResult(true, "not not true"); } [Fact] public void ConditionMethodsTest() { AssertEvaluationResult(true, "starts-with('foobar','foo')"); AssertEvaluationResult(false, "starts-with('foobar','bar')"); AssertEvaluationResult(true, "ends-with('foobar','bar')"); AssertEvaluationResult(false, "ends-with('foobar','foo')"); AssertEvaluationResult(0, "length('')"); AssertEvaluationResult(4, "length('${level}')"); AssertEvaluationResult(false, "equals(1, 2)"); AssertEvaluationResult(true, "equals(3.14, 3.14)"); AssertEvaluationResult(true, "contains('foobar','ooba')"); AssertEvaluationResult(false, "contains('foobar','oobe')"); AssertEvaluationResult(false, "contains('','foo')"); AssertEvaluationResult(true, "contains('foo','')"); } [Fact] public void ConditionMethodNegativeTest1() { try { AssertEvaluationResult(true, "starts-with('foobar')"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'starts-with'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'starts-with' requires between 2 and 3 parameters, but passed 1.", ex.InnerException.Message); } } [Fact] public void ConditionMethodNegativeTest2() { try { AssertEvaluationResult(true, "starts-with('foobar','baz','qux','zzz')"); Assert.True(false, "Expected exception"); } catch (ConditionParseException ex) { Assert.Equal("Cannot resolve function 'starts-with'", ex.Message); Assert.NotNull(ex.InnerException); Assert.Equal("Condition method 'starts-with' requires between 2 and 3 parameters, but passed 4.", ex.InnerException.Message); } } [Fact] public void LiteralTest() { AssertEvaluationResult(null, "null"); AssertEvaluationResult(0, "0"); AssertEvaluationResult(3, "3"); AssertEvaluationResult(3.1415, "3.1415"); AssertEvaluationResult(-1, "-1"); AssertEvaluationResult(-3.1415, "-3.1415"); AssertEvaluationResult(true, "true"); AssertEvaluationResult(false, "false"); AssertEvaluationResult(string.Empty, "''"); AssertEvaluationResult("x", "'x'"); AssertEvaluationResult("d'Artagnan", "'d''Artagnan'"); } [Fact] public void LogEventInfoPropertiesTest() { AssertEvaluationResult(LogLevel.Warn, "level"); AssertEvaluationResult("some message", "message"); AssertEvaluationResult("MyCompany.Product.Class", "logger"); } [Fact] public void RelationalOperatorTest() { AssertEvaluationResult(true, "1 < 2"); AssertEvaluationResult(false, "1 < 1"); AssertEvaluationResult(true, "2 > 1"); AssertEvaluationResult(false, "1 > 1"); AssertEvaluationResult(true, "1 <= 2"); AssertEvaluationResult(false, "1 <= 0"); AssertEvaluationResult(true, "2 >= 1"); AssertEvaluationResult(false, "0 >= 1"); AssertEvaluationResult(true, "2 == 2"); AssertEvaluationResult(false, "2 == 3"); AssertEvaluationResult(true, "2 != 3"); AssertEvaluationResult(false, "2 != 2"); AssertEvaluationResult(false, "1 < null"); AssertEvaluationResult(true, "1 > null"); AssertEvaluationResult(true, "null < 1"); AssertEvaluationResult(false, "null > 1"); AssertEvaluationResult(true, "null == null"); AssertEvaluationResult(false, "null != null"); AssertEvaluationResult(false, "null == 1"); AssertEvaluationResult(false, "1 == null"); AssertEvaluationResult(true, "null != 1"); AssertEvaluationResult(true, "1 != null"); } [Fact] public void UnsupportedRelationalOperatorTest() { var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1)); Assert.Throws<ConditionEvaluationException>(() => cond.Evaluate(LogEventInfo.CreateNullEvent())); } [Fact] public void UnsupportedRelationalOperatorTest2() { var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1)); Assert.Throws<NotSupportedException>(() => cond.ToString()); } [Fact] public void MethodWithLogEventInfoTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("IsValid()", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void TypePromotionTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/01'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(1)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("'42' == 42", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("42 == '42'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToDouble(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToDouble(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToSingle(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToSingle(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToDecimal(3) == 3", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("3 == ToDecimal(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(3)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("true == ToInt16(1)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(true, ConditionParser.ParseExpression("ToInt16(1) == true", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/02'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(2)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("'42' == 43", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("42 == '43'", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDouble(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToDouble(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToSingle(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToSingle(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToDecimal(3) == 4", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("3 == ToDecimal(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("false == ToInt16(4)", factories).Evaluate(CreateWellKnownContext())); Assert.Equal(false, ConditionParser.ParseExpression("ToInt16(1) == false", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void TypePromotionNegativeTest1() { var factories = SetupConditionMethods(); Assert.Throws<ConditionEvaluationException>(() => ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '20xx/01/01'", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void TypePromotionNegativeTest2() { var factories = SetupConditionMethods(); Assert.Throws<ConditionEvaluationException>(() => ConditionParser.ParseExpression("GetGuid() == ToInt16(1)", factories).Evaluate(CreateWellKnownContext())); } [Fact] public void ExceptionTest1() { var ex1 = new ConditionEvaluationException(); Assert.NotNull(ex1.Message); } [Fact] public void ExceptionTest2() { var ex1 = new ConditionEvaluationException("msg"); Assert.Equal("msg", ex1.Message); } [Fact] public void ExceptionTest3() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionEvaluationException("msg", inner); Assert.Equal("msg", ex1.Message); Assert.Same(inner, ex1.InnerException); } #if !SILVERLIGHT [Fact] public void ExceptionTest4() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionEvaluationException("msg", inner); BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ex1); ms.Position = 0; Exception ex2 = (Exception)bf.Deserialize(ms); Assert.Equal("msg", ex2.Message); Assert.Equal("f", ex2.InnerException.Message); } #endif [Fact] public void ExceptionTest11() { var ex1 = new ConditionParseException(); Assert.NotNull(ex1.Message); } [Fact] public void ExceptionTest12() { var ex1 = new ConditionParseException("msg"); Assert.Equal("msg", ex1.Message); } [Fact] public void ExceptionTest13() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionParseException("msg", inner); Assert.Equal("msg", ex1.Message); Assert.Same(inner, ex1.InnerException); } #if !SILVERLIGHT [Fact] public void ExceptionTest14() { var inner = new InvalidOperationException("f"); var ex1 = new ConditionParseException("msg", inner); BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ex1); ms.Position = 0; Exception ex2 = (Exception)bf.Deserialize(ms); Assert.Equal("msg", ex2.Message); Assert.Equal("f", ex2.InnerException.Message); } #endif private static ConfigurationItemFactory SetupConditionMethods() { var factories = new ConfigurationItemFactory(); factories.ConditionMethods.RegisterDefinition("GetGuid", typeof(MyConditionMethods).GetMethod("GetGuid")); factories.ConditionMethods.RegisterDefinition("ToInt16", typeof(MyConditionMethods).GetMethod("ToInt16")); factories.ConditionMethods.RegisterDefinition("ToInt32", typeof(MyConditionMethods).GetMethod("ToInt32")); factories.ConditionMethods.RegisterDefinition("ToInt64", typeof(MyConditionMethods).GetMethod("ToInt64")); factories.ConditionMethods.RegisterDefinition("ToDouble", typeof(MyConditionMethods).GetMethod("ToDouble")); factories.ConditionMethods.RegisterDefinition("ToSingle", typeof(MyConditionMethods).GetMethod("ToSingle")); factories.ConditionMethods.RegisterDefinition("ToDateTime", typeof(MyConditionMethods).GetMethod("ToDateTime")); factories.ConditionMethods.RegisterDefinition("ToDecimal", typeof(MyConditionMethods).GetMethod("ToDecimal")); factories.ConditionMethods.RegisterDefinition("IsValid", typeof(MyConditionMethods).GetMethod("IsValid")); return factories; } private static void AssertEvaluationResult(object expectedResult, string conditionText) { ConditionExpression condition = ConditionParser.ParseExpression(conditionText); LogEventInfo context = CreateWellKnownContext(); object actualResult = condition.Evaluate(context); Assert.Equal(expectedResult, actualResult); } private static LogEventInfo CreateWellKnownContext() { var context = new LogEventInfo { Level = LogLevel.Warn, Message = "some message", LoggerName = "MyCompany.Product.Class" }; return context; } /// <summary> /// Conversion methods helpful in covering type promotion logic /// </summary> public class MyConditionMethods { public static Guid GetGuid() { return new Guid("{40190B01-C9C0-4F78-AA5A-615E413742E1}"); } public static short ToInt16(object v) { return Convert.ToInt16(v, CultureInfo.InvariantCulture); } public static int ToInt32(object v) { return Convert.ToInt32(v, CultureInfo.InvariantCulture); } public static long ToInt64(object v) { return Convert.ToInt64(v, CultureInfo.InvariantCulture); } public static float ToSingle(object v) { return Convert.ToSingle(v, CultureInfo.InvariantCulture); } public static decimal ToDecimal(object v) { return Convert.ToDecimal(v, CultureInfo.InvariantCulture); } public static double ToDouble(object v) { return Convert.ToDouble(v, CultureInfo.InvariantCulture); } public static DateTime ToDateTime(object v) { return Convert.ToDateTime(v, CultureInfo.InvariantCulture); } public static bool IsValid(LogEventInfo context) { return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\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; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsUInt16() { var test = new VectorAs__AsUInt16(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsUInt16 { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector128<UInt16> value; value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector128<UInt16> value; value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<byte> byteResult = value.As<UInt16, byte>(); ValidateResult(byteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<double> doubleResult = value.As<UInt16, double>(); ValidateResult(doubleResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<short> shortResult = value.As<UInt16, short>(); ValidateResult(shortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<int> intResult = value.As<UInt16, int>(); ValidateResult(intResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<long> longResult = value.As<UInt16, long>(); ValidateResult(longResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<sbyte> sbyteResult = value.As<UInt16, sbyte>(); ValidateResult(sbyteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<float> floatResult = value.As<UInt16, float>(); ValidateResult(floatResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<ushort> ushortResult = value.As<UInt16, ushort>(); ValidateResult(ushortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<uint> uintResult = value.As<UInt16, uint>(); ValidateResult(uintResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); Vector128<ulong> ulongResult = value.As<UInt16, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector128<UInt16> value; value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object byteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsByte)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<byte>)(byteResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object doubleResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsDouble)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<double>)(doubleResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object shortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt16)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<short>)(shortResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object intResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt32)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<int>)(intResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object longResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt64)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<long>)(longResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object sbyteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSByte)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<sbyte>)(sbyteResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object floatResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSingle)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<float>)(floatResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object ushortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt16)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ushort>)(ushortResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object uintResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt32)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<uint>)(uintResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt16()); object ulongResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt64)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector128<T> result, Vector128<UInt16> value, [CallerMemberName] string method = "") where T : struct { UInt16[] resultElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result); UInt16[] valueElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(UInt16[] resultElements, UInt16[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt16>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// **************************************************************** // Copyright 2012, Stephan Burguchev // e-mail: [email protected] // **************************************************************** // * using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; namespace Motherlode.Common { /// <summary> /// The guard provides static methods to simplify the arguments check required for public /// interface. /// </summary> /// <remarks> /// This class provides helper methods for asserting the validity of arguments. It can be used to /// reduce the number of laborious <c>if</c>, <c>throw</c> sequences in your code. /// </remarks> public static class Guard { #region Public Methods and Operators /// <summary> /// Ensures the specified enumeration argument is a valid member of the /// <typeparamref name="TEnum" /> enumeration. If it is not, an <see cref="ArgumentException" /> is /// thrown. /// </summary> /// <remarks> /// <para> /// This method can be used to validate all publicly-supplied enumeration values. Without such /// an assertion, it is possible to cast any <c>int</c> value to the enumeration type and pass /// it in. /// </para> /// <para> /// This method works for both flags and non-flags enumerations. In the case of a flags /// enumeration, any combination of values in the enumeration is accepted. In the case of a non- /// flags enumeration, the specified value must be equal to one of the values in the enumeration. /// </para> /// </remarks> /// <typeparam name="TEnum">The enumeration type.</typeparam> /// <param name="arg">The expression containing the parameter variable.</param> /// <exception cref="ArgumentException"> /// Thrown if specified argument is not a valid member of the /// <typeparamref name="TEnum" /> enumeration. /// </exception> [DebuggerHidden] public static void IsEnumMember<TEnum>(Expression<Func<TEnum>> arg) where TEnum : struct, IConvertible { TEnum enumValue = arg.Compile()(); if (Attribute.IsDefined(typeof(TEnum), typeof(FlagsAttribute), false)) { // Flag enumeration - we can only get here if TEnum is a valid enumeration type, since the FlagsAttribute can // only be applied to enumerations bool throwEx; long longValue = enumValue.ToInt64(CultureInfo.InvariantCulture); if (longValue == 0) { // Only throw if zero isn't defined in the enum - we have to convert zero to the underlying type of the enum throwEx = !Enum.IsDefined( typeof(TEnum), ((IConvertible)0).ToType(Enum.GetUnderlyingType(typeof(TEnum)), CultureInfo.InvariantCulture)); } else { longValue = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Aggregate( longValue, (current, value) => current & ~value.ToInt64(CultureInfo.InvariantCulture)); // Throw if there is a value left over after removing all valid values throwEx = longValue != 0; } if (throwEx) { var param = (MemberExpression)arg.Body; throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "Enum value '{0}' is not valid for flags enumeration '{1}'.", enumValue, typeof(TEnum).FullName), param.Member.Name); } } else { // Not a flag enumeration if (!Enum.IsDefined(typeof(TEnum), enumValue)) { var param = (MemberExpression)arg.Body; throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "Enum value '{0}' is not defined for enumeration '{1}'.", enumValue, typeof(TEnum).FullName), param.Member.Name); } } } /// <summary> /// Ensures the specified argument is non-<see langword="null" />. If it is, an /// <see cref="ArgumentNullException" /> is thrown. /// </summary> /// <typeparam name="T">The type of the argument.</typeparam> /// <param name="arg">The expression containing the parameter variable.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" />. /// </exception> [DebuggerHidden] public static void IsNotNull<T>(Expression<Func<T>> arg) where T : class { if (arg.Compile()() != null) { return; } var param = (MemberExpression)arg.Body; throw new ArgumentNullException(param.Member.Name); } [DebuggerHidden] public static void IsNotNull<T>(Expression<Func<T>> arg, T value) where T : class { if (value != null) { return; } var param = (MemberExpression)arg.Body; throw new ArgumentNullException(param.Member.Name); } /// <summary> /// Ensures the specified nullable value argument is non-<see langword="null" />. If it is, an /// <see cref="ArgumentNullException" /> is thrown. /// </summary> /// <typeparam name="T">The type of the argument.</typeparam> /// <param name="arg">The expression containing the parameter variable.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" />. /// </exception> [DebuggerHidden] public static void IsNotNull<T>(Expression<Func<T?>> arg) where T : struct { if (arg.Compile()().HasValue) { return; } var param = (MemberExpression)arg.Body; throw new ArgumentNullException(param.Member.Name); } /// <summary> /// Ensures the specified argument is non-<see langword="null" />. If it is, an /// <see cref="ArgumentNullException" /> is thrown. /// </summary> /// <typeparam name="T">The type of the argument.</typeparam> /// <param name="value">Parameter value.</param> /// <param name="paramName">Parameter name.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" />. /// </exception> [DebuggerHidden] public static void IsNotNull<T>(T value, string paramName) where T : class { if (value != null) { return; } throw new ArgumentNullException(paramName); } /// <summary> /// Ensures the specified argument is non-<see langword="null" />. If it is, an /// <see cref="ArgumentNullException" /> is thrown. /// </summary> /// <typeparam name="T">The type of the argument.</typeparam> /// <param name="value">Parameter value.</param> /// <param name="paramName">Parameter name.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" />. /// </exception> [DebuggerHidden] public static void IsNotNull<T>(T? value, string paramName) where T : struct { if (value.HasValue) { return; } throw new ArgumentNullException(paramName); } /// <summary> /// Ensures the specified argument is non-<see langword="null" /> and not an empty <c>string</c>. /// If it is, an <see cref="ArgumentNullException" /> is thrown. /// </summary> /// <param name="arg">The expression containing the parameter variable.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" /> or an empty <c>string</c>. /// </exception> [DebuggerHidden] public static void IsNotNullOrEmpty(Expression<Func<string>> arg) { if (!string.IsNullOrEmpty(arg.Compile()())) { return; } var param = (MemberExpression)arg.Body; string paramName = param.Member.Name; throw new ArgumentNullException(paramName, "Value cannot be null or empty."); } /// <summary> /// Ensures the specified argument is non-<see langword="null" /> and not an empty <c>string</c>. /// If it is, an <see cref="ArgumentNullException" /> is thrown. /// </summary> /// <param name="value">Parameter value.</param> /// <param name="paramName">Parameter name.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" /> or an empty <c>string</c>. /// </exception> [DebuggerHidden] public static void IsNotNullOrEmpty(string value, string paramName) { if (!string.IsNullOrEmpty(value)) { return; } throw new ArgumentNullException(paramName, "Value cannot be null or empty."); } /// <summary> /// Ensures the specified argument is non-<see langword="null" />, not an empty <c>string</c> and /// contains not only the whitespace characters. If it is, an <see cref="ArgumentNullException" /> is /// thrown. /// </summary> /// <param name="arg">The expression containing the parameter variable.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" />, an empty <c>string</c> or a string /// containing whitespaces only. /// </exception> [DebuggerHidden] public static void IsNotNullOrWhiteSpace(Expression<Func<string>> arg) { if (!string.IsNullOrWhiteSpace(arg.Compile()())) { return; } var param = (MemberExpression)arg.Body; string paramName = param.Member.Name; throw new ArgumentNullException(paramName, "Value cannot be null or whitespace."); } /// <summary> /// Ensures the specified argument is non-<see langword="null" />, not an empty <c>string</c> and /// contains not only the whitespace characters. If it is, an <see cref="ArgumentNullException" /> is /// thrown. /// </summary> /// <param name="value">Parameter value.</param> /// <param name="paramName">Parameter name.</param> /// <exception cref="ArgumentNullException"> /// Thrown if specified argument is <see langword="null" />, an empty <c>string</c> or a string /// containing whitespaces only. /// </exception> [DebuggerHidden] public static void IsNotNullOrWhiteSpace(string value, string paramName) { if (!string.IsNullOrWhiteSpace(value)) { return; } throw new ArgumentNullException(paramName, "Value cannot be null or whitespace."); } #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 log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Services.UserAccountService { public class GridUserService : GridUserServiceBase, IGridUserService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public GridUserService(IConfigSource config) : base(config) { m_log.Debug("[GRID USER SERVICE]: Starting user grid service"); MainConsole.Instance.Commands.AddCommand( "Users", false, "show grid user", "show grid user <ID>", "Show grid user entry or entries that match or start with the given ID. This will normally be a UUID.", "This is for debug purposes to see what data is found for a particular user id.", HandleShowGridUser); MainConsole.Instance.Commands.AddCommand( "Users", false, "show grid users online", "show grid users online", "Show number of grid users registered as online.", "This number may not be accurate as a region may crash or not be cleanly shutdown and leave grid users shown as online\n." + "For this reason, users online for more than 5 days are not currently counted", HandleShowGridUsersOnline); } protected void HandleShowGridUser(string module, string[] cmdparams) { if (cmdparams.Length != 4) { MainConsole.Instance.Output("Usage: show grid user <UUID>"); return; } GridUserData[] data = m_Database.GetAll(cmdparams[3]); foreach (GridUserData gu in data) { ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("User ID", gu.UserID); foreach (KeyValuePair<string,string> kvp in gu.Data) cdl.AddRow(kvp.Key, kvp.Value); MainConsole.Instance.Output(cdl.ToString()); } MainConsole.Instance.OutputFormat("Entries: {0}", data.Length); } protected void HandleShowGridUsersOnline(string module, string[] cmdparams) { // if (cmdparams.Length != 4) // { // MainConsole.Instance.Output("Usage: show grid users online"); // return; // } // int onlineCount; int onlineRecentlyCount = 0; DateTime now = DateTime.UtcNow; foreach (GridUserData gu in m_Database.GetAll("")) { if (bool.Parse(gu.Data["Online"])) { // onlineCount++; int unixLoginTime = int.Parse(gu.Data["Login"]); if ((now - Util.ToDateTime(unixLoginTime)).Days < 5) onlineRecentlyCount++; } } MainConsole.Instance.OutputFormat("Users online: {0}", onlineRecentlyCount); } private GridUserData GetGridUserData(string userID) { GridUserData d = null; if (userID.Length > 36) // it's a UUI { d = m_Database.Get(userID); } else // it's a UUID { GridUserData[] ds = m_Database.GetAll(userID); if (ds == null) return null; if (ds.Length > 0) { d = ds[0]; foreach (GridUserData dd in ds) if (dd.UserID.Length > d.UserID.Length) // find the longest d = dd; } } return d; } public virtual GridUserInfo GetGridUserInfo(string userID) { GridUserData d = GetGridUserData(userID); if (d == null) return null; GridUserInfo info = new GridUserInfo(); info.UserID = d.UserID; info.HomeRegionID = new UUID(d.Data["HomeRegionID"]); info.HomePosition = Vector3.Parse(d.Data["HomePosition"]); info.HomeLookAt = Vector3.Parse(d.Data["HomeLookAt"]); info.LastRegionID = new UUID(d.Data["LastRegionID"]); info.LastPosition = Vector3.Parse(d.Data["LastPosition"]); info.LastLookAt = Vector3.Parse(d.Data["LastLookAt"]); info.Online = bool.Parse(d.Data["Online"]); info.Login = Util.ToDateTime(Convert.ToInt32(d.Data["Login"])); info.Logout = Util.ToDateTime(Convert.ToInt32(d.Data["Logout"])); return info; } public virtual GridUserInfo[] GetGridUserInfo(string[] userIDs) { List<GridUserInfo> ret = new List<GridUserInfo>(); foreach (string id in userIDs) ret.Add(GetGridUserInfo(id)); return ret.ToArray(); } public GridUserInfo LoggedIn(string userID) { m_log.DebugFormat("[GRID USER SERVICE]: User {0} is online", userID); GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["Online"] = true.ToString(); d.Data["Login"] = Util.UnixTimeSinceEpoch().ToString(); m_Database.Store(d); return GetGridUserInfo(userID); } public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { m_log.DebugFormat("[GRID USER SERVICE]: User {0} is offline", userID); GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["Online"] = false.ToString(); d.Data["Logout"] = Util.UnixTimeSinceEpoch().ToString(); d.Data["LastRegionID"] = regionID.ToString(); d.Data["LastPosition"] = lastPosition.ToString(); d.Data["LastLookAt"] = lastLookAt.ToString(); return m_Database.Store(d); } public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt) { GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["HomeRegionID"] = homeID.ToString(); d.Data["HomePosition"] = homePosition.ToString(); d.Data["HomeLookAt"] = homeLookAt.ToString(); return m_Database.Store(d); } public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { // m_log.DebugFormat("[GRID USER SERVICE]: SetLastPosition for {0}", userID); GridUserData d = GetGridUserData(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["LastRegionID"] = regionID.ToString(); d.Data["LastPosition"] = lastPosition.ToString(); d.Data["LastLookAt"] = lastLookAt.ToString(); return m_Database.Store(d); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Store; using Microsoft.WindowsAzure.Management.Store.Models; namespace Microsoft.WindowsAzure.Management.Store { /// <summary> /// Provides REST operations for working with cloud services from the /// Windows Azure store service. /// </summary> internal partial class CloudServiceOperations : IServiceOperations<StoreManagementClient>, ICloudServiceOperations { /// <summary> /// Initializes a new instance of the CloudServiceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal CloudServiceOperations(StoreManagementClient client) { this._client = client; } private StoreManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Store.StoreManagementClient. /// </summary> public StoreManagementClient Client { get { return this._client; } } /// <summary> /// The Create Cloud Service operation creates a Windows Azure cloud /// service in a Windows Azure subscription. /// </summary> /// <param name='parameters'> /// Required. Parameters used to specify how the Create procedure will /// function. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> BeginCreatingAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Description == null) { throw new ArgumentNullException("parameters.Description"); } if (parameters.GeoRegion == null) { throw new ArgumentNullException("parameters.GeoRegion"); } if (parameters.Label == null) { throw new ArgumentNullException("parameters.Label"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/CloudServices/"; url = url + Uri.EscapeDataString(parameters.Name); url = url + "/"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement cloudServiceElement = new XElement(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(cloudServiceElement); XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; cloudServiceElement.Add(nameElement); XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = parameters.Label; cloudServiceElement.Add(labelElement); XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; cloudServiceElement.Add(descriptionElement); XElement geoRegionElement = new XElement(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure")); geoRegionElement.Value = parameters.GeoRegion; cloudServiceElement.Add(geoRegionElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Create Cloud Service operation creates a Windows Azure cloud /// service in a Windows Azure subscription. /// </summary> /// <param name='parameters'> /// Required. Parameters used to specify how the Create procedure will /// function. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> CreateAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken) { StoreManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.CloudServices.BeginCreatingAsync(parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The List Cloud Services operation enumerates Windows Azure Store /// entries that are provisioned for a subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response structure for the Cloud Service List operation. /// </returns> public async Task<CloudServiceListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/CloudServices/"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result CloudServiceListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CloudServiceListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement cloudServicesSequenceElement = responseDoc.Element(XName.Get("CloudServices", "http://schemas.microsoft.com/windowsazure")); if (cloudServicesSequenceElement != null) { foreach (XElement cloudServicesElement in cloudServicesSequenceElement.Elements(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"))) { CloudServiceListResponse.CloudService cloudServiceInstance = new CloudServiceListResponse.CloudService(); result.CloudServices.Add(cloudServiceInstance); XElement nameElement = cloudServicesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; cloudServiceInstance.Name = nameInstance; } XElement labelElement = cloudServicesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); cloudServiceInstance.Label = labelInstance; } XElement descriptionElement = cloudServicesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; cloudServiceInstance.Description = descriptionInstance; } XElement geoRegionElement = cloudServicesElement.Element(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure")); if (geoRegionElement != null) { string geoRegionInstance = geoRegionElement.Value; cloudServiceInstance.GeoRegion = geoRegionInstance; } XElement resourcesSequenceElement = cloudServicesElement.Element(XName.Get("Resources", "http://schemas.microsoft.com/windowsazure")); if (resourcesSequenceElement != null) { foreach (XElement resourcesElement in resourcesSequenceElement.Elements(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"))) { CloudServiceListResponse.CloudService.AddOnResource resourceInstance = new CloudServiceListResponse.CloudService.AddOnResource(); cloudServiceInstance.Resources.Add(resourceInstance); XElement resourceProviderNamespaceElement = resourcesElement.Element(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure")); if (resourceProviderNamespaceElement != null) { string resourceProviderNamespaceInstance = resourceProviderNamespaceElement.Value; resourceInstance.Namespace = resourceProviderNamespaceInstance; } XElement typeElement = resourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; resourceInstance.Type = typeInstance; } XElement nameElement2 = resourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; resourceInstance.Name = nameInstance2; } XElement planElement = resourcesElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); if (planElement != null) { string planInstance = planElement.Value; resourceInstance.Plan = planInstance; } XElement schemaVersionElement = resourcesElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure")); if (schemaVersionElement != null) { string schemaVersionInstance = schemaVersionElement.Value; resourceInstance.SchemaVersion = schemaVersionInstance; } XElement eTagElement = resourcesElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure")); if (eTagElement != null) { string eTagInstance = eTagElement.Value; resourceInstance.ETag = eTagInstance; } XElement stateElement = resourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; resourceInstance.State = stateInstance; } XElement usageMetersSequenceElement = resourcesElement.Element(XName.Get("UsageMeters", "http://schemas.microsoft.com/windowsazure")); if (usageMetersSequenceElement != null) { foreach (XElement usageMetersElement in usageMetersSequenceElement.Elements(XName.Get("UsageMeter", "http://schemas.microsoft.com/windowsazure"))) { CloudServiceListResponse.CloudService.AddOnResource.UsageLimit usageMeterInstance = new CloudServiceListResponse.CloudService.AddOnResource.UsageLimit(); resourceInstance.UsageLimits.Add(usageMeterInstance); XElement nameElement3 = usageMetersElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement3 != null) { string nameInstance3 = nameElement3.Value; usageMeterInstance.Name = nameInstance3; } XElement unitElement = usageMetersElement.Element(XName.Get("Unit", "http://schemas.microsoft.com/windowsazure")); if (unitElement != null) { string unitInstance = unitElement.Value; usageMeterInstance.Unit = unitInstance; } XElement includedElement = usageMetersElement.Element(XName.Get("Included", "http://schemas.microsoft.com/windowsazure")); if (includedElement != null) { long includedInstance = long.Parse(includedElement.Value, CultureInfo.InvariantCulture); usageMeterInstance.AmountIncluded = includedInstance; } XElement usedElement = usageMetersElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure")); if (usedElement != null) { long usedInstance = long.Parse(usedElement.Value, CultureInfo.InvariantCulture); usageMeterInstance.AmountUsed = usedInstance; } } } XElement outputItemsSequenceElement = resourcesElement.Element(XName.Get("OutputItems", "http://schemas.microsoft.com/windowsazure")); if (outputItemsSequenceElement != null) { foreach (XElement outputItemsElement in outputItemsSequenceElement.Elements(XName.Get("OutputItem", "http://schemas.microsoft.com/windowsazure"))) { string outputItemsKey = outputItemsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/windowsazure")).Value; string outputItemsValue = outputItemsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")).Value; resourceInstance.OutputItems.Add(outputItemsKey, outputItemsValue); } } XElement operationStatusElement = resourcesElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure")); if (operationStatusElement != null) { CloudServiceListResponse.CloudService.AddOnResource.OperationStatus operationStatusInstance = new CloudServiceListResponse.CloudService.AddOnResource.OperationStatus(); resourceInstance.Status = operationStatusInstance; XElement typeElement2 = operationStatusElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement2 != null) { string typeInstance2 = typeElement2.Value; operationStatusInstance.Type = typeInstance2; } XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure")); if (resultElement != null) { string resultInstance = resultElement.Value; operationStatusInstance.Result = resultInstance; } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using Xunit; using Prism.Events; namespace Prism.Tests.Events { public class EventSubscriptionFixture { [Fact] public void NullTargetInActionThrows() { Assert.Throws<ArgumentException>(() => { var actionDelegateReference = new MockDelegateReference() { Target = null }; var filterDelegateReference = new MockDelegateReference() { Target = (Predicate<object>)(arg => { return true; }) }; var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference); }); } [Fact] public void DifferentTargetTypeInActionThrows() { Assert.Throws<ArgumentException>(() => { var actionDelegateReference = new MockDelegateReference() { Target = (Action<int>)delegate { } }; var filterDelegateReference = new MockDelegateReference() { Target = (Predicate<string>)(arg => { return true; }) }; var eventSubscription = new EventSubscription<string>(actionDelegateReference, filterDelegateReference); }); } [Fact] public void NullActionThrows() { Assert.Throws<ArgumentNullException>(() => { var filterDelegateReference = new MockDelegateReference() { Target = (Predicate<object>)(arg => { return true; }) }; var eventSubscription = new EventSubscription<object>(null, filterDelegateReference); }); } [Fact] public void NullTargetInFilterThrows() { Assert.Throws<ArgumentException>(() => { var actionDelegateReference = new MockDelegateReference() { Target = (Action<object>)delegate { } }; var filterDelegateReference = new MockDelegateReference() { Target = null }; var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference); }); } [Fact] public void DifferentTargetTypeInFilterThrows() { Assert.Throws<ArgumentException>(() => { var actionDelegateReference = new MockDelegateReference() { Target = (Action<string>)delegate { } }; var filterDelegateReference = new MockDelegateReference() { Target = (Predicate<int>)(arg => { return true; }) }; var eventSubscription = new EventSubscription<string>(actionDelegateReference, filterDelegateReference); }); } [Fact] public void NullFilterThrows() { Assert.Throws<ArgumentNullException>(() => { var actionDelegateReference = new MockDelegateReference() { Target = (Action<object>)delegate { } }; var eventSubscription = new EventSubscription<object>(actionDelegateReference, null); }); } [Fact] public void CanInitEventSubscription() { var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { }); var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; }); var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference); var subscriptionToken = new SubscriptionToken(t => { }); eventSubscription.SubscriptionToken = subscriptionToken; Assert.Same(actionDelegateReference.Target, eventSubscription.Action); Assert.Same(filterDelegateReference.Target, eventSubscription.Filter); Assert.Same(subscriptionToken, eventSubscription.SubscriptionToken); } [Fact] public void GetPublishActionReturnsDelegateThatExecutesTheFilterAndThenTheAction() { var executedDelegates = new List<string>(); var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { executedDelegates.Add("Action"); }); var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { executedDelegates.Add( "Filter"); return true; }); var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference); var publishAction = eventSubscription.GetExecutionStrategy(); Assert.NotNull(publishAction); publishAction.Invoke(null); Assert.Equal(2, executedDelegates.Count); Assert.Equal("Filter", executedDelegates[0]); Assert.Equal("Action", executedDelegates[1]); } [Fact] public void GetPublishActionReturnsNullIfActionIsNull() { var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { }); var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; }); var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference); var publishAction = eventSubscription.GetExecutionStrategy(); Assert.NotNull(publishAction); actionDelegateReference.Target = null; publishAction = eventSubscription.GetExecutionStrategy(); Assert.Null(publishAction); } [Fact] public void GetPublishActionReturnsNullIfFilterIsNull() { var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { }); var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; }); var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference); var publishAction = eventSubscription.GetExecutionStrategy(); Assert.NotNull(publishAction); filterDelegateReference.Target = null; publishAction = eventSubscription.GetExecutionStrategy(); Assert.Null(publishAction); } [Fact] public void GetPublishActionDoesNotExecuteActionIfFilterReturnsFalse() { bool actionExecuted = false; var actionDelegateReference = new MockDelegateReference() { Target = (Action<int>)delegate { actionExecuted = true; } }; var filterDelegateReference = new MockDelegateReference((Predicate<int>)delegate { return false; }); var eventSubscription = new EventSubscription<int>(actionDelegateReference, filterDelegateReference); var publishAction = eventSubscription.GetExecutionStrategy(); publishAction.Invoke(new object[] { null }); Assert.False(actionExecuted); } [Fact] public void StrategyPassesArgumentToDelegates() { string passedArgumentToAction = null; string passedArgumentToFilter = null; var actionDelegateReference = new MockDelegateReference((Action<string>)(obj => passedArgumentToAction = obj)); var filterDelegateReference = new MockDelegateReference((Predicate<string>)(obj => { passedArgumentToFilter = obj; return true; })); var eventSubscription = new EventSubscription<string>(actionDelegateReference, filterDelegateReference); var publishAction = eventSubscription.GetExecutionStrategy(); publishAction.Invoke(new[] { "TestString" }); Assert.Equal("TestString", passedArgumentToAction); Assert.Equal("TestString", passedArgumentToFilter); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Http { /// <summary> /// Contains the parsed HTTP form values. /// </summary> public class FormCollection : IFormCollection { /// <summary> /// An empty <see cref="FormCollection"/>. /// </summary> public static readonly FormCollection Empty = new FormCollection(); private static readonly string[] EmptyKeys = Array.Empty<string>(); // Pre-box private static readonly IEnumerator<KeyValuePair<string, StringValues>> EmptyIEnumeratorType = default(Enumerator); private static readonly IEnumerator EmptyIEnumerator = default(Enumerator); private static readonly IFormFileCollection EmptyFiles = new FormFileCollection(); private IFormFileCollection? _files; private FormCollection() { // For static Empty } /// <summary> /// Initializes a new instance of <see cref="FormCollection"/>. /// </summary> /// <param name="fields">The backing fields.</param> /// <param name="files">The files associated with the form.</param> public FormCollection(Dictionary<string, StringValues>? fields, IFormFileCollection? files = null) { // can be null Store = fields; _files = files; } /// <summary> /// Gets the files associated with the HTTP form. /// </summary> public IFormFileCollection Files { get => _files ?? EmptyFiles; private set => _files = value; } private Dictionary<string, StringValues>? Store { get; set; } /// <summary> /// Get or sets the associated value from the collection as a single string. /// </summary> /// <param name="key">The header name.</param> /// <returns>the associated value from the collection as a <see cref="StringValues"/> /// or <see cref="StringValues.Empty"/> if the key is not present.</returns> public StringValues this[string key] { get { if (Store == null) { return StringValues.Empty; } if (TryGetValue(key, out var value)) { return value; } return StringValues.Empty; } } /// <inheritdoc /> public int Count { get { return Store?.Count ?? 0; } } /// <inheritdoc /> public ICollection<string> Keys { get { if (Store == null) { return EmptyKeys; } return Store.Keys; } } /// <inheritdoc /> public bool ContainsKey(string key) { if (Store == null) { return false; } return Store.ContainsKey(key); } /// <inheritdoc /> public bool TryGetValue(string key, out StringValues value) { if (Store == null) { value = default(StringValues); return false; } return Store.TryGetValue(key, out value); } /// <summary> /// Returns an struct enumerator that iterates through a collection without boxing and /// is also used via the <see cref="IFormCollection" /> interface. /// </summary> /// <returns>An <see cref="Enumerator" /> object that can be used to iterate through the collection.</returns> public Enumerator GetEnumerator() { if (Store == null || Store.Count == 0) { // Non-boxed Enumerator return default; } // Non-boxed Enumerator return new Enumerator(Store.GetEnumerator()); } /// <summary> /// Returns an enumerator that iterates through a collection, boxes in non-empty path. /// </summary> /// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator<KeyValuePair<string, StringValues>> IEnumerable<KeyValuePair<string, StringValues>>.GetEnumerator() { if (Store == null || Store.Count == 0) { // Non-boxed Enumerator return EmptyIEnumeratorType; } // Boxed Enumerator return Store.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection, boxes in non-empty path. /// </summary> /// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { if (Store == null || Store.Count == 0) { // Non-boxed Enumerator return EmptyIEnumerator; } // Boxed Enumerator return Store.GetEnumerator(); } /// <summary> /// Enumerates a <see cref="FormCollection"/>. /// </summary> public struct Enumerator : IEnumerator<KeyValuePair<string, StringValues>> { // Do NOT make this readonly, or MoveNext will not work private Dictionary<string, StringValues>.Enumerator _dictionaryEnumerator; private readonly bool _notEmpty; internal Enumerator(Dictionary<string, StringValues>.Enumerator dictionaryEnumerator) { _dictionaryEnumerator = dictionaryEnumerator; _notEmpty = true; } /// <summary> /// Advances the enumerator to the next element of the <see cref="FormCollection"/>. /// </summary> /// <returns><see langword="true"/> if the enumerator was successfully advanced to the next element; /// <see langword="false"/> if the enumerator has passed the end of the collection.</returns> public bool MoveNext() { if (_notEmpty) { return _dictionaryEnumerator.MoveNext(); } return false; } /// <summary> /// Gets the element at the current position of the enumerator. /// </summary> public KeyValuePair<string, StringValues> Current { get { if (_notEmpty) { return _dictionaryEnumerator.Current; } return default; } } /// <inheritdoc /> public void Dispose() { } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { if (_notEmpty) { ((IEnumerator)_dictionaryEnumerator).Reset(); } } } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.Collections; using System.Collections.Specialized; namespace NUnit.Framework { /// <summary> /// TestCaseAttribute is used to mark parameterized test cases /// and provide them with their arguments. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)] public class TestCaseAttribute : Attribute, ITestCaseData { #region Instance Variables private object[] arguments; private object expectedResult; private bool hasExpectedResult; private Type expectedExceptionType; private string expectedExceptionName; private string expectedMessage; private MessageMatch matchType; private string description; private string testName; private bool isIgnored; private bool isExplicit; private string reason; private string category; #endregion #region Constructors /// <summary> /// Construct a TestCaseAttribute with a list of arguments. /// This constructor is not CLS-Compliant /// </summary> /// <param name="arguments"></param> public TestCaseAttribute(params object[] arguments) { if (arguments == null) this.arguments = new object[] { null }; else this.arguments = arguments; } /// <summary> /// Construct a TestCaseAttribute with a single argument /// </summary> /// <param name="arg"></param> public TestCaseAttribute(object arg) { this.arguments = new object[] { arg }; } /// <summary> /// Construct a TestCaseAttribute with a two arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> public TestCaseAttribute(object arg1, object arg2) { this.arguments = new object[] { arg1, arg2 }; } /// <summary> /// Construct a TestCaseAttribute with a three arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> public TestCaseAttribute(object arg1, object arg2, object arg3) { this.arguments = new object[] { arg1, arg2, arg3 }; } #endregion #region Properties /// <summary> /// Gets the list of arguments to a test case /// </summary> public object[] Arguments { get { return arguments; } } /// <summary> /// Gets or sets the expected result. /// </summary> /// <value>The result.</value> public object Result { get { return expectedResult; } set { expectedResult = value; hasExpectedResult = true; } } /// <summary> /// Gets the expected result. /// </summary> /// <value>The result.</value> public object ExpectedResult { get { return expectedResult; } } /// <summary> /// Gets a flag indicating whether an expected /// result has been set. /// </summary> public bool HasExpectedResult { get { return hasExpectedResult; } } /// <summary> /// Gets a list of categories associated with this test; /// </summary> public IList Categories { get { return category == null ? null : category.Split(','); } } /// <summary> /// Gets or sets the category associated with this test. /// May be a single category or a comma-separated list. /// </summary> public string Category { get { return category; } set { category = value; } } /// <summary> /// Gets or sets the expected exception. /// </summary> /// <value>The expected exception.</value> public Type ExpectedException { get { return expectedExceptionType; } set { expectedExceptionType = value; expectedExceptionName = expectedExceptionType.FullName; } } /// <summary> /// Gets or sets the name the expected exception. /// </summary> /// <value>The expected name of the exception.</value> public string ExpectedExceptionName { get { return expectedExceptionName; } set { expectedExceptionName = value; expectedExceptionType = null; } } /// <summary> /// Gets or sets the expected message of the expected exception /// </summary> /// <value>The expected message of the exception.</value> public string ExpectedMessage { get { return expectedMessage; } set { expectedMessage = value; } } /// <summary> /// Gets or sets the type of match to be performed on the expected message /// </summary> public MessageMatch MatchType { get { return matchType; } set { matchType = value; } } /// <summary> /// Gets or sets the description. /// </summary> /// <value>The description.</value> public string Description { get { return description; } set { description = value; } } /// <summary> /// Gets or sets the name of the test. /// </summary> /// <value>The name of the test.</value> public string TestName { get { return testName; } set { testName = value; } } /// <summary> /// Gets or sets the ignored status of the test /// </summary> public bool Ignore { get { return isIgnored; } set { isIgnored = value; } } /// <summary> /// Gets or sets the ignored status of the test /// </summary> public bool Ignored { get { return isIgnored; } set { isIgnored = value; } } /// <summary> /// Gets or sets the explicit status of the test /// </summary> public bool Explicit { get { return isExplicit; } set { isExplicit = value; } } /// <summary> /// Gets or sets the reason for not running the test /// </summary> public string Reason { get { return reason; } set { reason = value; } } /// <summary> /// Gets or sets the reason for not running the test. /// Set has the side effect of marking the test as ignored. /// </summary> /// <value>The ignore reason.</value> public string IgnoreReason { get { return reason; } set { reason = value; isIgnored = reason != null && reason != string.Empty; } } #endregion } }
#region using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; using SQLQueryStress.Properties; #endregion /********************************************* TODO, version 1.0:::: * figure out how to capture change of selection in parameter definer * Bug: Dotfuscated version crashes in some cases (need to verify this) * Bug: Dotfuscated version can't load non-dotfuscated .sqlstress files * * Throw a message box if param database has not been selected, or if can't connect (if parameterization is on) * repaint exception window when datatable is updated * Bug w/ stats sometimes going blank ?? *********************************************/ namespace SQLQueryStress { public partial class Form1 : Form { private const string Dashes = "---"; //Has this run been cancelled? private bool _cancelled; //Exceptions that occurred private Dictionary<string, int> _exceptions; //The exception viewer window private DataViewer _exceptionViewer; //Exit as soon as cancellation is finished? private bool _exitOnComplete; /* Configuration local */ private QueryStressSettings _settings = new QueryStressSettings(); //start of the load private TimeSpan _start; //total CPU time in milliseconds private double _totalCpuTime; //total elapsed time in milliseconds private double _totalElapsedTime; //total exceptions private int _totalExceptions; //threads * iterations private int _totalExpectedIterations; /* Runtime locals */ //total iterations that have run private int _totalIterations; //Same comments as above for these two... private double _totalLogicalReads; private int _totalReadMessages; //This is the total time as reported by the client private double _totalTime; //Number of query requests that returned time messages //Note:: Average times will be computed by: // A) Add up all results from time messages returned by // each query output // B) If the query returned one or more time messages, // increment the totalTimeMessages counter // C) Add the TOTAL of all messages to the total counters // D) Divide to find the actual time //TODO: Find out why elapsed time is not accurate in //some cases. For instance, look at time reported for //WAITFOR DELAY '00:00:05' (1300 ms?? WTF??) private int _totalTimeMessages; public Form1(string configFile) : this() { OpenConfigFile(configFile); } public Form1() { InitializeComponent(); saveFileDialog1.DefaultExt = "sqlstress"; saveFileDialog1.Filter = @"SQLQueryStress Configuration Files|*.sqlstress"; saveFileDialog1.FileOk += saveFileDialog1_FileOk; openFileDialog1.DefaultExt = "sqlstress"; openFileDialog1.Filter = @"SQLQueryStress Configuration Files|*.sqlstress"; openFileDialog1.FileOk += openFileDialog1_FileOk; } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { var a = new AboutBox(); a.ShowDialog(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { ((LoadEngine) e.Argument).StartLoad(backgroundWorker1); } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { var output = (LoadEngine.QueryOutput) e.UserState; _totalIterations++; if (output.LogicalReads > 0) { _totalReadMessages++; _totalLogicalReads += output.LogicalReads; } if (output.ElapsedTime > 0) { _totalTimeMessages++; _totalCpuTime += output.CpuTime; _totalElapsedTime += output.ElapsedTime; } _totalTime += output.Time.TotalMilliseconds; if (output.E != null) { _totalExceptions++; string theMessage; //strip the time stats, if they showed up as part //of the exception if (_settings.CollectTimeStats) { var matchPos = output.E.Message.IndexOf("SQL Server parse and compile time:", StringComparison.Ordinal); theMessage = matchPos > -1 ? output.E.Message.Substring(0, matchPos - 2) : output.E.Message; } else { theMessage = output.E.Message; } if (!_exceptions.ContainsKey(theMessage)) { _exceptions.Add(theMessage, 1); } else { _exceptions[theMessage] += 1; } //TODO: Get this working? -- Repaint exceptions as they occur? /* if ((exceptionViewer != null) && (exceptionViewer.WindowState == FormWindowState.Normal)) { exceptionViewer.Invoke(new System.Threading.ThreadStart(exceptionViewer.Repaint)); } */ } } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { mainUITimer.Stop(); UpdateUi(); go_button.Enabled = true; cancel_button.Enabled = false; threads_numericUpDown.Enabled = true; iterations_numericUpDown.Enabled = true; if (!_cancelled) progressBar1.Value = 100; ((BackgroundWorker) sender).Dispose(); db_label.Text = ""; if (_exitOnComplete) { Dispose(); } } private void cancel_button_Click(object sender, EventArgs e) { cancel_button.Enabled = false; backgroundWorker1.CancelAsync(); _cancelled = true; if (sender is string) { _exitOnComplete = true; } } private void database_button_Click(object sender, EventArgs e) { var dbselect = new DatabaseSelect(_settings) {StartPosition = FormStartPosition.CenterParent}; dbselect.ShowDialog(); } private void exceptions_button_Click(object sender, EventArgs e) { totalExceptions_textBox_Click(null, null); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Dispose(); } private void go_button_Click(object sender, EventArgs e) { if (!_settings.MainDbConnectionInfo.TestConnection()) { MessageBox.Show(Resources.MustSetValidDbConnInfo); return; } _cancelled = false; _exitOnComplete = false; _exceptions = new Dictionary<string, int>(); _totalIterations = 0; _totalTime = 0; _totalCpuTime = 0; _totalElapsedTime = 0; _totalTimeMessages = 0; _totalLogicalReads = 0; _totalReadMessages = 0; _totalExceptions = 0; iterationsSecond_textBox.Text = "0"; avgSeconds_textBox.Text = "0.0"; actualSeconds_textBox.Text = Dashes; cpuTime_textBox.Text = Dashes; logicalReads_textBox.Text = Dashes; go_button.Enabled = false; cancel_button.Enabled = true; iterations_numericUpDown.Enabled = false; threads_numericUpDown.Enabled = false; progressBar1.Value = 0; SaveSettingsFromForm1(); _totalExpectedIterations = _settings.NumThreads * _settings.NumIterations; var paramConnectionInfo = _settings.ShareDbSettings ? _settings.MainDbConnectionInfo : _settings.ParamDbConnectionInfo; db_label.Text = "" + "Server: " + paramConnectionInfo.Server + (paramConnectionInfo.Database.Length > 0 ? " // Database: " + paramConnectionInfo.Database : ""); var engine = new LoadEngine(_settings.MainDbConnectionInfo.ConnectionString, _settings.MainQuery, _settings.NumThreads, _settings.NumIterations, _settings.ParamQuery, _settings.ParamMappings, paramConnectionInfo.ConnectionString, _settings.CommandTimeout, _settings.CollectIoStats, _settings.CollectTimeStats, _settings.ForceDataRetrieval); backgroundWorker1.RunWorkerAsync(engine); _start = new TimeSpan(DateTime.Now.Ticks); mainUITimer.Start(); } private void loadSettingsToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } private void mainUITimer_Tick(object sender, EventArgs e) { UpdateUi(); } private void OpenConfigFile(string fileName) { FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open); var bf = new BinaryFormatter(); _settings = (QueryStressSettings) bf.Deserialize(fs); } catch { MessageBox.Show(Resources.ErrLoadingSettings); } finally { if (fs != null) fs.Dispose(); } query_textBox.Text = _settings.MainQuery; threads_numericUpDown.Value = _settings.NumThreads; iterations_numericUpDown.Value = _settings.NumIterations; } private void openFileDialog1_FileOk(object sender, EventArgs e) { OpenConfigFile(openFileDialog1.FileName); } private void optionsToolStripMenuItem_Click(object sender, EventArgs e) { var options = new Options(_settings); options.ShowDialog(); } private void param_button_Click(object sender, EventArgs e) { var p = new ParamWindow(_settings, query_textBox.Text) {StartPosition = FormStartPosition.CenterParent}; p.ShowDialog(); } private void saveFileDialog1_FileOk(object sender, EventArgs e) { FileStream fs = null; try { fs = new FileStream(saveFileDialog1.FileName, FileMode.Create); var bf = new BinaryFormatter(); bf.Serialize(fs, _settings); } catch { MessageBox.Show(Resources.ErrorSavingSettings); } finally { if (fs != null) fs.Dispose(); } } private void SaveSettingsFromForm1() { _settings.MainQuery = query_textBox.Text; _settings.NumThreads = (int) threads_numericUpDown.Value; _settings.NumIterations = (int) iterations_numericUpDown.Value; } private void saveSettingsToolStripMenuItem_Click(object sender, EventArgs e) { SaveSettingsFromForm1(); saveFileDialog1.ShowDialog(); } private void totalExceptions_textBox_Click(object sender, EventArgs e) { _exceptionViewer = new DataViewer {StartPosition = FormStartPosition.CenterParent, Text = Resources.Exceptions}; var dt = new DataTable(); dt.Columns.Add("Count"); dt.Columns.Add("Exception"); if (_exceptions != null) { var values = _exceptions.Values.GetEnumerator(); foreach (var ex in _exceptions.Keys) { values.MoveNext(); var count = values.Current; dt.Rows.Add(count, ex); } } _exceptionViewer.DataView = dt; _exceptionViewer.ShowDialog(); } private void UpdateUi() { iterationsSecond_textBox.Text = _totalIterations.ToString(); var avgIterations = _totalIterations == 0 ? 0.0 : _totalTime / _totalIterations / 1000; var avgCpu = _totalTimeMessages == 0 ? 0.0 : _totalCpuTime / _totalTimeMessages / 1000; var avgActual = _totalTimeMessages == 0 ? 0.0 : _totalElapsedTime / _totalTimeMessages / 1000; var avgReads = _totalReadMessages == 0 ? 0.0 : _totalLogicalReads / _totalReadMessages; avgSeconds_textBox.Text = avgIterations.ToString("0.0000"); cpuTime_textBox.Text = _totalTimeMessages == 0 ? "---" : avgCpu.ToString("0.0000"); actualSeconds_textBox.Text = _totalTimeMessages == 0 ? "---" : avgActual.ToString("0.0000"); logicalReads_textBox.Text = _totalReadMessages == 0 ? "---" : avgReads.ToString("0.0000"); totalExceptions_textBox.Text = _totalExceptions.ToString(); progressBar1.Value = (int) (_totalIterations / (decimal) _totalExpectedIterations * 100); var end = new TimeSpan(DateTime.Now.Ticks); end = end.Subtract(_start); var theTime = end.ToString(); //Some systems return "hh:mm:ss" instead of "hh:mm:ss.0000" if //there is no fractional part of the second. I'm not sure //why, but this fixes it for now. if (theTime.Length > 8) elapsedTime_textBox.Text = theTime.Substring(0, 13); else elapsedTime_textBox.Text = theTime + ".0000"; } [Serializable] public class QueryStressSettings { /// <summary> /// Collect I/O stats? /// </summary> public bool CollectIoStats; /// <summary> /// Collect time stats? /// </summary> public bool CollectTimeStats; /// <summary> /// command timeout /// </summary> public int CommandTimeout; /// <summary> /// Connection Timeout /// </summary> public int ConnectionTimeout; /// <summary> /// Enable pooling? /// </summary> public bool EnableConnectionPooling; /// <summary> /// Force the client to retrieve all data? /// </summary> public bool ForceDataRetrieval; /// <summary> /// Connection info for the DB in which to run the test /// </summary> public DatabaseSelect.ConnectionInfo MainDbConnectionInfo; /// <summary> /// main query to test /// </summary> public string MainQuery; /// <summary> /// Number of iterations to run per thread /// </summary> public int NumIterations; /// <summary> /// Number of threads to test with /// </summary> public int NumThreads; /// <summary> /// Connection info for the DB from which to get the paramaters /// </summary> public DatabaseSelect.ConnectionInfo ParamDbConnectionInfo; /// <summary> /// mapped parameters /// </summary> public Dictionary<string, string> ParamMappings; /// <summary> /// query from which to take parameters /// </summary> public string ParamQuery; /// <summary> /// Should the main db and param db share the same settings? /// If so, use main db settings for the params /// </summary> public bool ShareDbSettings; public QueryStressSettings() { MainDbConnectionInfo = new DatabaseSelect.ConnectionInfo(this); ShareDbSettings = true; ParamDbConnectionInfo = new DatabaseSelect.ConnectionInfo(); MainQuery = ""; ParamQuery = ""; NumThreads = 1; NumIterations = 1; ParamMappings = new Dictionary<string, string>(); ConnectionTimeout = 15; CommandTimeout = 0; EnableConnectionPooling = true; CollectIoStats = true; CollectTimeStats = true; ForceDataRetrieval = false; } [OnDeserialized] private void FixSettings(StreamingContext context) { ConnectionTimeout = ConnectionTimeout == 0 ? 15 : ConnectionTimeout; } } private void btnCleanBuffer_Click(object sender, EventArgs e) { MessageBox.Show(LoadEngine.ExecuteCommand(_settings.MainDbConnectionInfo.ConnectionString, "DBCC DROPCLEANBUFFERS") ? "Buffers cleared" : "Errors encountered"); } private void btnFreeCache_Click(object sender, EventArgs e) { MessageBox.Show(LoadEngine.ExecuteCommand(_settings.MainDbConnectionInfo.ConnectionString, "DBCC FREEPROCCACHE") ? "Cache freed" : "Errors encountered"); } } }
using UnityEngine; using CreateThis.VR.UI.Interact; using CreateThis.Unity; namespace MeshEngine.Controller { public class TriangleController : Triggerable { public UnityEngine.Mesh uMesh; public Mesh mesh; public Vertex a; public Vertex b; public Vertex c; public Vector3 center; public UnityEngine.Material material; public UnityEngine.Material stickySelectedMaterial; private UnityEngine.Material blendedStickySelectedMaterial; private bool stickySelected; private bool isSelectable = true; private Selectable selectable; private MeshRenderer meshRenderer; private MeshCollider meshCollider; private UnityEngine.Mesh collisionMesh; private bool hasInitialized; private UnityEngine.Material[] materials; private Vector3[] meshVertices; private int[] meshTriangles; private Vector3[] collisionMeshVertices; private int[] collisionMeshTriangles; public override void OnTriggerDown(Transform controller, int controllerIndex) { base.OnTriggerDown(controller, controllerIndex); switch (Mode.mode) { case ModeType.PickColor: TriggerDownModePickColor(); break; case ModeType.SelectTriangles: TriggerDownModeSelectTriangles(); break; case ModeType.SelectVerticesByTriangles: TriggerDownModeSelectVertices(); break; case ModeType.TriangleDelete: TriggerDownModeTriangleDelete(); break; case ModeType.Normal: TriggerDownModeNormal(); break; case ModeType.Fill: TriggerDownModeFill(); break; } } private void TriggerDownModeSelectTriangles() { if (mesh.selection.TriangleSelectedByVertices(GetTriangle())) { mesh.selection.DeselectTriangleByVertices(GetTriangle()); return; } mesh.selection.SelectTriangleByVertices(GetTriangle()); } private void TriggerDownModeSelectVertices() { if (mesh.selection.VerticesSelected(GetTriangle())) { mesh.selection.DeselectVertices(GetTriangle()); return; } mesh.selection.SelectVertices(GetTriangle()); } private void TriggerDownModeNormal() { mesh.triangles.FlipNormalByVertices(GetTriangle()); } private void TriggerDownModeTriangleDelete() { RemoveTriangle(); } private void TriggerDownModePickColor() { Settings.SetFillColor(material.color); } private void TriggerDownModeFill() { Triangle triangle = mesh.triangles.FindTriangleByVertices(GetTriangle()); material = MaterialUtils.FillTriangle(mesh, triangle); } public void RemoveTriangle() { mesh.triangles.RemoveTriangleByVertices(GetTriangle()); } public UnityEngine.Material GetMaterial() { if (stickySelected) { return blendedStickySelectedMaterial; } else { return material; } } public void UpdateStickySelectedMaterial() { Color color = material.color * stickySelectedMaterial.color; color.a = 1.0f; blendedStickySelectedMaterial = MaterialCache.MaterialByColor(color, true, true, true); } public void SyncMaterials() { UpdateStickySelectedMaterial(); materials[0] = GetMaterial(); meshRenderer.materials = materials; selectable.unselectedMaterials = materials; selectable.outlineMesh = uMesh; selectable.UpdateSelectedMaterials(); } public void SetStickySelected(bool value) { stickySelected = value; SyncMaterials(); selectable.SetSelected(selectable.selected); } public void SetSelectable(bool value) { bool oldValue = isSelectable; isSelectable = value; if (isSelectable) { meshCollider.enabled = true; if (oldValue != true) UpdateMeshCollider(); } else { meshCollider.enabled = false; } } public void SetA(Vector3 newPosition) { a.position = newPosition; UpdateMeshes(); } public void SetB(Vector3 newPosition) { b.position = newPosition; UpdateMeshes(); } public void SetC(Vector3 newPosition) { c.position = newPosition; UpdateMeshes(); } public void UpdateMeshCollider() { collisionMeshVertices[0] = a.position - center; collisionMeshVertices[1] = b.position - center; collisionMeshVertices[2] = c.position - center; collisionMeshVertices[3] = -Vector3.Cross(b.position - a.position, c.position - a.position).normalized * 0.025f; collisionMesh.Clear(); collisionMesh.vertices = collisionMeshVertices; collisionMesh.triangles = collisionMeshTriangles; if (!(a.position == b.position || b.position == c.position)) meshCollider.sharedMesh = collisionMesh; } public void UpdateMeshes() { center = mesh.Center(a.position, b.position, c.position); transform.localPosition = center; UpdateMesh(); if (selectable) UpdateMeshCollider(); } private void UpdateMesh() { meshVertices[0] = a.position - center; meshVertices[1] = b.position - center; meshVertices[2] = c.position - center; uMesh.Clear(); uMesh.vertices = meshVertices; uMesh.triangles = meshTriangles; } public void UnsubscribeEvents() { if (a != null) a.OnUpdateVertex -= UpdateMeshes; if (b != null) b.OnUpdateVertex -= UpdateMeshes; if (c != null) c.OnUpdateVertex -= UpdateMeshes; } public void SubscribeEvents() { if (a != null) a.OnUpdateVertex += UpdateMeshes; if (b != null) b.OnUpdateVertex += UpdateMeshes; if (c != null) c.OnUpdateVertex += UpdateMeshes; } public void Populate(Vertex a, Vertex b, Vertex c, Vector3 center) { UnsubscribeEvents(); this.a = a; this.b = b; this.c = c; SubscribeEvents(); this.center = center; transform.localScale = Vector3.one; UpdateMesh(); if (selectable) UpdateMeshCollider(); } public Vertex[] GetTriangle() { Vertex[] triangle = new Vertex[] { a, b, c }; return triangle; } private void OnDisable() { UnsubscribeEvents(); } private void OnEnable() { SubscribeEvents(); } public void Initialize() { if (!hasInitialized) { // avoid GC alloc on subsequent calls selectable = GetComponent<Selectable>(); meshRenderer = GetComponent<MeshRenderer>(); meshCollider = GetComponent<MeshCollider>(); if (meshCollider == null) meshCollider = gameObject.AddComponent<MeshCollider>(); collisionMesh = new UnityEngine.Mesh(); collisionMeshVertices = new Vector3[4]; collisionMesh.vertices = new Vector3[4]; collisionMeshTriangles = new int[] { 0, 1, 2, 0, 3, 1, 3, 0, 2, 1, 3, 2 }; collisionMesh.triangles = collisionMeshTriangles; uMesh = gameObject.GetComponent<MeshFilter>().mesh; meshVertices = new Vector3[3]; uMesh.vertices = new Vector3[3]; meshTriangles = new int[3] { 0, 1, 2 }; uMesh.triangles = meshTriangles; materials = new UnityEngine.Material[1]; hasInitialized = true; } } // Use this for initialization void Start() { if (!hasInitialized) Initialize(); } } }
// ---------------------------------------------------------------------------------- // // 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 Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions; using Microsoft.WindowsAzure.Commands.ServiceManagement.Model; using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Commands.Sync.Download; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Security.Cryptography; using Security.Cryptography.X509Certificates; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests { internal class Utilities { #region Constants public static string windowsAzurePowershellPath = Path.Combine(Environment.CurrentDirectory, "ServiceManagement\\Azure"); public static string windowsAzurePowershellDefaultPath = Environment.CurrentDirectory; public const string windowsAzurePowershellServiceModule = "Azure.psd1"; public const string AzurePowershellModuleServiceManagementPirModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.PlatformImageRepository.dll"; public const string AzurePowershellModuleServiceManagementPreviewModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.Preview.dll"; // AzureAffinityGroup public const string NewAzureAffinityGroupCmdletName = "New-AzureAffinityGroup"; public const string GetAzureAffinityGroupCmdletName = "Get-AzureAffinityGroup"; public const string SetAzureAffinityGroupCmdletName = "Set-AzureAffinityGroup"; public const string RemoveAzureAffinityGroupCmdletName = "Remove-AzureAffinityGroup"; // AzureAvailablitySet public const string SetAzureAvailabilitySetCmdletName = "Set-AzureAvailabilitySet"; public const string RemoveAzureAvailabilitySetCmdletName = "Remove-AzureAvailabilitySet"; // AzureCertificate & AzureCertificateSetting public const string AddAzureCertificateCmdletName = "Add-AzureCertificate"; public const string GetAzureCertificateCmdletName = "Get-AzureCertificate"; public const string RemoveAzureCertificateCmdletName = "Remove-AzureCertificate"; public const string NewAzureCertificateSettingCmdletName = "New-AzureCertificateSetting"; // AzureDataDisk public const string AddAzureDataDiskCmdletName = "Add-AzureDataDisk"; public const string GetAzureDataDiskCmdletName = "Get-AzureDataDisk"; public const string SetAzureDataDiskCmdletName = "Set-AzureDataDisk"; public const string RemoveAzureDataDiskCmdletName = "Remove-AzureDataDisk"; // AzureDeployment public const string NewAzureDeploymentCmdletName = "New-AzureDeployment"; public const string GetAzureDeploymentCmdletName = "Get-AzureDeployment"; public const string SetAzureDeploymentCmdletName = "Set-AzureDeployment"; public const string RemoveAzureDeploymentCmdletName = "Remove-AzureDeployment"; public const string MoveAzureDeploymentCmdletName = "Move-AzureDeployment"; public const string GetAzureDeploymentEventCmdletName = "Get-AzureDeploymentEvent"; // AzureDisk public const string AddAzureDiskCmdletName = "Add-AzureDisk"; public const string GetAzureDiskCmdletName = "Get-AzureDisk"; public const string UpdateAzureDiskCmdletName = "Update-AzureDisk"; public const string RemoveAzureDiskCmdletName = "Remove-AzureDisk"; // AzureDns public const string NewAzureDnsCmdletName = "New-AzureDns"; public const string GetAzureDnsCmdletName = "Get-AzureDns"; public const string SetAzureDnsCmdletName = "Set-AzureDns"; public const string AddAzureDnsCmdletName = "Add-AzureDns"; public const string RemoveAzureDnsCmdletName = "Remove-AzureDns"; // AzureEndpoint public const string AddAzureEndpointCmdletName = "Add-AzureEndpoint"; public const string GetAzureEndpointCmdletName = "Get-AzureEndpoint"; public const string SetAzureEndpointCmdletName = "Set-AzureEndpoint"; public const string RemoveAzureEndpointCmdletName = "Remove-AzureEndpoint"; // AzureLocation public const string GetAzureLocationCmdletName = "Get-AzureLocation"; // AzureOSDisk & AzureOSVersion public const string GetAzureOSDiskCmdletName = "Get-AzureOSDisk"; public const string SetAzureOSDiskCmdletName = "Set-AzureOSDisk"; public const string GetAzureOSVersionCmdletName = "Get-AzureOSVersion"; // AzureProvisioningConfig public const string AddAzureProvisioningConfigCmdletName = "Add-AzureProvisioningConfig"; // AzurePublishSettingsFile public const string ImportAzurePublishSettingsFileCmdletName = "Import-AzurePublishSettingsFile"; public const string GetAzurePublishSettingsFileCmdletName = "Get-AzurePublishSettingsFile"; public const string AddAzureEnvironmentCmdletName = "Add-AzureEnvironment"; // AzureQuickVM public const string NewAzureQuickVMCmdletName = "New-AzureQuickVM"; // Get-AzureWinRMUri public const string GetAzureWinRMUriCmdletName = "Get-AzureWinRMUri"; // AzurePlatformExtension public const string PublishAzurePlatformExtensionCmdletName = "Publish-AzurePlatformExtension"; public const string SetAzurePlatformExtensionCmdletName = "Set-AzurePlatformExtension"; public const string UnpublishAzurePlatformExtensionCmdletName = "Unpublish-AzurePlatformExtension"; public const string NewAzurePlatformExtensionCertificateConfigCmdletName = "New-AzurePlatformExtensionCertificateConfig"; public const string NewAzurePlatformExtensionEndpointConfigSetCmdletName = "New-AzurePlatformExtensionEndpointConfigSet"; public const string SetAzurePlatformExtensionEndpointCmdletName = "Set-AzurePlatformExtensionEndpoint"; public const string RemoveAzurePlatformExtensionEndpointCmdletName = "Remove-AzurePlatformExtensionEndpoint"; public const string NewAzurePlatformExtensionLocalResourceConfigSetCmdletName = "New-AzurePlatformExtensionLocalResourceConfigSet"; public const string SetAzurePlatformExtensionLocalResourceCmdletName = "Set-AzurePlatformExtensionLocalResource"; public const string RemoveAzurePlatformExtensionLocalResourceCmdletName = "Remove-AzurePlatformExtensionLocalResource"; // AzurePlatformVMImage public const string SetAzurePlatformVMImageCmdletName = "Set-AzurePlatformVMImage"; public const string GetAzurePlatformVMImageCmdletName = "Get-AzurePlatformVMImage"; public const string RemoveAzurePlatformVMImageCmdletName = "Remove-AzurePlatformVMImage"; public const string NewAzurePlatformComputeImageConfigCmdletName = "New-AzurePlatformComputeImageConfig"; public const string NewAzurePlatformMarketplaceImageConfigCmdletName = "New-AzurePlatformMarketplaceImageConfig"; // AzureRemoteDesktopFile public const string GetAzureRemoteDesktopFileCmdletName = "Get-AzureRemoteDesktopFile"; // AzureReservedIP public const string NewAzureReservedIPCmdletName = "New-AzureReservedIP"; public const string GetAzureReservedIPCmdletName = "Get-AzureReservedIP"; public const string RemoveAzureReservedIPCmdletName = "Remove-AzureReservedIP"; public const string SetAzureReservedIPAssociationCmdletName = "Set-AzureReservedIPAssociation"; public const string RemoveAzureReservedIPAssociationCmdletName = "Remove-AzureReservedIPAssociation"; public const string AddAzureVirtualIPCmdletName = "Add-AzureVirtualIP"; public const string RemoveAzureVirtualIPCmdletName = "Remove-AzureVirtualIP"; // AzureRole & AzureRoleInstnace public const string GetAzureRoleCmdletName = "Get-AzureRole"; public const string SetAzureRoleCmdletName = "Set-AzureRole"; public const string GetAzureRoleInstanceCmdletName = "Get-AzureRoleInstance"; // AzureRoleSize public const string GetAzureRoleSizeCmdletName = "Get-AzureRoleSize"; // AzureService public const string NewAzureServiceCmdletName = "New-AzureService"; public const string GetAzureServiceCmdletName = "Get-AzureService"; public const string SetAzureServiceCmdletName = "Set-AzureService"; public const string RemoveAzureServiceCmdletName = "Remove-AzureService"; // AzureServiceAvailableExtension public const string GetAzureServiceAvailableExtensionCmdletName = "Get-AzureServiceAvailableExtension"; // AzureServiceExtension public const string NewAzureServiceExtensionConfigCmdletName = "New-AzureServiceExtensionConfig"; public const string SetAzureServiceExtensionCmdletName = "Set-AzureServiceExtension"; public const string GetAzureServiceExtensionCmdletName = "Get-AzureServiceExtension"; public const string RemoveAzureServiceExtensionCmdletName = "Remove-AzureServiceExtension"; // AzureServiceRemoteDesktopExtension public const string NewAzureServiceRemoteDesktopExtensionConfigCmdletName = "New-AzureServiceRemoteDesktopExtensionConfig"; public const string SetAzureServiceRemoteDesktopExtensionCmdletName = "Set-AzureServiceRemoteDesktopExtension"; public const string GetAzureServiceRemoteDesktopExtensionCmdletName = "Get-AzureServiceRemoteDesktopExtension"; public const string RemoveAzureServiceRemoteDesktopExtensionCmdletName = "Remove-AzureServiceRemoteDesktopExtension"; // AzureServiceDiagnosticExtension public const string NewAzureServiceDiagnosticsExtensionConfigCmdletName = "New-AzureServiceDiagnosticsExtensionConfig"; public const string SetAzureServiceDiagnosticsExtensionCmdletName = "Set-AzureServiceDiagnosticsExtension"; public const string GetAzureServiceDiagnosticsExtensionCmdletName = "Get-AzureServiceDiagnosticsExtension"; public const string RemoveAzureServiceDiagnosticsExtensionCmdletName = "Remove-AzureServiceDiagnosticsExtension"; // AzureSSHKey public const string NewAzureSSHKeyCmdletName = "New-AzureSSHKey"; // AzureStorageAccount public const string NewAzureStorageAccountCmdletName = "New-AzureStorageAccount"; public const string GetAzureStorageAccountCmdletName = "Get-AzureStorageAccount"; public const string SetAzureStorageAccountCmdletName = "Set-AzureStorageAccount"; public static string RemoveAzureStorageAccountCmdletName = "Remove-AzureStorageAccount"; //AzureDomainJoinExtension public const string NewAzureServiceDomainJoinExtensionConfig = "New-AzureServiceADDomainExtensionConfig"; public const string SetAzureServiceDomainJoinExtension = "Set-AzureServiceADDomainExtension"; public const string RemoveAzureServiceDomainJoinExtension = "Remove-AzureServiceADDomainExtension"; public const string GetAzureServiceDomainJoinExtension = "Get-AzureServiceADDomainExtension"; // AzureStorageKey public static string NewAzureStorageKeyCmdletName = "New-AzureStorageKey"; public static string GetAzureStorageKeyCmdletName = "Get-AzureStorageKey"; // AzureSubnet public static string GetAzureSubnetCmdletName = "Get-AzureSubnet"; public static string SetAzureSubnetCmdletName = "Set-AzureSubnet"; // AzureSubscription public const string GetAzureSubscriptionCmdletName = "Get-AzureSubscription"; public const string SetAzureSubscriptionCmdletName = "Set-AzureSubscription"; public const string SelectAzureSubscriptionCmdletName = "Select-AzureSubscription"; public const string RemoveAzureSubscriptionCmdletName = "Remove-AzureSubscription"; // AzureEnvironment public const string GetAzureEnvironmentCmdletName = "Get-AzureEnvironment"; public const string SetAzureEnvironmentCmdletName = "Set-AzureEnvironment"; // AzureVhd public static string AddAzureVhdCmdletName = "Add-AzureVhd"; public static string SaveAzureVhdCmdletName = "Save-AzureVhd"; // AzureVM public const string NewAzureVMCmdletName = "New-AzureVM"; public const string GetAzureVMCmdletName = "Get-AzureVM"; public const string UpdateAzureVMCmdletName = "Update-AzureVM"; public const string RemoveAzureVMCmdletName = "Remove-AzureVM"; public const string ExportAzureVMCmdletName = "Export-AzureVM"; public const string ImportAzureVMCmdletName = "Import-AzureVM"; public const string StartAzureVMCmdletName = "Start-AzureVM"; public const string StopAzureVMCmdletName = "Stop-AzureVM"; public const string RestartAzureVMCmdletName = "Restart-AzureVM"; // AzureVMConfig public const string NewAzureVMConfigCmdletName = "New-AzureVMConfig"; // AzureVMImage public const string AddAzureVMImageCmdletName = "Add-AzureVMImage"; public const string GetAzureVMImageCmdletName = "Get-AzureVMImage"; public const string RemoveAzureVMImageCmdletName = "Remove-AzureVMImage"; public const string SaveAzureVMImageCmdletName = "Save-AzureVMImage"; public const string UpdateAzureVMImageCmdletName = "Update-AzureVMImage"; // AzureVMSize public const string SetAzureVMSizeCmdletName = "Set-AzureVMSize"; // AzureVNetConfig & AzureVNetConnection public const string GetAzureVNetConfigCmdletName = "Get-AzureVNetConfig"; public const string SetAzureVNetConfigCmdletName = "Set-AzureVNetConfig"; public const string RemoveAzureVNetConfigCmdletName = "Remove-AzureVNetConfig"; public const string GetAzureVNetConnectionCmdletName = "Get-AzureVNetConnection"; // AzureVnetGateway & AzureVnetGatewayKey public const string NewAzureVNetGatewayCmdletName = "New-AzureVNetGateway"; public const string GetAzureVNetGatewayCmdletName = "Get-AzureVNetGateway"; public const string SetAzureVNetGatewayCmdletName = "Set-AzureVNetGateway"; public const string RemoveAzureVNetGatewayCmdletName = "Remove-AzureVNetGateway"; public const string GetAzureVNetGatewayKeyCmdletName = "Get-AzureVNetGatewayKey"; // AzureVNetSite public const string GetAzureVNetSiteCmdletName = "Get-AzureVNetSite"; // AzureWalkUpgradeDomain public const string SetAzureWalkUpgradeDomainCmdletName = "Set-AzureWalkUpgradeDomain"; public const string GetModuleCmdletName = "Get-Module"; public const string TestAzureNameCmdletName = "Test-AzureName"; public const string CopyAzureStorageBlobCmdletName = "Copy-AzureStorageBlob"; public static string SetAzureAclConfigCmdletName = "Set-AzureAclConfig"; public static string NewAzureAclConfigCmdletName = "New-AzureAclConfig"; public static string GetAzureAclConfigCmdletName = "Get-AzureAclConfig"; public static string SetAzureLoadBalancedEndpointCmdletName = "Set-AzureLoadBalancedEndpoint"; public const string ResetAzureRoleInstanceCmdletName = "ReSet-AzureRoleInstance"; //Static CA cmdlets public const string TestAzureStaticVNetIPCmdletName = "Test-AzureStaticVNetIP"; public const string SetAzureStaticVNetIPCmdletName = "Set-AzureStaticVNetIP"; public const string GetAzureStaticVNetIPCmdletName = "Get-AzureStaticVNetIP"; public const string RemoveAzureStaticVNetIPCmdletName = "Remove-AzureStaticVNetIP"; public const string GetAzureVMBGInfoExtensionCmdletName = "Get-AzureVMBGInfoExtension"; public const string SetAzureVMBGInfoExtensionCmdletName = "Set-AzureVMBGInfoExtension"; public const string RemoveAzureVMBGInfoExtensionCmdletName = "Remove-AzureVMBGInfoExtension"; // Generic Azure VM Extension cmdlets public const string GetAzureVMExtensionCmdletName = "Get-AzureVMExtension"; public const string SetAzureVMExtensionCmdletName = "Set-AzureVMExtension"; public const string RemoveAzureVMExtensionCmdletName = "Remove-AzureVMExtension"; public const string GetAzureVMAvailableExtensionCmdletName = "Get-AzureVMAvailableExtension"; public const string GetAzureVMExtensionConfigTemplateCmdletName = "Get-AzureVMExtensionConfigTemplate"; // VM Access Extesnion public const string GetAzureVMAccessExtensionCmdletName = "Get-AzureVMAccessExtension"; public const string SetAzureVMAccessExtensionCmdletName = "Set-AzureVMAccessExtension"; public const string RemoveAzureVMAccessExtensionCmdletName = "Remove-AzureVMAccessExtension"; // Custom script extension public const string SetAzureVMCustomScriptExtensionCmdletName = "Set-AzureVMCustomScriptExtension"; public const string GetAzureVMCustomScriptExtensionCmdletName = "Get-AzureVMCustomScriptExtension"; public const string RemoveAzureVMCustomScriptExtensionCmdletName = "Remove-AzureVMCustomScriptExtension"; public const string PaaSDiagnosticsExtensionName = "PaaSDiagnostics"; // VM Image Disk public const string GetAzureVMImageDiskConfigSetCmdletName = "Get-AzureVMImageDiskConfigSet"; public const string SetAzureVMImageDataDiskConfigCmdletName = "Set-AzureVMImageDataDiskConfig"; public const string SetAzureVMImageOSDiskConfigCmdletName = "Set-AzureVMImageOSDiskConfig"; public const string NewAzureVMImageDiskConfigSetCmdletName = "New-AzureVMImageDiskConfigSet"; //ILB public const string NewAzureInternalLoadBalancerConfigCmdletName = "New-AzureInternalLoadBalancerConfig"; public const string AddAzureInternalLoadBalancerCmdletName = "Add-AzureInternalLoadBalancer"; public const string GetAzureInternalLoadBalancerCmdletName = "Get-AzureInternalLoadBalancer"; public const string SetAzureInternalLoadBalancerCmdletName = "Set-AzureInternalLoadBalancer"; public const string RemoveAzureInternalLoadBalancerCmdletName = "Remove-AzureInternalLoadBalancer"; public const string SetAzurePublicIPCmdletName = "Set-AzurePublicIP"; public const string GetAzurePublicIPCmdletName = "Get-AzurePublicIP"; // NetworkInterface config public const string AddAzureNetworkInterfaceConfig = "Add-AzureNetworkInterfaceConfig"; public const string SetAzureNetworkInterfaceConfig = "Set-AzureNetworkInterfaceConfig"; public const string RemoveAzureNetworkInterfaceConfig = "Remove-AzureNetworkInterfaceConfig"; public const string GetAzureNetworkInterfaceConfig = "Get-AzureNetworkInterfaceConfig"; // SqlServer extension public const string SetAzureVMSqlServerExtensionCmdletName = "Set-AzureVMSqlServerExtension"; public const string GetAzureVMSqlServerExtensionCmdletName = "Get-AzureVMSqlServerExtension"; public const string RemoveAzureVMSqlServerExtensionCmdletName = "Remove-AzureVMSqlServerExtension"; #endregion private static ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); public static string GetUniqueShortName(string prefix = "", int length = 6, string suffix = "", bool includeDate = false) { string dateSuffix = ""; if (includeDate) { dateSuffix = string.Format("-{0}{1}", DateTime.Now.Year, DateTime.Now.DayOfYear); } return string.Format("{0}{1}{2}{3}", prefix, Guid.NewGuid().ToString("N").Substring(0, length), suffix, dateSuffix); } public static int MatchKeywords(string input, string[] keywords, bool exactMatch = true) { //returns -1 for no match, 0 for exact match, and a positive number for how many keywords are matched. int result = 0; if (string.IsNullOrEmpty(input) || keywords.Length == 0) return -1; foreach (string keyword in keywords) { //For whole word match, modify pattern to be "\b{0}\b" if (!string.IsNullOrEmpty(keyword) && Regex.IsMatch(input, string.Format(@"{0}", Regex.Escape(keyword)), RegexOptions.IgnoreCase)) { result++; } } if (result == keywords.Length) { return 0; } else if (result == 0) { return -1; } else { if (exactMatch) { return -1; } else { return result; } } } public static bool GetAzureVMAndWaitForReady(string serviceName, string vmName,int waitTime, int maxWaitTime ) { Console.WriteLine("Waiting for the vm {0} to reach \"ReadyRole\" "); DateTime startTime = DateTime.Now; DateTime MaxEndTime = startTime.AddMilliseconds(maxWaitTime); while (true) { Console.WriteLine("Getting vm '{0}' details:",vmName); var vmRoleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Console.WriteLine("Current status of the VM is {0} ", vmRoleContext.InstanceStatus); if (vmRoleContext.InstanceStatus == "ReadyRole") { Console.WriteLine("Instance status reached expected ReadyRole state. Exiting wait."); return true; } else { if (DateTime.Compare(DateTime.Now, MaxEndTime) > 0) { Console.WriteLine("Maximum wait time reached and instance status didnt reach \"ReadyRole\" state. Exiting wait. "); return false; } else { Console.WriteLine("Waiting for {0} seconds for the {1} status to be ReadyRole", waitTime / 1000, vmName); Thread.Sleep(waitTime); } } } } public static bool PrintAndCompareDeployment (DeploymentInfoContext deployment, string serviceName, string deploymentName, string deploymentLabel, string slot, string status, int instanceCount) { Console.WriteLine("ServiceName:{0}, DeploymentID: {1}, Uri: {2}", deployment.ServiceName, deployment.DeploymentId, deployment.Url.AbsoluteUri); Console.WriteLine("Name - {0}, Label - {1}, Slot - {2}, Status - {3}", deployment.DeploymentName, deployment.Label, deployment.Slot, deployment.Status); Console.WriteLine("RoleInstance: {0}", deployment.RoleInstanceList.Count); foreach (var instance in deployment.RoleInstanceList) { Console.WriteLine("InstanceName - {0}, InstanceStatus - {1}", instance.InstanceName, instance.InstanceStatus); } Assert.AreEqual(deployment.ServiceName, serviceName); Assert.AreEqual(deployment.DeploymentName, deploymentName); Assert.AreEqual(deployment.Label, deploymentLabel); Assert.AreEqual(deployment.Slot, slot); if (status != null) { Assert.AreEqual(deployment.Status, status); } Assert.AreEqual(deployment.RoleInstanceList.Count, instanceCount); Assert.IsNotNull(deployment.LastModifiedTime); Assert.IsNotNull(deployment.CreatedTime); return true; } // CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name' public static bool CheckRemove<Arg, Ret>(Func<Arg, Ret> fn, Arg name) { try { fn(name); Console.WriteLine("{0} still exists!", name); return false; } catch (Exception e) { if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("{0} does not exist.", name); return true; } else { Console.WriteLine("Error: {0}", e.ToString()); return false; } } } public static PersistentVM CreateVMObjectWithDataDiskSubnetAndAvailibilitySet(string vmName, OS os, string username, string password, string subnet) { string disk1 = "Disk1"; int diskSize = 30; string availabilitySetName = Utilities.GetUniqueShortName("AvailSet"); string img = string.Empty; bool isWindowsOs = false; if (os == OS.Windows) { img = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); isWindowsOs = true; } else { img = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux" }, false); isWindowsOs = false; } PersistentVM vm = Utilities.CreateIaaSVMObject(vmName, InstanceSize.Small, img, isWindowsOs, username, password); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize, disk1, 0, HostCaching.ReadWrite.ToString()); azureDataDiskConfigInfo1.Vm = vm; vm = vmPowershellCmdlets.SetAzureSubnet(vm, new string[] { subnet }); vm = vmPowershellCmdlets.SetAzureAvailabilitySet(availabilitySetName, vm); return vm; } // CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name' public static bool CheckRemove<Arg1, Arg2, Ret>(Func<Arg1, Arg2, Ret> fn, Arg1 name1, Arg2 name2) { try { fn(name1, name2); Console.WriteLine("{0}, {1} still exist!", name1, name2); return false; } catch (Exception e) { if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("{0}, {1} is successfully removed", name1, name2); return true; } else { Console.WriteLine("Error: {0}", e.ToString()); return false; } } } // CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name' public static bool CheckRemove<Arg1, Arg2, Arg3, Ret>(Func<Arg1, Arg2, Arg3, Ret> fn, Arg1 name1, Arg2 name2, Arg3 name3) { try { fn(name1, name2, name3); Console.WriteLine("{0}, {1}, {2} still exist!", name1, name2, name3); return false; } catch (Exception e) { if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("{0}, {1}, {2} is successfully removed", name1, name2, name3); return true; } else { Console.WriteLine("Error: {0}", e.ToString()); return false; } } } public static BlobHandle GetBlobHandle(string blob, string key) { BlobUri blobPath; Assert.IsTrue(BlobUri.TryParseUri(new Uri(blob), out blobPath)); return new BlobHandle(blobPath, key); } /// <summary> /// Retry the given action until success or timed out. /// </summary> /// <param name="act">the action</param> /// <param name="errorMessage">retry for this error message</param> /// <param name="maxTry">the max number of retries</param> /// <param name="intervalSeconds">the interval between retries</param> public static void RetryActionUntilSuccess(Action act, string errorMessage, int maxTry, int intervalSeconds) { int i = 0; while (i < maxTry) { try { act(); return; } catch (Exception e) { if (e.ToString().Contains(errorMessage) || (e.InnerException != null && e.InnerException.ToString().Contains(errorMessage))) { i++; if (i == maxTry) { Console.WriteLine("Max number of retry is reached: {0}", errorMessage); throw; } Console.WriteLine("{0} error occurs! retrying ...", errorMessage); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } Thread.Sleep(TimeSpan.FromSeconds(intervalSeconds)); continue; } else { Console.WriteLine(e); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } throw; } } } } /// <summary> /// Retry the given action until success or timed out. /// </summary> /// <param name="act">the action</param> /// <param name="errorMessages">retry for this error messages</param> /// <param name="maxTry">the max number of retries</param> /// <param name="intervalSeconds">the interval between retries</param> public static void RetryActionUntilSuccess(Action act, string[] errorMessages, int maxTry, int intervalSeconds) { int i = 0; while (i < maxTry) { try { act(); return; } catch (Exception e) { bool found = false; foreach (var errorMessage in errorMessages) { if (e.ToString().Contains(errorMessage) || (e.InnerException != null && e.InnerException.ToString().Contains(errorMessage))) { found = true; i++; if (i == maxTry) { Console.WriteLine("Max number of retry is reached: {0}", errorMessage); throw; } Console.WriteLine("{0} error occurs! retrying ...", errorMessage); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } Thread.Sleep(TimeSpan.FromSeconds(intervalSeconds)); break; } } if (!found) { Console.WriteLine(e); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } throw; } } } } /// <summary> /// This method verifies if a given error occurs during the action. Otherwise, it throws. /// </summary> /// <param name="act">Action item</param> /// <param name="errorMessage">Required error message</param> public static void VerifyFailure(Action act, string errorMessage) { try { act(); Assert.Fail("Should have failed, but it succeeded!!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } if (e.ToString().Contains(errorMessage)) { Console.WriteLine("This failure is expected: {0}", e.InnerException); } else { Console.WriteLine(e); throw; } } } /// <summary> /// /// </summary> /// <param name="act"></param> /// <param name="errorMessage"></param> public static void TryAndIgnore(Action act, string errorMessage) { try { act(); } catch (Exception e) { if (e.ToString().Contains(errorMessage)) { Console.WriteLine("Ignoring exception: {0}", e.InnerException); } else { Console.WriteLine(e); throw; } } } public static X509Certificate2 InstallCert(string certFile, StoreLocation location = StoreLocation.CurrentUser, StoreName name = StoreName.My) { var cert = new X509Certificate2(certFile); var certStore = new X509Store(name, location); certStore.Open(OpenFlags.ReadWrite); certStore.Add(cert); certStore.Close(); Console.WriteLine("Cert, {0}, is installed.", cert.Thumbprint); return cert; } public static void UninstallCert(X509Certificate2 cert, StoreLocation location, StoreName name) { try { X509Store certStore = new X509Store(name, location); certStore.Open(OpenFlags.ReadWrite); certStore.Remove(cert); certStore.Close(); Console.WriteLine("Cert, {0}, is uninstalled.", cert.Thumbprint); } catch (Exception e) { Console.WriteLine("Error during uninstalling the cert: {0}", e.ToString()); throw; } } public static X509Certificate2 CreateCertificate(string password, string issuer = "CN=Microsoft Azure Powershell Test", string friendlyName = "PSTest") { var keyCreationParameters = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowExport, KeyCreationOptions = CngKeyCreationOptions.None, KeyUsage = CngKeyUsages.AllUsages, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider }; keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None)); CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters); var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer)) { TakeOwnershipOfKey = true }; X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams); key = null; cert.FriendlyName = friendlyName; byte[] bytes = cert.Export(X509ContentType.Pfx, password); X509Certificate2 returnCert = new X509Certificate2(); returnCert.Import(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return returnCert; } public static SecureString convertToSecureString(string str) { SecureString secureStr = new SecureString(); foreach (char c in str) { secureStr.AppendChar(c); } return secureStr; } public static string FindSubstring(string givenStr, char givenChar, int i) { if (i > 0) { return FindSubstring(givenStr.Substring(givenStr.IndexOf(givenChar) + 1), givenChar, i - 1); } else { return givenStr; } } public static bool CompareDateTime(DateTime expectedDate, string givenDate) { DateTime resultExpDate = DateTime.Parse(givenDate); bool result = (resultExpDate.Day == expectedDate.Day); result &= (resultExpDate.Month == expectedDate.Month); result &= (resultExpDate.Year == expectedDate.Year); return result; } public static string GetInnerXml(string xmlString, string tag) { string removedHeader = "<" + Utilities.FindSubstring(xmlString, '<', 2); byte[] encodedString = Encoding.UTF8.GetBytes(xmlString); MemoryStream stream = new MemoryStream(encodedString); stream.Flush(); stream.Position = 0; XmlDocument xml = new XmlDocument(); xml.Load(stream); return xml.GetElementsByTagName(tag)[0].InnerXml; } public static void CompareWadCfg(string wadcfg, XmlDocument daconfig) { if (string.IsNullOrWhiteSpace(wadcfg)) { Assert.IsNull(wadcfg); } else { string innerXml = daconfig.InnerXml; StringAssert.Contains(Utilities.FindSubstring(innerXml, '<', 2), Utilities.FindSubstring(wadcfg, '<', 2)); } } static public string GenerateSasUri(string blobStorageEndpointFormat, string storageAccount, string storageAccountKey, string blobContainer, string vhdName, int hours = 10, bool read = true, bool write = true, bool delete = true, bool list = true) { string destinationSasUri = string.Format(@blobStorageEndpointFormat, storageAccount) + string.Format("/{0}/{1}", blobContainer, vhdName); var destinationBlob = new CloudPageBlob(new Uri(destinationSasUri), new StorageCredentials(storageAccount, storageAccountKey)); SharedAccessBlobPermissions permission = 0; permission |= (read) ? SharedAccessBlobPermissions.Read : 0; permission |= (write) ? SharedAccessBlobPermissions.Write : 0; permission |= (delete) ? SharedAccessBlobPermissions.Delete : 0; permission |= (list) ? SharedAccessBlobPermissions.List : 0; var policy = new SharedAccessBlobPolicy() { Permissions = permission, SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(hours) }; string destinationBlobToken = destinationBlob.GetSharedAccessSignature(policy); return (destinationSasUri + destinationBlobToken); } static public void RecordTimeTaken(ref DateTime prev) { var period = DateTime.Now - prev; Console.WriteLine("{0} minutes {1} seconds and {2} ms passed...", period.Minutes.ToString(), period.Seconds.ToString(), period.Milliseconds.ToString()); prev = DateTime.Now; } public static void PrintContext<T>(T obj) { PrintTypeContents(typeof(T), obj); } public static void PrintContextAndItsBase<T>(T obj) { Type type = typeof(T); PrintTypeContents(type, obj); PrintTypeContents(type.BaseType, obj); } private static void PrintTypeContents<T>(Type type, T obj) { foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null)); } else if (typeName.Contains("Boolean")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null).ToString()); } else { Console.WriteLine("This type is not printed: {0}", typeName); } } } public static void PrintCompleteContext<T>(T obj) { Type type = typeof(T); foreach (PropertyInfo property in type.GetProperties()) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null)); } else if (typeName.Contains("Boolean")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null).ToString()); } else { Console.WriteLine("This type is not printed: {0}", typeName); } } } public static bool validateHttpUri(string uri) { Uri uriResult; return Uri.TryCreate(uri, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp; } public static PersistentVM CreateIaaSVMObject(string vmName,InstanceSize size,string imageName,bool isWindows = true,string username = null,string password = null,bool disableGuestAgent = false) { //Create an IaaS VM var azureVMConfigInfo = new AzureVMConfigInfo(vmName, size.ToString(), imageName); AzureProvisioningConfigInfo azureProvisioningConfig = null; if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(username)) { azureProvisioningConfig = new AzureProvisioningConfigInfo(isWindows ? OS.Windows:OS.Linux, username, password,disableGuestAgent); } var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); return vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); } public static void PrintHeader(string title) { if (title.Length > 100) { Console.WriteLine(string.Format("{0}{1}{0}", "> > >", title)); } else { int headerLineLength = 100; Console.WriteLine(); Console.WriteLine(string.Format("{0}{1}{0}", new String('>', (headerLineLength - title.Length) / 2), title)); } } public static void PrintFooter(string title) { if (title.Length > 100) { Console.WriteLine(string.Format("{0}{1}{0}", "< < <", title)); } else { int headerLineLength = 100; string completed = ": Completed"; Console.WriteLine(string.Format("{0}{1}{0}", new String('<', (headerLineLength - (title.Length + completed.Length)) / 2), title + completed)); } } public static void PrintSeperationLineStart(string title,char seperator) { int headerLineLength = 100; string completed = ": Completed"; Console.WriteLine(string.Format("{0}{1}{0}", new String(seperator, (headerLineLength - (title.Length + completed.Length)) / 2), title + completed)); } public static void PrintSeperationLineEnd(string title,string successMessage, char seperator) { int headerLineLength = 100; Console.WriteLine(string.Format("{0}{1}{0}", new String(seperator, (headerLineLength - (title.Length + successMessage.Length)) / 2), title + successMessage)); } public static string ConvertToJsonArray(string[] values) { List<string> files = new List<string>(); foreach (string s in values) { files.Add(string.Format("'{0}'", s)); } return string.Join(",", files); } public static string GetSASUri(string blobUrlRoot,string storageAccoutnName,string primaryKey, string container, string filename, TimeSpan persmissionDuration,SharedAccessBlobPermissions permissionType) { // Set the destination string httpsBlobUrlRoot = string.Format("https:{0}", blobUrlRoot.Substring(blobUrlRoot.IndexOf('/'))); string vhdDestUri = httpsBlobUrlRoot + string.Format("{0}/{1}", container, filename); var destinationBlob = new CloudPageBlob(new Uri(vhdDestUri), new StorageCredentials(storageAccoutnName, primaryKey)); var policy2 = new SharedAccessBlobPolicy() { Permissions = permissionType, SharedAccessExpiryTime = DateTime.UtcNow.Add(persmissionDuration) }; var destinationBlobToken2 = destinationBlob.GetSharedAccessSignature(policy2); vhdDestUri += destinationBlobToken2; return vhdDestUri; } public static PersistentVM GetAzureVM(string vmName, string serviceName) { var vmroleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); return vmroleContext.VM; } public static void LogAssert(Action method,string actionTitle) { Console.Write(actionTitle); method(); Console.WriteLine(": verified"); } public static void ExecuteAndLog(Action method,string actionTitle) { PrintHeader(actionTitle); method(); PrintFooter(actionTitle); } public static VirtualMachineExtensionImageContext GetAzureVMExtenionInfo(string extensionName) { List<VirtualMachineExtensionImageContext> extensionInfo = new List<VirtualMachineExtensionImageContext>(); extensionInfo.AddRange(vmPowershellCmdlets.GetAzureVMAvailableExtension()); return extensionInfo.Find(c => c.ExtensionName.Equals(extensionName)); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 2:20:30 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.GeographicCategories { /// <summary> /// SpheroidBased /// </summary> public class SpheroidBased : CoordinateSystemCategory { #region Fields public readonly ProjectionInfo Airy1830; public readonly ProjectionInfo Airymodified; public readonly ProjectionInfo AustralianNational; public readonly ProjectionInfo Authalicsphere; public readonly ProjectionInfo AuthalicsphereARCINFO; public readonly ProjectionInfo AverageTerrestrialSystem1977; public readonly ProjectionInfo Bessel1841; public readonly ProjectionInfo BesselNamibia; public readonly ProjectionInfo Besselmodified; public readonly ProjectionInfo Clarke1858; public readonly ProjectionInfo Clarke1866; public readonly ProjectionInfo Clarke1866Michigan; public readonly ProjectionInfo Clarke1880; public readonly ProjectionInfo Clarke1880Arc; public readonly ProjectionInfo Clarke1880Benoit; public readonly ProjectionInfo Clarke1880IGN; public readonly ProjectionInfo Clarke1880RGS; public readonly ProjectionInfo Clarke1880SGA; public readonly ProjectionInfo Everest1830; public readonly ProjectionInfo Everestdefinition1967; public readonly ProjectionInfo Everestdefinition1975; public readonly ProjectionInfo Everestmodified; public readonly ProjectionInfo Everestmodified1969; public readonly ProjectionInfo Fischer1960; public readonly ProjectionInfo Fischer1968; public readonly ProjectionInfo Fischermodified; public readonly ProjectionInfo GRS1967; public readonly ProjectionInfo GRS1980; public readonly ProjectionInfo Helmert1906; public readonly ProjectionInfo Hough1960; public readonly ProjectionInfo IndonesianNational; public readonly ProjectionInfo International1924; public readonly ProjectionInfo International1967; public readonly ProjectionInfo Krasovsky1940; public readonly ProjectionInfo OSU1986geoidalmodel; public readonly ProjectionInfo OSU1991geoidalmodel; public readonly ProjectionInfo Plessis1817; public readonly ProjectionInfo SphereEMEP; public readonly ProjectionInfo Struve1860; public readonly ProjectionInfo Transitpreciseephemeris; public readonly ProjectionInfo WGS1966; public readonly ProjectionInfo Walbeck; public readonly ProjectionInfo WarOffice; #endregion #region Constructors /// <summary> /// Creates a new instance of SpheroidBased /// </summary> public SpheroidBased() { Airy1830 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=airy +no_defs "); Airymodified = ProjectionInfo.FromProj4String("+proj=longlat +a=6377340.189 +b=6356034.447938534 +no_defs "); AustralianNational = ProjectionInfo.FromProj4String("+proj=longlat +ellps=aust_SA +no_defs "); Authalicsphere = ProjectionInfo.FromProj4String("+proj=longlat +a=6371000 +b=6371000 +no_defs "); AuthalicsphereARCINFO = ProjectionInfo.FromProj4String("+proj=longlat +a=6370997 +b=6370997 +no_defs "); AverageTerrestrialSystem1977 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378135 +b=6356750.304921594 +no_defs "); Bessel1841 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bessel +no_defs "); Besselmodified = ProjectionInfo.FromProj4String("+proj=longlat +a=6377492.018 +b=6356173.508712696 +no_defs "); BesselNamibia = ProjectionInfo.FromProj4String("+proj=longlat +ellps=bess_nam +no_defs "); Clarke1858 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378293.639 +b=6356617.98149216 +no_defs "); Clarke1866 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk66 +no_defs "); Clarke1866Michigan = ProjectionInfo.FromProj4String("+proj=longlat +a=6378450.047 +b=6356826.620025999 +no_defs "); Clarke1880 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378249.138 +b=6356514.959419348 +no_defs "); Clarke1880Arc = ProjectionInfo.FromProj4String("+proj=longlat +a=6378249.145 +b=6356514.966395495 +no_defs "); Clarke1880Benoit = ProjectionInfo.FromProj4String("+proj=longlat +a=6378300.79 +b=6356566.430000036 +no_defs "); Clarke1880IGN = ProjectionInfo.FromProj4String("+proj=longlat +a=6378249.2 +b=6356514.999904194 +no_defs "); Clarke1880RGS = ProjectionInfo.FromProj4String("+proj=longlat +ellps=clrk80 +no_defs "); Clarke1880SGA = ProjectionInfo.FromProj4String("+proj=longlat +a=6378249.2 +b=6356514.996941779 +no_defs "); Everestdefinition1967 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=evrstSS +no_defs "); Everestdefinition1975 = ProjectionInfo.FromProj4String("+proj=longlat +a=6377301.243 +b=6356100.228368102 +no_defs "); Everest1830 = ProjectionInfo.FromProj4String("+proj=longlat +a=6377276.345 +b=6356075.41314024 +no_defs "); Everestmodified = ProjectionInfo.FromProj4String("+proj=longlat +a=6377304.063 +b=6356103.041812424 +no_defs "); Everestmodified1969 = ProjectionInfo.FromProj4String("+proj=longlat +a=6377295.664 +b=6356094.667915204 +no_defs "); Fischer1960 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378166 +b=6356784.283607107 +no_defs "); Fischer1968 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378150 +b=6356768.337244385 +no_defs "); Fischermodified = ProjectionInfo.FromProj4String("+proj=longlat +ellps=fschr60m +no_defs "); GRS1967 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS67 +no_defs "); GRS1980 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=GRS80 +no_defs "); Helmert1906 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=helmert +no_defs "); Hough1960 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378270 +b=6356794.343434343 +no_defs "); IndonesianNational = ProjectionInfo.FromProj4String("+proj=longlat +a=6378160 +b=6356774.50408554 +no_defs "); International1924 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=intl +no_defs "); International1967 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=aust_SA +no_defs "); Krasovsky1940 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=krass +no_defs "); OSU1986geoidalmodel = ProjectionInfo.FromProj4String("+proj=longlat +a=6378136.2 +b=6356751.516671965 +no_defs "); OSU1991geoidalmodel = ProjectionInfo.FromProj4String("+proj=longlat +a=6378136.3 +b=6356751.616336684 +no_defs "); Plessis1817 = ProjectionInfo.FromProj4String("+proj=longlat +a=6376523 +b=6355862.933255573 +no_defs "); SphereEMEP = ProjectionInfo.FromProj4String("+proj=longlat +a=6370000 +b=6370000 +no_defs "); Struve1860 = ProjectionInfo.FromProj4String("+proj=longlat +a=6378297 +b=6356655.847080379 +no_defs "); Transitpreciseephemeris = ProjectionInfo.FromProj4String("+proj=longlat +ellps=WGS66 +no_defs "); Walbeck = ProjectionInfo.FromProj4String("+proj=longlat +a=6376896 +b=6355834.846687364 +no_defs "); WarOffice = ProjectionInfo.FromProj4String("+proj=longlat +a=6378300.583 +b=6356752.270219594 +no_defs "); WGS1966 = ProjectionInfo.FromProj4String("+proj=longlat +ellps=WGS66 +no_defs "); Airy1830.GeographicInfo.Name = "GCS_Airy_1830"; Airymodified.GeographicInfo.Name = "GCS_Airy_Modified"; AustralianNational.GeographicInfo.Name = "GCS_Australian"; Authalicsphere.GeographicInfo.Name = "GCS_Sphere"; AuthalicsphereARCINFO.GeographicInfo.Name = "GCS_Sphere_ARC_INFO"; AverageTerrestrialSystem1977.GeographicInfo.Name = "GCS_ATS_1977"; Bessel1841.GeographicInfo.Name = "GCS_Bessel_1841"; Besselmodified.GeographicInfo.Name = "GCS_Bessel_Modified"; BesselNamibia.GeographicInfo.Name = "GCS_Bessel_Namibia"; Clarke1858.GeographicInfo.Name = "GCS_Clarke_1858"; Clarke1866.GeographicInfo.Name = "GCS_Clarke_1866"; Clarke1866Michigan.GeographicInfo.Name = "GCS_Clarke_1866_Michigan"; Clarke1880.GeographicInfo.Name = "GCS_Clarke_1880"; Clarke1880Arc.GeographicInfo.Name = "GCS_Clarke_1880_Arc"; Clarke1880Benoit.GeographicInfo.Name = "GCS_Clarke_1880_Benoit"; Clarke1880IGN.GeographicInfo.Name = "GCS_Clarke_1880_IGN"; Clarke1880RGS.GeographicInfo.Name = "GCS_Clarke_1880_RGS"; Clarke1880SGA.GeographicInfo.Name = "GCS_Clarke_1880_SGA"; Everestdefinition1967.GeographicInfo.Name = "GCS_Everest_def_1967"; Everestdefinition1975.GeographicInfo.Name = "GCS_Everest_def_1975"; Everest1830.GeographicInfo.Name = "GCS_Everest_1830"; Everestmodified.GeographicInfo.Name = "GCS_Everest_Modified"; Everestmodified1969.GeographicInfo.Name = "GCS_Everest_Modified_1969"; Fischer1960.GeographicInfo.Name = "GCS_Fischer_1960"; Fischer1968.GeographicInfo.Name = "GCS_Fischer_1968"; Fischermodified.GeographicInfo.Name = "GCS_Fischer_Modified"; GRS1967.GeographicInfo.Name = "GCS_GRS_1967"; GRS1980.GeographicInfo.Name = "GCS_GRS_1980"; Helmert1906.GeographicInfo.Name = "GCS_Helmert_1906"; Hough1960.GeographicInfo.Name = "GCS_Hough_1960"; IndonesianNational.GeographicInfo.Name = "GCS_Indonesian"; International1924.GeographicInfo.Name = "GCS_International_1924"; International1967.GeographicInfo.Name = "GCS_International_1967"; Krasovsky1940.GeographicInfo.Name = "GCS_Krasovsky_1940"; OSU1986geoidalmodel.GeographicInfo.Name = "GCS_OSU_86F"; OSU1991geoidalmodel.GeographicInfo.Name = "GCS_OSU_91A"; Plessis1817.GeographicInfo.Name = "GCS_Plessis_1817"; SphereEMEP.GeographicInfo.Name = "GCS_Sphere_EMEP"; Struve1860.GeographicInfo.Name = "GCS_Struve_1860"; Transitpreciseephemeris.GeographicInfo.Name = "GCS_NWL_9D"; Walbeck.GeographicInfo.Name = "GCS_Walbeck"; WarOffice.GeographicInfo.Name = "GCS_War_Office"; WGS1966.GeographicInfo.Name = "GCS_WGS_1966"; Airy1830.GeographicInfo.Datum.Name = "D_Airy_1830"; Airymodified.GeographicInfo.Datum.Name = "D_Airy_Modified"; AustralianNational.GeographicInfo.Datum.Name = "D_Australian"; Authalicsphere.GeographicInfo.Datum.Name = "D_Sphere"; AuthalicsphereARCINFO.GeographicInfo.Datum.Name = "D_Sphere_ARC_INFO"; AverageTerrestrialSystem1977.GeographicInfo.Datum.Name = "D_ATS_1977"; Bessel1841.GeographicInfo.Datum.Name = "D_Bessel_1841"; Besselmodified.GeographicInfo.Datum.Name = "D_Bessel_Modified"; BesselNamibia.GeographicInfo.Datum.Name = "D_Bessel_Namibia"; Clarke1858.GeographicInfo.Datum.Name = "D_Clarke_1858"; Clarke1866.GeographicInfo.Datum.Name = "D_Clarke_1866"; Clarke1866Michigan.GeographicInfo.Datum.Name = "D_Clarke_1866_Michigan"; Clarke1880.GeographicInfo.Datum.Name = "D_Clarke_1880"; Clarke1880Arc.GeographicInfo.Datum.Name = "D_Clarke_1880_Arc"; Clarke1880Benoit.GeographicInfo.Datum.Name = "D_Clarke_1880_Benoit"; Clarke1880IGN.GeographicInfo.Datum.Name = "D_Clarke_1880_IGN"; Clarke1880RGS.GeographicInfo.Datum.Name = "D_Clarke_1880_RGS"; Clarke1880SGA.GeographicInfo.Datum.Name = "D_Clarke_1880_SGA"; Everestdefinition1967.GeographicInfo.Datum.Name = "D_Everest_Def_1967"; Everestdefinition1975.GeographicInfo.Datum.Name = "D_Everest_Def_1975"; Everest1830.GeographicInfo.Datum.Name = "D_Everest_1830"; Everestmodified.GeographicInfo.Datum.Name = "D_Everest_Modified"; Everestmodified1969.GeographicInfo.Datum.Name = "D_Everest_Modified_1969"; Fischer1960.GeographicInfo.Datum.Name = "D_Fischer_1960"; Fischer1968.GeographicInfo.Datum.Name = "D_Fischer_1968"; Fischermodified.GeographicInfo.Datum.Name = "D_Fischer_Modified"; GRS1967.GeographicInfo.Datum.Name = "D_GRS_1967"; GRS1980.GeographicInfo.Datum.Name = "D_GRS_1980"; Helmert1906.GeographicInfo.Datum.Name = "D_Helmert_1906"; Hough1960.GeographicInfo.Datum.Name = "D_Hough_1960"; IndonesianNational.GeographicInfo.Datum.Name = "D_Indonesian"; International1924.GeographicInfo.Datum.Name = "D_International_1924"; International1967.GeographicInfo.Datum.Name = "D_International_1967"; Krasovsky1940.GeographicInfo.Datum.Name = "D_Krasovsky_1940"; OSU1986geoidalmodel.GeographicInfo.Datum.Name = "D_OSU_86F"; OSU1991geoidalmodel.GeographicInfo.Datum.Name = "D_OSU_91A"; Plessis1817.GeographicInfo.Datum.Name = "D_Plessis_1817"; SphereEMEP.GeographicInfo.Datum.Name = "D_Sphere_EMEP"; Struve1860.GeographicInfo.Datum.Name = "D_Struve_1860"; Transitpreciseephemeris.GeographicInfo.Datum.Name = "D_NWL_9D"; Walbeck.GeographicInfo.Datum.Name = "D_Walbeck"; WarOffice.GeographicInfo.Datum.Name = "D_War_Office"; WGS1966.GeographicInfo.Datum.Name = "D_WGS_1966"; } #endregion } } #pragma warning restore 1591
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Compute.Fluent { using Models; using System; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Helper type to enable or disable virtual machine disk (OS, Data) encryption. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVFbmNyeXB0aW9uSGVscGVy internal partial class VirtualMachineEncryptionHelper : object { private string encryptionExtensionPublisher = "Microsoft.Azure.Security"; private OperatingSystemTypes osType; private IVirtualMachine virtualMachine; private readonly string ERROR_ENCRYPTION_EXTENSION_NOT_FOUND = "Expected encryption extension not found in the VM"; private readonly string ERROR_NON_SUCCESS_PROVISIONING_STATE = "Extension needed for disk encryption was not provisioned correctly, found ProvisioningState as '%s'"; private readonly string ERROR_EXPECTED_KEY_VAULT_URL_NOT_FOUND = "Could not found URL pointing to the secret for disk encryption"; private readonly string ERROR_EXPECTED_ENCRYPTION_EXTENSION_STATUS_NOT_FOUND = "Encryption extension with successful status not found in the VM"; private readonly string ERROR_ENCRYPTION_EXTENSION_STATUS_IS_EMPTY = "Encryption extension status is empty"; private readonly string ERROR_ON_LINUX_DECRYPTING_NON_DATA_DISK_IS_NOT_SUPPORTED = "Only data disk is supported to disable encryption on Linux VM"; private readonly string ERROR_ON_LINUX_DATA_DISK_DECRYPT_NOT_ALLOWED_IF_OS_DISK_IS_ENCRYPTED = "On Linux VM disabling data disk encryption is allowed only if OS disk is not encrypted"; /// <summary> /// Creates VirtualMachineEncryptionHelper. /// </summary> /// <param name="virtualMachine">The virtual machine to enable or disable encryption.</param> ///GENMHASH:FC0CE97F5CDB23A526AC5FBD778B25E4:B371E9156A68585E5C6F1DA9109A9E4F internal VirtualMachineEncryptionHelper(IVirtualMachine virtualMachine) { this.virtualMachine = virtualMachine; this.osType = this.virtualMachine.OSType; } /// <summary> /// Retrieves encryption extension installed in the virtual machine, if the extension is /// not installed then return an empty observable. /// </summary> /// <return>An observable that emits the encryption extension installed in the virtual machine.</return> ///GENMHASH:9E0CF934F182F50D2FE7A72E02617F94:324B026FB14C16BEDA7B060212E59DE0 private async Task<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineExtension> GetEncryptionExtensionInstalledInVMAsync(CancellationToken cancellationToken = default(CancellationToken)) { var extensions = await virtualMachine.ListExtensionsAsync(cancellationToken); IVirtualMachineExtension encryptionExtension = extensions .FirstOrDefault(e => e.PublisherName.Equals(encryptionExtensionPublisher, StringComparison.OrdinalIgnoreCase) && e.TypeName.Equals(EncryptionExtensionType(), StringComparison.OrdinalIgnoreCase)); return encryptionExtension; } /// <summary> /// Prepare encryption extension using provided configuration and install it in the virtual machine. /// </summary> /// <param name="encryptConfig">The volume encryption configuration.</param> /// <return>An observable that emits updated virtual machine.</return> ///GENMHASH:90F5E95CF3EB9C10D9E436E206241DB8:709FA1AD6AFC4D8E0EEEB4F58D788AFA private async Task<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachine> InstallEncryptionExtensionAsync(EnableDisableEncryptConfig encryptConfig, CancellationToken cancellationToken = default(CancellationToken)) { string extensionName = EncryptionExtensionType(); return await virtualMachine.Update() .DefineNewExtension(extensionName) .WithPublisher(encryptionExtensionPublisher) .WithType(EncryptionExtensionType()) .WithVersion(EncryptionExtensionVersion()) .WithPublicSettings(encryptConfig.ExtensionPublicSettings()) .WithProtectedSettings(encryptConfig.ExtensionProtectedSettings()) .WithMinorVersionAutoUpgrade() .Attach() .ApplyAsync(cancellationToken); } /// <summary> /// Gets status object that describes the current status of the volume encryption or decryption process. /// </summary> /// <param name="virtualMachine">The virtual machine on which encryption or decryption is running.</param> /// <return>An observable that emits current encrypt or decrypt status.</return> ///GENMHASH:320925F5DE599EF676589095F72B25CB:2FDB3461FF786FBAE2C4F7E37E373582 private async Task<Microsoft.Azure.Management.Compute.Fluent.IDiskVolumeEncryptionMonitor> GetDiskVolumeEncryptDecryptStatusAsync(IVirtualMachine virtualMachine, CancellationToken cancellationToken = default(CancellationToken)) { IDiskVolumeEncryptionMonitor monitor = null; if (osType == OperatingSystemTypes.Linux) { monitor = new LinuxDiskVolumeEncryptionMonitorImpl(virtualMachine.Id, virtualMachine.Manager); } else { monitor = new WindowsVolumeEncryptionMonitorImpl(virtualMachine.Id, virtualMachine.Manager); } return await monitor.RefreshAsync(cancellationToken); } /// <summary> /// Retrieves the encryption extension status from the extension instance view. /// An error observable will be returned if /// 1. extension is not installed /// 2. extension is not provisioned successfully /// 2. extension status could be retrieved (either not found or empty). /// </summary> /// <param name="statusEmptyErrorMessage">The error message to emit if unable to locate the status.</param> /// <return>An observable that emits status message.</return> ///GENMHASH:5D5D4450A8A3676D4AB254F68D0D6E6F:FD676570747D9407B4E5BA65CEA5012A private async Task<string> RetrieveEncryptionExtensionStatusStringAsync(string statusEmptyErrorMessage, CancellationToken cancellationToken = default(CancellationToken)) { IVirtualMachineExtension encryptionExtension = await GetEncryptionExtensionInstalledInVMAsync(cancellationToken); if (encryptionExtension == null) { throw new Exception(ERROR_ENCRYPTION_EXTENSION_NOT_FOUND); } if (!encryptionExtension.ProvisioningState.Equals("Succeeded", StringComparison.OrdinalIgnoreCase)) { throw new Exception(string.Format(ERROR_NON_SUCCESS_PROVISIONING_STATE, encryptionExtension.ProvisioningState)); } VirtualMachineExtensionInstanceView instanceView = await encryptionExtension.GetInstanceViewAsync(cancellationToken); if (instanceView == null || instanceView.Statuses == null || instanceView.Statuses.Count == 0) { throw new Exception(ERROR_EXPECTED_ENCRYPTION_EXTENSION_STATUS_NOT_FOUND); } string extensionStatus = instanceView.Statuses[0].Message; if (string.IsNullOrEmpty(extensionStatus)) { throw new Exception(statusEmptyErrorMessage); } return extensionStatus; } /// <summary> /// Updates the virtual machine's OS Disk model with the encryption specific details so that platform can /// use it while booting the virtual machine. /// </summary> /// <param name="encryptConfig">The configuration specific to enabling the encryption.</param> /// <param name="encryptionSecretKeyVaultUrl">The keyVault URL pointing to secret holding disk encryption key.</param> /// <return>An observable that emits updated virtual machine.</return> ///GENMHASH:67C0461B156AC4E3B99954E3C1D2CBC6:FD88377F886FF359056146DABA972399 private async Task<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachine> UpdateVMStorageProfileAsync(EnableDisableEncryptConfig encryptConfig, string encryptionSecretKeyVaultUrl, CancellationToken cancellationToken = default(CancellationToken)) { var diskEncryptionSettings = encryptConfig.StorageProfileEncryptionSettings(); diskEncryptionSettings.DiskEncryptionKey.SecretUrl = encryptionSecretKeyVaultUrl; return await virtualMachine.Update() .WithOSDiskEncryptionSettings(diskEncryptionSettings) .ApplyAsync(cancellationToken); } /// <summary> /// Updates the virtual machine's OS Disk model with the encryption specific details. /// </summary> /// <param name="encryptConfig">The configuration specific to disabling the encryption.</param> /// <return>An observable that emits updated virtual machine.</return> ///GENMHASH:9E912268A5CDF429573A7112EC718690:63BF821D222D03E59BCD43264C3339D8 private async Task<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachine> UpdateVMStorageProfileAsync(EnableDisableEncryptConfig encryptConfig, CancellationToken cancellationToken = default(CancellationToken)) { DiskEncryptionSettings diskEncryptionSettings = encryptConfig.StorageProfileEncryptionSettings(); return await virtualMachine.Update() .WithOSDiskEncryptionSettings(diskEncryptionSettings) .ApplyAsync(cancellationToken); } /// <return>OS specific encryption extension version.</return> ///GENMHASH:C6B6A6BE7125F3222921978BAAAD158C:DA7BCCD8F3EBB8DF30FE3B09A51993F0 private string EncryptionExtensionVersion() { if (this.osType == OperatingSystemTypes.Linux) { return "0.1"; } else { return "1.1"; } } /// <return>OS specific encryption extension type.</return> ///GENMHASH:EB5E4873902883B7A5D561248699E59F:0697EDE3B59F3C8FC56609ECBD880CD3 private string EncryptionExtensionType() { if (this.osType == OperatingSystemTypes.Linux) { return "AzureDiskEncryptionForLinux"; } else { return "AzureDiskEncryption"; } } /// <summary> /// Enables encryption. /// </summary> /// <param name="encryptionSettings">The settings to be used for encryption extension.</param> /// <param name="">The Windows or Linux encryption settings.</param> /// <return>An observable that emits the encryption status.</return> ///GENMHASH:FB7DBA27A41CC76685F21AB0A9729C82:D88D73A86520940C4EA57E9CEEA1516F internal async Task<IDiskVolumeEncryptionMonitor> EnableEncryptionAsync<T>(VirtualMachineEncryptionConfiguration<T> encryptionSettings, CancellationToken cancellationToken = default(CancellationToken)) where T : VirtualMachineEncryptionConfiguration<T> { var encryptConfig = new EnableEncryptConfig<T>(encryptionSettings); // Update the encryption extension if already installed // IVirtualMachine virtualMachine = await UpdateEncryptionExtensionAsync(encryptConfig, cancellationToken); if (virtualMachine == null) { // If encryption extension is not installed then install it // virtualMachine = await InstallEncryptionExtensionAsync(encryptConfig, cancellationToken); } // Retrieve the encryption key URL after extension install or update // string keyVaultSecretUrl = await RetrieveEncryptionExtensionStatusStringAsync(ERROR_EXPECTED_KEY_VAULT_URL_NOT_FOUND, cancellationToken); // Update the VM's OS Disk (in storage profile) with the encryption metadata // virtualMachine = await UpdateVMStorageProfileAsync(encryptConfig, keyVaultSecretUrl, cancellationToken); // Gets the encryption status // return await GetDiskVolumeEncryptDecryptStatusAsync(virtualMachine, cancellationToken); } /// <summary> /// Updates the encryption extension in the virtual machine using provided configuration. /// If extension is not installed then this method return null else the updated vm. /// </summary> /// <param name="encryptConfig">The volume encryption configuration.</param> /// <return>Tasks that emits updated virtual machine.</return> ///GENMHASH:99CCEB2CE75C64E72E8D4CB8CFDA73B5:B2EAD454D0D489C6F6AC659E4EB949F0 private async Task<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachine> UpdateEncryptionExtensionAsync(EnableDisableEncryptConfig encryptConfig, CancellationToken cancellationToken = default(CancellationToken)) { IVirtualMachineExtension extension = await GetEncryptionExtensionInstalledInVMAsync(cancellationToken); if (extension == null) { return await Task.FromResult<IVirtualMachine>(null); } return await virtualMachine.Update() .UpdateExtension(extension.Name) .WithPublicSettings(encryptConfig.ExtensionPublicSettings()) .WithProtectedSettings(encryptConfig.ExtensionProtectedSettings()) .Parent() .ApplyAsync(cancellationToken); } /// <summary> /// Checks the given volume type in the virtual machine can be decrypted. /// </summary> /// <param name="volumeType">The volume type to decrypt.</param> /// <return>Observable that emit true if no validation error otherwise error observable.</return> ///GENMHASH:88D2478D6B927119AD5935A29B7D7C60:D8EC0364E38FD84A3DD1F18E9AF6198A private async Task<bool> ValidateBeforeDecryptAsync(DiskVolumeType volumeType, CancellationToken cancellationToken = default(CancellationToken)) { if (osType == OperatingSystemTypes.Linux) { if (volumeType != DiskVolumeType.Data) { throw new Exception(ERROR_ON_LINUX_DECRYPTING_NON_DATA_DISK_IS_NOT_SUPPORTED); } var monitor = await GetDiskVolumeEncryptDecryptStatusAsync(virtualMachine, cancellationToken); if (monitor.OSDiskStatus.Equals(EncryptionStatus.Encrypted)) { throw new Exception(ERROR_ON_LINUX_DATA_DISK_DECRYPT_NOT_ALLOWED_IF_OS_DISK_IS_ENCRYPTED); } } return true; } /// <summary> /// Disables encryption on the given disk volume. /// </summary> /// <param name="volumeType">The disk volume.</param> /// <return>An observable that emits the decryption status.</return> ///GENMHASH:B980B0A762D67885E3B127392FD42890:A65E5C07D8DA37A2AB5EC199276933B9 internal async Task<Microsoft.Azure.Management.Compute.Fluent.IDiskVolumeEncryptionMonitor> DisableEncryptionAsync(DiskVolumeType volumeType, CancellationToken cancellationToken = default(CancellationToken)) { EnableDisableEncryptConfig encryptConfig = new DisableEncryptConfig(volumeType); await ValidateBeforeDecryptAsync(volumeType, cancellationToken); // Update the encryption extension if already installed // IVirtualMachine virtualMachine = await UpdateEncryptionExtensionAsync(encryptConfig, cancellationToken); if (virtualMachine == null) { // If encryption extension is not then install it // virtualMachine = await InstallEncryptionExtensionAsync(encryptConfig, cancellationToken); } // Validate and retrieve the encryption extension status // string status = await RetrieveEncryptionExtensionStatusStringAsync(ERROR_ENCRYPTION_EXTENSION_STATUS_IS_EMPTY, cancellationToken); // Update the VM's OS profile by marking encryption disabled // virtualMachine = await UpdateVMStorageProfileAsync(encryptConfig, cancellationToken); // Gets the encryption status // return await GetDiskVolumeEncryptDecryptStatusAsync(virtualMachine, cancellationToken); } } /// <summary> /// Base type representing configuration for enabling and disabling disk encryption. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVFbmNyeXB0aW9uSGVscGVyLkVuYWJsZURpc2FibGVFbmNyeXB0Q29uZmln internal abstract partial class EnableDisableEncryptConfig { /// <return>Encryption specific settings to be set on virtual machine storage profile.</return> ///GENMHASH:861A97732A551A94F695C3B49DFAB96C:27E486AB74A10242FF421C0798DDC450 public abstract DiskEncryptionSettings StorageProfileEncryptionSettings(); /// <return>Encryption extension public settings.</return> ///GENMHASH:112DFE7CB9D7594A6C865E2D6CC357DD:27E486AB74A10242FF421C0798DDC450 public abstract IDictionary<string, object> ExtensionPublicSettings(); /// <return>Encryption extension protected settings.</return> ///GENMHASH:42BADBBDF9B8511E182143831C7F0FF6:27E486AB74A10242FF421C0798DDC450 public abstract IDictionary<string, object> ExtensionProtectedSettings(); } /// <summary> /// Base type representing configuration for enabling disk encryption. /// </summary> /// <param><T>.</param> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVFbmNyeXB0aW9uSGVscGVyLkVuYWJsZUVuY3J5cHRDb25maWc= internal partial class EnableEncryptConfig<T> : EnableDisableEncryptConfig where T : VirtualMachineEncryptionConfiguration<T> { private VirtualMachineEncryptionConfiguration<T> settings; ///GENMHASH:A4680AAD3C732AD8C23180D4695F0002:2D5ABDE502752AC4098DD0B501F665E5 public EnableEncryptConfig(VirtualMachineEncryptionConfiguration<T> settings) { this.settings = settings; } ///GENMHASH:861A97732A551A94F695C3B49DFAB96C:E348102753EC23A2170268E43AF0844B public override DiskEncryptionSettings StorageProfileEncryptionSettings() { KeyVaultKeyReference keyEncryptionKey = null; if (settings.KeyEncryptionKeyURL() != null) { keyEncryptionKey = new KeyVaultKeyReference() { KeyUrl = settings.KeyEncryptionKeyURL() }; if (settings.KeyEncryptionKeyVaultId() != null) { keyEncryptionKey.SourceVault = new ResourceManager.Fluent.SubResource() { Id = settings.KeyEncryptionKeyVaultId() }; } } DiskEncryptionSettings diskEncryptionSettings = new DiskEncryptionSettings() { Enabled = true, KeyEncryptionKey = keyEncryptionKey, DiskEncryptionKey = new KeyVaultSecretReference() { SourceVault = new ResourceManager.Fluent.SubResource() { Id = settings.KeyVaultId() } } }; return diskEncryptionSettings; } ///GENMHASH:112DFE7CB9D7594A6C865E2D6CC357DD:A73CB70ECA05F57606DC4D8C914F8EB6 public override IDictionary<string, object> ExtensionPublicSettings() { var publicSettings = new Dictionary<string, object>(); publicSettings.Add("EncryptionOperation", "EnableEncryption"); publicSettings.Add("AADClientID", settings.AadClientId()); publicSettings.Add("KeyEncryptionAlgorithm", settings.VolumeEncryptionKeyEncryptAlgorithm()); publicSettings.Add("KeyVaultURL", settings.KeyVaultUrl()); publicSettings.Add("VolumeType", settings.VolumeType().ToString()); publicSettings.Add("SequenceVersion", Guid.NewGuid().ToString()); if (settings.KeyEncryptionKeyURL() != null) { publicSettings.Add("KeyEncryptionKeyURL", settings.KeyEncryptionKeyURL()); } return publicSettings; } ///GENMHASH:42BADBBDF9B8511E182143831C7F0FF6:310634F314DEDED02B268CD45ABDDF80 public override IDictionary<string, object> ExtensionProtectedSettings() { var protectedSettings = new Dictionary<string, object>(); protectedSettings.Add("AADClientSecret", settings.AadSecret()); if (settings.OsType() == OperatingSystemTypes.Linux && settings.LinuxPassPhrase() != null) { protectedSettings.Add("Passphrase", settings.LinuxPassPhrase()); } return protectedSettings; } } /// <summary> /// Base type representing configuration for disabling disk encryption. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVFbmNyeXB0aW9uSGVscGVyLkRpc2FibGVFbmNyeXB0Q29uZmln internal partial class DisableEncryptConfig : EnableDisableEncryptConfig { private DiskVolumeType volumeType; ///GENMHASH:ED81FD69658AB4C787751DF16402585E:43501F666AB8B6252C9423192FE5CC88 internal DisableEncryptConfig(DiskVolumeType volumeType) { this.volumeType = volumeType; } ///GENMHASH:861A97732A551A94F695C3B49DFAB96C:8745D610DD6AEA078F21FC3C57C74909 public override DiskEncryptionSettings StorageProfileEncryptionSettings() { return new DiskEncryptionSettings() { Enabled = false }; } ///GENMHASH:112DFE7CB9D7594A6C865E2D6CC357DD:9C5C71076B1A45D64B463082FDD67FF0 public override IDictionary<string, object> ExtensionPublicSettings() { Dictionary<string, object> publicSettings = new Dictionary<string, object>(); publicSettings.Add("EncryptionOperation", "DisableEncryption"); publicSettings.Add("SequenceVersion", Guid.NewGuid().ToString()); publicSettings.Add("VolumeType", this.volumeType); return publicSettings; } ///GENMHASH:42BADBBDF9B8511E182143831C7F0FF6:91C3605EF0B602A2AC8FE63B07EDB661 public override IDictionary<string, object> ExtensionProtectedSettings() { return new Dictionary<string, object>(); } } }
// Copyright 2004-2008 Castle Project - http://www.castleproject.org/ // // 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 Commons.Collections { using System; using System.Collections; /// <summary> /// A keyed list with a fixed maximum size which removes /// the least recently used entry if an entry is added when full. /// </summary> [Serializable] public class LRUMap : ICollection, IDictionary, IEnumerable { private Hashtable objectTable = new Hashtable(); private ArrayList objectList = new ArrayList(); /// <summary> /// Default maximum size /// </summary> protected internal const int DEFAULT_MAX_SIZE = 100; /// <summary> /// Maximum size /// </summary> [NonSerialized] private int maxSize; public LRUMap() : this(DEFAULT_MAX_SIZE) { } public LRUMap(Int32 maxSize) { this.maxSize = maxSize; } public virtual void Add(object key, object value) { if (objectList.Count == maxSize) { RemoveLRU(); } objectTable.Add(key, value); objectList.Insert(0, new DictionaryEntry(key, value)); } public virtual void Clear() { objectTable.Clear(); objectList.Clear(); } public virtual bool Contains(object key) { return objectTable.Contains(key); } public virtual void CopyTo(Array array, int idx) { objectTable.CopyTo(array, idx); } public virtual void Remove(object key) { objectTable.Remove(key); objectList.RemoveAt(IndexOf(key)); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new KeyedListEnumerator(objectList); } IEnumerator IEnumerable.GetEnumerator() { return new KeyedListEnumerator(objectList); } public virtual int Count { get { return objectList.Count; } } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsReadOnly { get { return false; } } public virtual bool IsSynchronized { get { return false; } } /// <summary> /// Gets the maximum size of the map (the bound). /// </summary> public Int32 MaxSize { get { return maxSize; } } // public object this[int idx] { // Get { return ((DictionaryEntry) objectList[idx]).Value; } // set { // if (idx < 0 || idx >= Count) // throw new ArgumentOutOfRangeException ("index"); // // object key = ((DictionaryEntry) objectList[idx]).Key; // objectList[idx] = new DictionaryEntry (key, value); // objectTable[key] = value; // } // } public virtual object this[object key] { get { MoveToMRU(key); return objectTable[key]; } set { if (objectTable.Contains(key)) { Remove(key); } Add(key, value); } } public virtual ICollection Keys { get { ArrayList retList = new ArrayList(); for(int i = 0; i < objectList.Count; i++) { retList.Add(((DictionaryEntry) objectList[i]).Key); } return retList; } } public virtual ICollection Values { get { ArrayList retList = new ArrayList(); for(int i = 0; i < objectList.Count; i++) { retList.Add(((DictionaryEntry) objectList[i]).Value); } return retList; } } public virtual object SyncRoot { get { return this; } } public void AddAll(IDictionary dictionary) { foreach(DictionaryEntry entry in dictionary) { Add(entry.Key, entry.Value); } } private int IndexOf(object key) { for(int i = 0; i < objectList.Count; i++) { if (((DictionaryEntry) objectList[i]).Key.Equals(key)) { return i; } } return -1; } /// <summary> /// Remove the least recently used entry (the last one in the list) /// </summary> private void RemoveLRU() { Object key = ((DictionaryEntry) objectList[objectList.Count - 1]).Key; objectTable.Remove(key); objectList.RemoveAt(objectList.Count - 1); } private void MoveToMRU(Object key) { Int32 i = IndexOf(key); // only move if found and not already first if (i > 0) { Object value = objectList[i]; objectList.RemoveAt(i); objectList.Insert(0, value); } } // Returns a thread-safe wrapper for a LRUMap. // public static LRUMap Synchronized(LRUMap table) { if (table == null) { throw new ArgumentNullException("table"); } return new SyncLRUMap(table); } // Synchronized wrapper for LRUMap [Serializable()] private class SyncLRUMap : LRUMap, IDictionary, IEnumerable { protected LRUMap _table; internal SyncLRUMap(LRUMap table) { _table = table; } // internal SyncLRUMap(SerializationInfo Info, StreamingContext context) : base (Info, context) { // _table = (LRUMap)Info.GetValue("ParentTable", typeof(LRUMap)); // if (_table==null) { // throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); // } // } /*================================GetObjectData================================= **Action: Return a serialization Info containing a reference to _table. We need ** to implement this because our parent HT does and we don't want to actually ** serialize all of it's values (just a reference to the table, which will then ** be serialized separately.) **Returns: void **Arguments: Info -- the SerializationInfo into which to store the data. ** context -- the StreamingContext for the current serialization (ignored) **Exceptions: ArgumentNullException if Info is null. ==============================================================================*/ // public override void GetObjectData(SerializationInfo Info, StreamingContext context) { // if (Info==null) { // throw new ArgumentNullException("Info"); // } // Info.AddValue("ParentTable", _table, typeof(Hashtable)); // } public override int Count { get { return _table.Count; } } public override bool IsReadOnly { get { return _table.IsReadOnly; } } public override bool IsFixedSize { get { return _table.IsFixedSize; } } public override bool IsSynchronized { get { return true; } } public override Object this[Object key] { get { return _table[key]; } set { lock(_table.SyncRoot) { _table[key] = value; } } } public override Object SyncRoot { get { return _table.SyncRoot; } } public override void Add(Object key, Object value) { lock(_table.SyncRoot) { _table.Add(key, value); } } public override void Clear() { lock(_table.SyncRoot) { _table.Clear(); } } public override bool Contains(Object key) { return _table.Contains(key); } // public override bool ContainsKey(Object key) { // return _table.ContainsKey(key); // } // public override bool ContainsValue(Object key) { // return _table.ContainsValue(key); // } public override void CopyTo(Array array, int arrayIndex) { _table.CopyTo(array, arrayIndex); } IDictionaryEnumerator IDictionary.GetEnumerator() { return ((IDictionary) _table).GetEnumerator(); } // protected override int GetHash(Object key) { // return _table.GetHash(key); // } // protected override bool KeyEquals(Object item, Object key) { // return _table.KeyEquals(item, key); // } public override ICollection Keys { get { lock(_table.SyncRoot) { return _table.Keys; } } } public override ICollection Values { get { lock(_table.SyncRoot) { return _table.Values; } } } public override void Remove(Object key) { lock(_table.SyncRoot) { _table.Remove(key); } } /*==============================OnDeserialization=============================== **Action: Does nothing. We have to implement this because our parent HT implements it, ** but it doesn't do anything meaningful. The real work will be done when we ** call OnDeserialization on our parent table. **Returns: void **Arguments: None **Exceptions: None ==============================================================================*/ // public override void OnDeserialization(Object sender) { // return; // } } } }
using UnityEngine; using UniverseEngine; using System.Collections.Generic; public class UniverseView : MonoBehaviour, IUniverseListener { public UniverseViewFactory universeFactory; public int MaxActivePlanetViews = 5; [HideInInspector] [System.NonSerialized] public AvatarView avatarView; [HideInInspector] [System.NonSerialized] public ShipView shipView; private Universe universe = new Universe(); private PlanetView[] planetViews = new PlanetView[Universe.MAX_THINGS]; private List<PlanetView> activePlanetViews = new List<PlanetView>(32); private List<UniverseObjectView> tilemapObjectViews = new List<UniverseObjectView>(32); private Mesh mesh1; private Mesh mesh2; private int frameCount; private Renderer rend; private Transform trans; private PlanetType[] planetTypes; private MeshFilter meshFilter; public Universe Universe { get { return universe; } } public void Awake() { rend = renderer; trans = transform; trans.localPosition = Vector3.zero; trans.localScale = Vector3.one; trans.localRotation = Quaternion.identity; renderer.sharedMaterial.mainTexture = SpriteMeshEngine.SpriteSheetManager.GetSpriteSheet("Planets").Texture; planetTypes = PlanetTypes.GetPlanetTypes(); meshFilter = GetComponent<MeshFilter>(); mesh1 = new Mesh(); mesh2 = new Mesh(); } public void Init(int seed) { CreateUniverse(seed); UpdateMesh(true); } private void CreateUniverse(int seed) { universe = new Universe(); universe.Init(seed, this); } public PlanetView GetPlanetView(TilemapCircle tilemapCircle) { if (tilemapCircle is Planet) return GetPlanetView(((Planet) tilemapCircle).ThingIndex); return null; } public bool ExistsPlanetView(TilemapCircle tilemapCircle) { if (tilemapCircle is Planet) return planetViews[((Planet) tilemapCircle).ThingIndex] != null; return false; } public PlanetView GetPlanetView(ushort thingIndex) { if (planetViews[thingIndex] != null) return planetViews[thingIndex]; if (activePlanetViews.Count >= MaxActivePlanetViews) universe.ReturnPlanet(activePlanetViews[0].Planet); Planet planet = universe.GetPlanet(thingIndex); if (planet == null) return null; PlanetView planetView = universeFactory.GetPlanet(planet.Height); planetView.InitPlanet(planet, this); activePlanetViews.Add(planetView); planetViews[thingIndex] = planetView; //Debug.Log(planetViews.Count); return planetView; } public void OnPlanetReturned(Planet planet) { planetViews[planet.ThingIndex] = null; for (int i = 0; i < activePlanetViews.Count; i++) { if (activePlanetViews[i].Planet == planet) { PlanetView planetView = activePlanetViews[i]; universeFactory.ReturnPlanet(planetView); activePlanetViews.RemoveAt(i); break; } } } public void OnUniverseObjectAdded(UniverseObject universeObject) { if (universeObject is UniverseEngine.Avatar) { avatarView = universeFactory.GetAvatar(); avatarView.Init((UniverseEngine.Avatar) universeObject, this); tilemapObjectViews.Add(avatarView); } else if (universeObject is UniverseEngine.Ship) { shipView = universeFactory.GetShip(); shipView.Init((UniverseEngine.Ship) universeObject, this); tilemapObjectViews.Add(shipView); } } /// <summary> /// Called by GameLogic /// </summary> public void UpdateUniverse(float deltaTime) { universe.UpdateUniverse(deltaTime); if (IsVisible()) { UEProfiler.BeginSample("UniverseView.UpdateMesh"); UpdateMesh(false); UEProfiler.EndSample(); } } public void SetVisible(bool visible) { rend.enabled = visible; } public bool IsVisible() { return rend.enabled; } private void UpdateMesh(bool firstTime) { Thing[] things = universe.Things; ThingPosition[] thingsPositions = universe.ThingsPositions; ushort[] thingsToRender = universe.ThingsToRender; ushort thingsToRenderAmount = universe.ThingsToRenderAmount; int vertexCount = thingsToRenderAmount * 4; int triangleCount = thingsToRenderAmount * 6; Vector3[] vertices = DataPools.poolVector3.GetArray(vertexCount); int vertexOffset = 0; //Update all positions for (int i = 0; i < thingsToRenderAmount; i++) { ushort thingIndex = thingsToRender[i]; ThingPosition position = thingsPositions[thingIndex]; vertices[vertexOffset + 0].x = position.x - position.radius; vertices[vertexOffset + 0].y = position.y - position.radius; vertices[vertexOffset + 1].x = position.x - position.radius; vertices[vertexOffset + 1].y = position.y + position.radius; vertices[vertexOffset + 2].x = position.x + position.radius; vertices[vertexOffset + 2].y = position.y + position.radius; vertices[vertexOffset + 3].x = position.x + position.radius; vertices[vertexOffset + 3].y = position.y - position.radius; vertexOffset += 4; } //Don't draw preview of active planets (except the first time that everything is draw) if (!firstTime) { for (int i = 0; i < activePlanetViews.Count; i++) { ushort thingIndex = activePlanetViews[i].Planet.ThingIndex; int thingsToRenderIndex = System.Array.BinarySearch(thingsToRender, 0, thingsToRenderAmount, thingIndex); if (thingsToRenderIndex >= 0) { vertexOffset = thingsToRenderIndex * 4; vertices[vertexOffset + 0].x = 0; vertices[vertexOffset + 0].y = 0; vertices[vertexOffset + 1].x = 0; vertices[vertexOffset + 1].y = 0; vertices[vertexOffset + 2].x = 0; vertices[vertexOffset + 2].y = 0; vertices[vertexOffset + 3].x = 0; vertices[vertexOffset + 3].y = 0; } } } if (firstTime) { //Update triangles and uvs only the first time that the mesh is updated int triangleOffset = 0; vertexOffset = 0; int[] triangles = DataPools.poolInt.GetArray(triangleCount); Vector2[] uvs = DataPools.poolVector2.GetArray(vertexCount); for (ushort i = 0; i < thingsToRenderAmount; i++) { Thing thing = things[thingsToRender[i]]; PlanetType planetType; if (thing.type == (ushort) ThingType.Sun) planetType = planetTypes[Mathf.Abs(thing.seed % 2) + 4]; //suns! else planetType = planetTypes[Mathf.Abs(thing.seed % 4)]; //planets! Rect planetUV = planetType.planetSprite.UV; uvs[vertexOffset + 0] = new Vector2(planetUV.xMin, planetUV.yMax); uvs[vertexOffset + 1] = new Vector2(planetUV.xMax, planetUV.yMax); uvs[vertexOffset + 2] = new Vector2(planetUV.xMax, planetUV.yMin); uvs[vertexOffset + 3] = new Vector2(planetUV.xMin, planetUV.yMin); triangles[triangleOffset + 0] = vertexOffset + 0; triangles[triangleOffset + 1] = vertexOffset + 1; triangles[triangleOffset + 2] = vertexOffset + 2; triangles[triangleOffset + 3] = vertexOffset + 2; triangles[triangleOffset + 4] = vertexOffset + 3; triangles[triangleOffset + 5] = vertexOffset + 0; triangleOffset += 6; vertexOffset += 4; } mesh1.vertices = vertices; mesh2.vertices = vertices; mesh1.triangles = triangles; mesh1.uv = uvs; mesh1.bounds = new Bounds(Vector3.zero, new Vector3(ushort.MaxValue * 2, ushort.MaxValue * 2, 0.0f)); mesh2.triangles = triangles; mesh2.uv = uvs; mesh2.bounds = new Bounds(Vector3.zero, new Vector3(ushort.MaxValue * 2, ushort.MaxValue * 2, 0.0f)); mesh1.Optimize(); mesh2.Optimize(); DataPools.poolInt.ReturnArray(triangles); DataPools.poolVector2.ReturnArray(uvs); } if ((frameCount % 2) == 0) { mesh1.vertices = vertices; meshFilter.sharedMesh = mesh1; } else { mesh2.vertices = vertices; meshFilter.sharedMesh = mesh2; } DataPools.poolVector3.ReturnArray(vertices); frameCount++; } }
//========================================================================= // Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved. // This product is protected by U.S. and international copyright // and intellectual property laws. Pivotal products are covered by // more patents listed at http://www.pivotal.io/patents. //======================================================================== using System; using System.Collections.Generic; using System.Collections; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using Region = Apache.Geode.Client.IRegion<Object, Object>; public class MyAppDomainResultCollector<TResult> : IResultCollector<TResult> { #region Private members private bool m_resultReady = false; ICollection<TResult> m_results = null; private int m_addResultCount = 0; private int m_getResultCount = 0; private int m_endResultCount = 0; #endregion public int GetAddResultCount() { return m_addResultCount; } public int GetGetResultCount() { return m_getResultCount; } public int GetEndResultCount() { return m_endResultCount; } public MyAppDomainResultCollector() { m_results = new List<TResult>(); } public void AddResult(TResult result) { Util.Log("MyAppDomainResultCollector " + result + " : " + result.GetType()); m_addResultCount++; m_results.Add(result); } public ICollection<TResult> GetResult() { return GetResult(TimeSpan.FromSeconds(50)); } public ICollection<TResult> GetResult(TimeSpan timeout) { m_getResultCount++; lock (this) { if (!m_resultReady) { if (timeout > TimeSpan.Zero) { if (!Monitor.Wait(this, timeout)) { throw new FunctionExecutionException("Timeout waiting for result."); } } else { throw new FunctionExecutionException("Results not ready."); } } } return m_results; } public void EndResults() { m_endResultCount++; lock (this) { m_resultReady = true; Monitor.Pulse(this); } } public void ClearResults(/*bool unused*/) { m_results.Clear(); m_addResultCount = 0; m_getResultCount = 0; m_endResultCount = 0; m_resultReady = false; } } [TestFixture] [Category("group3")] [Category("unicast_only")] [Category("generics")] public class ThinClientAppDomainFunctionExecutionTests : ThinClientRegionSteps { #region Private members private static string[] FunctionExecutionRegionNames = { "partition_region", "partition_region1" }; private static string poolName = "__TEST_POOL1__"; private static string serverGroup = "ServerGroup1"; private static string QERegionName = "partition_region"; private static string OnServerHAExceptionFunction = "OnServerHAExceptionFunction"; private static string OnServerHAShutdownFunction = "OnServerHAShutdownFunction"; #endregion protected override ClientBase[] GetClients() { return new ClientBase[] { }; } [TestFixtureSetUp] public override void InitTests() { Util.Log("InitTests: AppDomain: " + AppDomain.CurrentDomain.Id); CacheHelper.Init(); } [TearDown] public override void EndTest() { Util.Log("EndTest: AppDomain: " + AppDomain.CurrentDomain.Id); try { CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } finally { CacheHelper.StopJavaServers(); CacheHelper.StopJavaLocators(); } base.EndTest(); } public void createRegionAndAttachPool(string regionName, string poolName) { CacheHelper.CreateTCRegion_Pool<object, object>(regionName, true, true, null, null, poolName, false, serverGroup); } public void createPool(string name, string locators, string serverGroup, int redundancy, bool subscription, bool prSingleHop, bool threadLocal = false) { CacheHelper.CreatePool<object, object>(name, locators, serverGroup, redundancy, subscription, prSingleHop, threadLocal); } public void OnServerHAStepOne() { Region region = CacheHelper.GetVerifyRegion<object, object>(QERegionName); for (int i = 0; i < 34; i++) { region["KEY--" + i] = "VALUE--" + i; } object[] routingObj = new object[17]; ArrayList args1 = new ArrayList(); int j = 0; for (int i = 0; i < 34; i++) { if (i % 2 == 0) continue; routingObj[j] = "KEY--" + i; j++; } Util.Log("routingObj count= {0}.", routingObj.Length); for (int i = 0; i < routingObj.Length; i++) { Console.WriteLine("routingObj[{0}]={1}.", i, (string)routingObj[i]); args1.Add(routingObj[i]); } //test data independant function execution with result onServer Pool/*<TKey, TValue>*/ pool = CacheHelper.DCache.GetPoolManager().Find(poolName); Apache.Geode.Client.Execution<object> exc = FunctionService<object>.OnServer(pool); Assert.IsTrue(exc != null, "onServer Returned NULL"); IResultCollector<object> rc = exc.WithArgs<ArrayList>(args1).Execute(OnServerHAExceptionFunction, TimeSpan.FromSeconds(15)); ICollection<object> executeFunctionResult = rc.GetResult(); List<object> resultList = new List<object>(); Console.WriteLine("executeFunctionResult.Length = {0}", executeFunctionResult.Count); foreach (List<object> item in executeFunctionResult) { foreach (object item2 in item) { resultList.Add(item2); } } Util.Log("on region: result count= {0}.", resultList.Count); Assert.IsTrue(resultList.Count == 17, "result count check failed"); for (int i = 0; i < resultList.Count; i++) { Util.Log("on region:get:result[{0}]={1}.", i, (string)resultList[i]); Assert.IsTrue(((string)resultList[i]) != null, "onServer Returned NULL"); } rc = exc.WithArgs<ArrayList>(args1).Execute(OnServerHAShutdownFunction, TimeSpan.FromSeconds(15)); ICollection<object> executeFunctionResult1 = rc.GetResult(); List<object> resultList1 = new List<object>(); foreach (List<object> item in executeFunctionResult1) { foreach (object item2 in item) { resultList1.Add(item2); } } Util.Log("on region: result count= {0}.", resultList1.Count); Console.WriteLine("resultList1.Count = {0}", resultList1.Count); Assert.IsTrue(resultList1.Count == 17, "result count check failed"); for (int i = 0; i < resultList1.Count; i++) { Util.Log("on region:get:result[{0}]={1}.", i, (string)resultList1[i]); Assert.IsTrue(((string)resultList1[i]) != null, "onServer Returned NULL"); } // Bring down the region //region.LocalDestroyRegion(); } [Test] public void OnServerHAExecuteFunction() { Util.Log("OnServerHAExecuteFunction: AppDomain: " + AppDomain.CurrentDomain.Id); CacheHelper.SetupJavaServers(true, "func_cacheserver1_pool.xml", "func_cacheserver2_pool.xml", "func_cacheserver3_pool.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("Cacheserver 2 started."); CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1); Util.Log("Cacheserver 3 started."); createPool(poolName, CacheHelper.Locators, serverGroup, 1, true, true, /*threadLocal*/true); createRegionAndAttachPool(QERegionName, poolName); Util.Log("Client 1 (pool locator) regions created"); OnServerHAStepOne(); Close(); Util.Log("Client 1 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaServer(3); Util.Log("Cacheserver 3 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using GongSolutions.Shell.Interop; namespace GongSolutions.Shell { /// <summary> /// Provides support for displaying the context menu of a shell item. /// </summary> /// /// <remarks> /// <para> /// Use this class to display a context menu for a shell item, either /// as a popup menu, or as a main menu. /// </para> /// /// <para> /// To display a popup menu, simply call <see cref="ShowContextMenu"/> /// with the parent control and the position at which the menu should /// be shown. /// </para> /// /// <para> /// To display a shell context menu in a Form's main menu, call the /// <see cref="Populate"/> method to populate the menu. In addition, /// you must intercept a number of special messages that will be sent /// to the menu's parent form. To do this, you must override /// <see cref="Form.WndProc"/> like so: /// </para> /// /// <code> /// protected override void WndProc(ref Message m) { /// if ((m_ContextMenu == null) || (!m_ContextMenu.HandleMenuMessage(ref m))) { /// base.WndProc(ref m); /// } /// } /// </code> /// /// <para> /// Where m_ContextMenu is the <see cref="ShellContextMenu"/> being shown. /// </para> /// /// Standard menu commands can also be invoked from this class, for /// example <see cref="InvokeDelete"/> and <see cref="InvokeRename"/>. /// </remarks> public class ShellContextMenu { /// <summary> /// Initialises a new instance of the <see cref="ShellContextMenu"/> /// class. /// </summary> /// /// <param name="item"> /// The item to which the context menu should refer. /// </param> public ShellContextMenu(ShellItem item) { Initialize(new ShellItem[] { item }); } /// <summary> /// Initialises a new instance of the <see cref="ShellContextMenu"/> /// class. /// </summary> /// /// <param name="items"> /// The items to which the context menu should refer. /// </param> public ShellContextMenu(ShellItem[] items) { Initialize(items); } /// <summary> /// Handles context menu messages when the <see cref="ShellContextMenu"/> /// is displayed on a Form's main menu bar. /// </summary> /// /// <remarks> /// <para> /// To display a shell context menu in a Form's main menu, call the /// <see cref="Populate"/> method to populate the menu with the shell /// item's menu items. In addition, you must intercept a number of /// special messages that will be sent to the menu's parent form. To /// do this, you must override <see cref="Form.WndProc"/> like so: /// </para> /// /// <code> /// protected override void WndProc(ref Message m) { /// if ((m_ContextMenu == null) || (!m_ContextMenu.HandleMenuMessage(ref m))) { /// base.WndProc(ref m); /// } /// } /// </code> /// /// <para> /// Where m_ContextMenu is the <see cref="ShellContextMenu"/> being shown. /// </para> /// </remarks> /// /// <param name="m"> /// The message to handle. /// </param> /// /// <returns> /// <see langword="true"/> if the message was a Shell Context Menu /// message, <see langword="false"/> if not. If the method returns false, /// then the message should be passed down to the base class's /// <see cref="Form.WndProc"/> method. /// </returns> public bool HandleMenuMessage(ref Message m) { if ((m.Msg == (int)MSG.WM_COMMAND) && ((int)m.WParam >= m_CmdFirst)) { InvokeCommand((int)m.WParam - m_CmdFirst); return true; } else { if (m_ComInterface3 != null) { IntPtr result; if (m_ComInterface3.HandleMenuMsg2(m.Msg, m.WParam, m.LParam, out result) == HResult.S_OK) { m.Result = result; return true; } } else if (m_ComInterface2 != null) { if (m_ComInterface2.HandleMenuMsg(m.Msg, m.WParam, m.LParam) == HResult.S_OK) { m.Result = IntPtr.Zero; return true; } } } return false; } /// <summary> /// Invokes the Copy command on the shell item(s). /// </summary> public void InvokeCopy() { InvokeVerb("copy"); } /// <summary> /// Invokes the Copy command on the shell item(s). /// </summary> public void InvokeCut() { InvokeVerb("cut"); } /// <summary> /// Invokes the Delete command on the shell item(s). /// </summary> public void InvokeDelete() { try { InvokeVerb("delete"); } catch (COMException e) { // Ignore the exception raised when the user cancels // a delete operation. if (e.ErrorCode != unchecked((int)0x800704C7) && e.ErrorCode != unchecked((int)0x80270000)) { throw; } } } /// <summary> /// Invokes the Paste command on the shell item(s). /// </summary> public void InvokePaste() { InvokeVerb("paste"); } /// <summary> /// Invokes the Rename command on the shell item. /// </summary> public void InvokeRename() { InvokeVerb("rename"); } /// <summary> /// Invokes the specified verb on the shell item(s). /// </summary> public void InvokeVerb(string verb) { CMINVOKECOMMANDINFO invoke = new CMINVOKECOMMANDINFO(); invoke.cbSize = Marshal.SizeOf(invoke); invoke.lpVerb = verb; m_ComInterface.InvokeCommand(ref invoke); } /// <summary> /// Populates a <see cref="Menu"/> with the context menu items for /// a shell item. /// </summary> /// /// <remarks> /// If this method is being used to populate a Form's main menu /// then you need to call <see cref="HandleMenuMessage"/> in the /// Form's message handler. /// </remarks> /// /// <param name="menu"> /// The menu to populate. /// </param> public void Populate(Menu menu) { RemoveShellMenuItems(menu); m_ComInterface.QueryContextMenu(menu.Handle, 0, m_CmdFirst, int.MaxValue, CMF.EXPLORE); } /// <summary> /// Shows a context menu for a shell item. /// </summary> /// /// <param name="control"> /// The parent control. /// </param> /// /// <param name="pos"> /// The position on <paramref name="control"/> that the menu /// should be displayed at. /// </param> public void ShowContextMenu(Control control, Point pos) { using (ContextMenu menu = new ContextMenu()) { pos = control.PointToScreen(pos); Populate(menu); int command = User32.TrackPopupMenuEx(menu.Handle, TPM.TPM_RETURNCMD, pos.X, pos.Y, m_MessageWindow.Handle, IntPtr.Zero); if (command > 0) { InvokeCommand(command - m_CmdFirst); } } } /// <summary> /// Gets the underlying COM <see cref="IContextMenu"/> interface. /// </summary> public IContextMenu ComInterface { get { return m_ComInterface; } set { m_ComInterface = value; } } void Initialize(ShellItem[] items) { IntPtr[] pidls = new IntPtr[items.Length]; ShellItem parent = null; IntPtr result; for (int n = 0; n < items.Length; ++n) { pidls[n] = Shell32.ILFindLastID(items[n].Pidl); if (parent == null) { if (items[n] == ShellItem.Desktop) { parent = ShellItem.Desktop; } else { parent = items[n].Parent; } } else { if (items[n].Parent != parent) { throw new Exception("All shell items must have the same parent"); } } } parent.GetIShellFolder().GetUIObjectOf(IntPtr.Zero, (uint)pidls.Length, pidls, typeof(IContextMenu).GUID, 0, out result); m_ComInterface = (IContextMenu) Marshal.GetTypedObjectForIUnknown(result, typeof(IContextMenu)); m_ComInterface2 = m_ComInterface as IContextMenu2; m_ComInterface3 = m_ComInterface as IContextMenu3; m_MessageWindow = new MessageWindow(this); } void InvokeCommand(int index) { const int SW_SHOWNORMAL = 1; CMINVOKECOMMANDINFO_ByIndex invoke = new CMINVOKECOMMANDINFO_ByIndex(); invoke.cbSize = Marshal.SizeOf(invoke); invoke.iVerb = index; invoke.nShow = SW_SHOWNORMAL; m_ComInterface2.InvokeCommand(ref invoke); } void TagManagedMenuItems(Menu menu, int tag) { MENUINFO info = new MENUINFO(); info.cbSize = Marshal.SizeOf(info); info.fMask = MIM.MIM_MENUDATA; info.dwMenuData = tag; foreach (MenuItem item in menu.MenuItems) { User32.SetMenuInfo(item.Handle, ref info); } } void RemoveShellMenuItems(Menu menu) { const int tag = 0xAB; List<int> remove = new List<int>(); int count = User32.GetMenuItemCount(menu.Handle); MENUINFO menuInfo = new MENUINFO(); MENUITEMINFO itemInfo = new MENUITEMINFO(); menuInfo.cbSize = Marshal.SizeOf(menuInfo); menuInfo.fMask = MIM.MIM_MENUDATA; itemInfo.cbSize = Marshal.SizeOf(itemInfo); itemInfo.fMask = MIIM.MIIM_ID | MIIM.MIIM_SUBMENU; // First, tag the managed menu items with an arbitary // value (0xAB). TagManagedMenuItems(menu, tag); for (int n = 0; n < count; ++n) { User32.GetMenuItemInfo(menu.Handle, n, true, ref itemInfo); if (itemInfo.hSubMenu == IntPtr.Zero) { // If the item has no submenu we can't get the tag, so // check its ID to determine if it was added by the shell. if (itemInfo.wID >= m_CmdFirst) remove.Add(n); } else { User32.GetMenuInfo(itemInfo.hSubMenu, ref menuInfo); if (menuInfo.dwMenuData != tag) remove.Add(n); } } // Remove the unmanaged menu items. remove.Reverse(); foreach (int position in remove) { User32.DeleteMenu(menu.Handle, position, MF.MF_BYPOSITION); } } class MessageWindow : Control { public MessageWindow(ShellContextMenu parent) { m_Parent = parent; } protected override void WndProc(ref Message m) { if (!m_Parent.HandleMenuMessage(ref m)) { base.WndProc(ref m); } } ShellContextMenu m_Parent; } MessageWindow m_MessageWindow; IContextMenu m_ComInterface; IContextMenu2 m_ComInterface2; IContextMenu3 m_ComInterface3; const int m_CmdFirst = 0x8000; } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Build.Tasks.Xaml { using System; using System.Collections.Generic; using System.IO; using System.Xaml; using System.Xaml.Schema; using System.Xml; using System.Reflection; using System.Runtime; using System.Globalization; using Microsoft.Build.Utilities; using XamlBuildTask; using Microsoft.Build.Framework; internal class CompilationPass2TaskInternal : MarshalByRefObject { IList<string> applicationMarkup; IList<ITaskItem> references; IList<LogData> logData; IList<string> sourceCodeFiles; IList<string> generatedCodeFiles; XamlBuildTypeInspectionExtensionContext buildContextForExtensions; IDictionary<string, ITaskItem> applicationMarkupWithTypeName; public IList<string> ApplicationMarkup { get { if (this.applicationMarkup == null) { this.applicationMarkup = new List<string>(); } return this.applicationMarkup; } set { this.applicationMarkup = value; } } public string AssemblyName { get; set; } public TaskLoggingHelper BuildLogger { get; set; } public string LocalAssemblyReference { get; set; } public string RootNamespace { get; set; } public string MSBuildProjectDirectory { get; set; } public IList<LogData> LogData { get { if (this.logData == null) { this.logData = new List<LogData>(); } return this.logData; } } public IList<ITaskItem> References { get { if (this.references == null) { this.references = new List<ITaskItem>(); } return this.references; } set { this.references = value; } } public IList<string> SourceCodeFiles { get { if (this.sourceCodeFiles == null) { this.sourceCodeFiles = new List<string>(); } return this.sourceCodeFiles; } set { this.sourceCodeFiles = value; } } public IList<string> GeneratedCodeFiles { get { if (this.generatedCodeFiles == null) { this.generatedCodeFiles = new List<string>(); } return generatedCodeFiles; } } public IDictionary<string, ITaskItem> ApplicationMarkupWithTypeName { get { if (this.applicationMarkupWithTypeName == null) { this.applicationMarkupWithTypeName = new Dictionary<string, ITaskItem>(); } return applicationMarkupWithTypeName; } set { this.applicationMarkupWithTypeName = value; } } public string OutputPath { get; set; } public string Language { get; set; } public bool IsInProcessXamlMarkupCompile { get; set; } public IList<Tuple<string, string, string>> XamlBuildTaskTypeInspectionExtensionNames { get; set; } public IList<Tuple<AssemblyName, Assembly>> ReferencedAssemblies { get; set; } public bool SupportExtensions { get; set; } public XamlBuildTypeInspectionExtensionContext BuildContextForExtensions { get { if (this.buildContextForExtensions == null) { XamlBuildTypeInspectionExtensionContext local = new XamlBuildTypeInspectionExtensionContext(); local.AssemblyName = this.AssemblyName; local.IsInProcessXamlMarkupCompile = this.IsInProcessXamlMarkupCompile; local.Language = this.Language; local.OutputPath = this.OutputPath; local.RootNamespace = this.RootNamespace; local.AddSourceCodeFiles(this.SourceCodeFiles); local.LocalAssembly = this.LocalAssemblyReference; local.XamlBuildLogger = this.BuildLogger; local.AddReferences(XamlBuildTaskServices.GetReferences(this.references)); local.AddApplicationMarkupWithTypeName(this.ApplicationMarkupWithTypeName); this.buildContextForExtensions = local; } return this.buildContextForExtensions; } } public bool Execute() { try { if ((!this.SupportExtensions) && ((this.ApplicationMarkup == null) || this.ApplicationMarkup.Count == 0)) { return true; } else if (this.ApplicationMarkupWithTypeName == null || this.ApplicationMarkupWithTypeName.Count == 0) { return true; } IList<Assembly> loadedAssemblyList = null; if (this.References != null) { loadedAssemblyList = XamlBuildTaskServices.Load(this.References, false); } Assembly localAssembly = null; if (LocalAssemblyReference != null) { try { localAssembly = XamlBuildTaskServices.Load(LocalAssemblyReference); loadedAssemblyList.Add(localAssembly); } catch (FileNotFoundException e) { XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.FileName, 0, 0); return false; } } AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(XamlBuildTaskServices.ReflectionOnlyAssemblyResolve); XamlNsReplacingContext wxsc = new XamlNsReplacingContext(loadedAssemblyList, localAssembly.GetName().Name, this.AssemblyName); bool foundValidationErrors = false; if (!this.SupportExtensions) { foreach (string app in ApplicationMarkup) { try { if (!ProcessMarkupItem(app, wxsc, localAssembly)) { foundValidationErrors = true; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, app, 0, 0); return false; } } } else { foreach (ITaskItem app in this.ApplicationMarkupWithTypeName.Values) { string inputMarkupFile = app.ItemSpec; try { if (!ProcessMarkupItem(inputMarkupFile, wxsc, localAssembly)) { foundValidationErrors = true; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, inputMarkupFile, 0, 0); return false; } } if (!foundValidationErrors) { foundValidationErrors = !ExecuteExtensions(); if (!foundValidationErrors) { foundValidationErrors = this.BuildLogger.HasLoggedErrors; } } } return !foundValidationErrors; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // Log unknown errors that do not originate from the task. // Assumes that all known errors are logged when the exception is thrown. XamlBuildTaskServices.LogException(this.BuildLogger, e.Message); return false; } } bool ProcessMarkupItem(string markupItem, XamlNsReplacingContext wxsc, Assembly localAssembly) { XamlXmlReaderSettings settings = new XamlXmlReaderSettings() { LocalAssembly = localAssembly, ProvideLineInfo = true, AllowProtectedMembersOnRoot = true }; using (StreamReader streamReader = new StreamReader(markupItem)) { var xamlReader = new XamlXmlReader(XmlReader.Create(streamReader), wxsc, settings); ClassValidator validator = new ClassValidator(markupItem, localAssembly, this.RootNamespace); IList<LogData> validationErrors = null; if (validator.ValidateXaml(xamlReader, false, this.AssemblyName, out validationErrors)) { return true; } else { foreach (LogData logData in validationErrors) { this.LogData.Add(logData); } return false; } } } bool ExecuteExtensions() { ResolveAssemblyHelper resolveAssemblyHelper = new ResolveAssemblyHelper(XamlBuildTaskServices.GetReferences(this.References)); AppDomain.CurrentDomain.AssemblyResolve += resolveAssemblyHelper.ResolveLocalProjectReferences; bool extensionExecutedSuccessfully = true; try { IEnumerable<IXamlBuildTypeInspectionExtension> extensions = XamlBuildTaskServices.GetXamlBuildTaskExtensions<IXamlBuildTypeInspectionExtension>( this.XamlBuildTaskTypeInspectionExtensionNames, this.BuildLogger, this.MSBuildProjectDirectory); foreach (IXamlBuildTypeInspectionExtension extension in extensions) { try { extensionExecutedSuccessfully &= extension.Execute(this.BuildContextForExtensions); } catch (FileNotFoundException e) { throw FxTrace.Exception.AsError(new LoggableException(SR.ExceptionThrownInExtension(extension.ToString(), e.GetType().ToString(), SR.AssemblyNotFound(ResolveAssemblyHelper.FileNotFound)))); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw FxTrace.Exception.AsError(new LoggableException(SR.ExceptionThrownInExtension(extension.ToString(), e.GetType().ToString(), e.Message))); } } if (!this.BuildLogger.HasLoggedErrors && extensionExecutedSuccessfully) { foreach (string file in this.BuildContextForExtensions.GeneratedFiles) { this.GeneratedCodeFiles.Add(file); } } } finally { AppDomain.CurrentDomain.AssemblyResolve -= resolveAssemblyHelper.ResolveLocalProjectReferences; } return extensionExecutedSuccessfully; } } }
/* * 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.Timers; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Groups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")] public class GroupsModule : ISharedRegionModule, IGroupsModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IMessageTransferModule m_msgTransferModule = null; private IGroupsServicesConnector m_groupData = null; private IUserManagement m_UserManagement; // Configuration settings private bool m_groupsEnabled = false; private bool m_groupNoticesEnabled = true; private bool m_debugEnabled = false; private int m_levelGroupCreate = 0; #region Region Module interfaceBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false); if (!m_groupsEnabled) { return; } if (groupsConfig.GetString("Module", "Default") != Name) { m_groupsEnabled = false; return; } m_log.InfoFormat("[Groups]: Initializing {0}", this.Name); m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false); m_levelGroupCreate = groupsConfig.GetInt("LevelGroupCreate", 0); } } public void AddRegion(Scene scene) { if (m_groupsEnabled) { scene.RegisterModuleInterface<IGroupsModule>(this); scene.AddCommand( "Debug", this, "debug groups verbose", "debug groups verbose <true|false>", "This setting turns on very verbose groups debugging", HandleDebugGroupsVerbose); } } private void HandleDebugGroupsVerbose(object modules, string[] args) { if (args.Length < 4) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } bool verbose = false; if (!bool.TryParse(args[3], out verbose)) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } m_debugEnabled = verbose; MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled); } public void RegionLoaded(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMakeRootAgent += OnMakeRoot; scene.EventManager.OnMakeChildAgent += OnMakeChild; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; // The InstantMessageModule itself doesn't do this, // so lets see if things explode if we don't do it // scene.EventManager.OnClientClosed += OnClientClosed; if (m_groupData == null) { m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); // No Groups Service Connector, then nothing works... if (m_groupData == null) { m_groupsEnabled = false; m_log.Error("[Groups]: Could not get IGroupsServicesConnector"); RemoveRegion(scene); return; } } if (m_msgTransferModule == null) { m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_msgTransferModule == null) { m_log.Warn("[Groups]: Could not get MessageTransferModule"); } } if (m_UserManagement == null) { m_UserManagement = scene.RequestModuleInterface<IUserManagement>(); if (m_UserManagement == null) m_log.Warn("[Groups]: Could not get UserManagementModule"); } lock (m_sceneList) { m_sceneList.Add(scene); } } public void RemoveRegion(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnMakeRootAgent -= OnMakeRoot; scene.EventManager.OnMakeChildAgent -= OnMakeChild; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; lock (m_sceneList) { m_sceneList.Remove(scene); } } public void Close() { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.Debug("[Groups]: Shutting down Groups module."); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "Groups Module V2"; } } public void PostInitialise() { // NoOp } #endregion #region EventHandlers private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnRequestAvatarProperties += OnRequestAvatarProperties; } private void OnMakeRoot(ScenePresence sp) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); sp.ControllingClient.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; // Used for Notices and Group Invites/Accept/Reject sp.ControllingClient.OnInstantMessage += OnInstantMessage; // Send client their groups information. SendAgentGroupDataUpdate(sp.ControllingClient, sp.UUID); } private void OnMakeChild(ScenePresence sp) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); sp.ControllingClient.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; // Used for Notices and Group Invites/Accept/Reject sp.ControllingClient.OnInstantMessage -= OnInstantMessage; } private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); //GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetRequestingAgentID(remoteClient), avatarID).ToArray(); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } /* * This becomes very problematic in a shared module. In a shared module you may have more then one * reference to IClientAPI's, one for 0 or 1 root connections, and 0 or more child connections. * The OnClientClosed event does not provide anything to indicate which one of those should be closed * nor does it provide what scene it was from so that the specific reference can be looked up. * The InstantMessageModule.cs does not currently worry about unregistering the handles, * and it should be an issue, since it's the client that references us not the other way around * , so as long as we don't keep a reference to the client laying around, the client can still be GC'ed private void OnClientClosed(UUID AgentId) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_ActiveClients) { if (m_ActiveClients.ContainsKey(AgentId)) { IClientAPI client = m_ActiveClients[AgentId]; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnDirFindQuery -= OnDirFindQuery; client.OnInstantMessage -= OnInstantMessage; m_ActiveClients.Remove(AgentId); } else { if (m_debugEnabled) m_log.WarnFormat("[Groups]: Client closed that wasn't registered here."); } } } */ private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID activeGroupID = UUID.Zero; string activeGroupTitle = string.Empty; string activeGroupName = string.Empty; ulong activeGroupPowers = (ulong)GroupPowers.None; GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetRequestingAgentIDStr(remoteClient), dataForAgentID.ToString()); if (membership != null) { activeGroupID = membership.GroupID; activeGroupTitle = membership.GroupTitle; activeGroupPowers = membership.GroupPowers; } SendAgentDataUpdate(remoteClient, dataForAgentID, activeGroupID, activeGroupName, activeGroupPowers, activeGroupTitle); SendScenePresenceUpdate(dataForAgentID, activeGroupTitle); } private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null); if (group != null) { GroupName = group.GroupName; } else { GroupName = "Unknown"; } remoteClient.SendGroupNameReply(GroupID, GroupName); } private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); //m_log.DebugFormat("[Groups]: IM From {0} to {1} msg {2} type {3}", im.fromAgentID, im.toAgentID, im.message, (InstantMessageDialog)im.dialog); // Group invitations if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) { UUID inviteID = new UUID(im.imSessionID); GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID); if (inviteInfo == null) { if (m_debugEnabled) m_log.WarnFormat("[Groups]: Received an Invite IM for an invite that does not exist {0}.", inviteID); return; } //m_log.DebugFormat("[XXX]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID); UUID fromAgentID = new UUID(im.fromAgentID); UUID invitee = UUID.Zero; string tmp = string.Empty; Util.ParseUniversalUserIdentifier(inviteInfo.AgentID, out invitee, out tmp, out tmp, out tmp, out tmp); if ((inviteInfo != null) && (fromAgentID == invitee)) { // Accept if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) { //m_log.DebugFormat("[XXX]: Received an accept invite notice."); // and the sessionid is the role string reason = string.Empty; if (!m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), invitee.ToString(), inviteInfo.GroupID, inviteInfo.RoleID, string.Empty, out reason)) remoteClient.SendAgentAlertMessage("Unable to add you to the group: " + reason, false); else { GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = UUID.Zero.Guid; msg.toAgentID = invitee.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "Groups"; msg.message = string.Format("You have been added to the group."); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, invitee); UpdateAllClientsWithGroupInfo(invitee); } m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID); } // Reject if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: Received a reject invite notice."); m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID); m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID); } } } // Group notices if ((im.dialog == (byte)InstantMessageDialog.GroupNotice)) { if (!m_groupNoticesEnabled) { return; } UUID GroupID = new UUID(im.toAgentID); if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null) != null) { UUID NoticeID = UUID.Random(); string Subject = im.message.Substring(0, im.message.IndexOf('|')); string Message = im.message.Substring(Subject.Length + 1); InventoryItemBase item = null; bool hasAttachment = false; if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0) { hasAttachment = true; string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket); binBucket = binBucket.Remove(0, 14).Trim(); OSD binBucketOSD = OSDParser.DeserializeLLSDXml(binBucket); if (binBucketOSD is OSDMap) { OSDMap binBucketMap = (OSDMap)binBucketOSD; UUID itemID = binBucketMap["item_id"].AsUUID(); UUID ownerID = binBucketMap["owner_id"].AsUUID(); item = new InventoryItemBase(itemID, ownerID); item = m_sceneList[0].InventoryService.GetItem(item); } else m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType()); } if (m_groupData.AddGroupNotice(GetRequestingAgentIDStr(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, hasAttachment, (byte)(item == null ? 0 : item.AssetType), item == null ? null : item.Name, item == null ? UUID.Zero : item.ID, item == null ? UUID.Zero.ToString() : item.Owner.ToString())) { if (OnNewGroupNotice != null) { OnNewGroupNotice(GroupID, NoticeID); } // Send notice out to everyone that wants notices foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), GroupID)) { if (member.AcceptNotices) { // Build notice IIM, one of reach, because the sending may be async GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice); msg.toAgentID = member.AgentID.Guid; OutgoingInstantMessage(msg, member.AgentID); } } } } } if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted) { if (im.binaryBucket.Length < 16) // Invalid return; //// 16 bytes are the UUID. Maybe. // UUID folderID = new UUID(im.binaryBucket, 0); UUID noticeID = new UUID(im.imSessionID); GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteClient.AgentId.ToString(), noticeID); if (notice != null) { UUID giver = new UUID(im.toAgentID); string tmp = string.Empty; Util.ParseUniversalUserIdentifier(notice.noticeData.AttachmentOwnerID, out giver, out tmp, out tmp, out tmp, out tmp); m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId); string message; InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId, giver, notice.noticeData.AttachmentItemID, out message); if (itemCopy == null) { remoteClient.SendAgentAlertMessage(message, false); return; } remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0); } } // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presense server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue if ((im.dialog == 210)) { // This is sent from the region that the ejectee was ejected from // if it's being delivered here, then the ejectee is here // so we need to send local updates to the agent. UUID ejecteeID = new UUID(im.toAgentID); im.dialog = (byte)InstantMessageDialog.MessageFromAgent; OutgoingInstantMessage(im, ejecteeID); IClientAPI ejectee = GetActiveClient(ejecteeID); if (ejectee != null) { UUID groupID = new UUID(im.imSessionID); ejectee.SendAgentDropGroup(groupID); } } } private void OnGridInstantMessage(GridInstantMessage msg) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Trigger the above event handler OnInstantMessage(null, msg); // If a message from a group arrives here, it may need to be forwarded to a local client if (msg.fromGroup == true) { switch (msg.dialog) { case (byte)InstantMessageDialog.GroupInvitation: case (byte)InstantMessageDialog.GroupNotice: UUID toAgentID = new UUID(msg.toAgentID); IClientAPI localClient = GetActiveClient(toAgentID); if (localClient != null) { localClient.SendInstantMessage(msg); } break; } } } #endregion #region IGroupsModule Members public event NewGroupNotice OnNewGroupNotice; public GroupRecord GetGroupRecord(UUID GroupID) { return m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null); } public GroupRecord GetGroupRecord(string name) { return m_groupData.GetGroupRecord(UUID.Zero.ToString(), UUID.Zero, name); } public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); // Changing active group changes title, active powers, all kinds of things // anyone who is in any region that can see this client, should probably be // updated with new group info. At a minimum, they should get ScenePresence // updated with new title. UpdateAllClientsWithGroupInfo(remoteClient.AgentId); } /// <summary> /// Get the Role Titles for an Agent, for a specific group /// </summary> public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); List<GroupTitlesData> titles = new List<GroupTitlesData>(); foreach (GroupRolesData role in agentRoles) { GroupTitlesData title = new GroupTitlesData(); title.Name = role.Name; if (agentMembership != null) { title.Selected = agentMembership.ActiveRole == role.RoleID; } title.UUID = role.RoleID; titles.Add(title); } return titles; } public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat( "[Groups]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name); List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupMembersData member in data) { m_log.DebugFormat("[Groups]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner); } } return data; } public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentIDStr(remoteClient), groupID); return data; } public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentIDStr(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupRoleMembersData member in data) { m_log.DebugFormat("[Groups]: Member({0}) - Role({1})", member.MemberID, member.RoleID); } } return data; } public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupProfileData profile = new GroupProfileData(); // just to get the OwnerRole... ExtendedGroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), groupID, string.Empty); GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); if (groupInfo != null) { profile.AllowPublish = groupInfo.AllowPublish; profile.Charter = groupInfo.Charter; profile.FounderID = groupInfo.FounderID; profile.GroupID = groupID; profile.GroupMembershipCount = groupInfo.MemberCount; profile.GroupRolesCount = groupInfo.RoleCount; profile.InsigniaID = groupInfo.GroupPicture; profile.MaturePublish = groupInfo.MaturePublish; profile.MembershipFee = groupInfo.MembershipFee; profile.Money = 0; profile.Name = groupInfo.GroupName; profile.OpenEnrollment = groupInfo.OpenEnrollment; profile.OwnerRole = groupInfo.OwnerRoleID; profile.ShowInList = groupInfo.ShowInList; } if (memberInfo != null) { profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } return profile; } public GroupMembershipData[] GetMembershipData(UUID agentID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); return m_groupData.GetAgentGroupMemberships(UUID.Zero.ToString(), agentID.ToString()).ToArray(); } public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) { if (m_debugEnabled) m_log.DebugFormat( "[Groups]: {0} called with groupID={1}, agentID={2}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID); return m_groupData.GetAgentGroupMembership(UUID.Zero.ToString(), agentID.ToString(), groupID); } public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Note: Permissions checking for modification rights is handled by the Groups Server/Service string reason = string.Empty; if (!m_groupData.UpdateGroup(GetRequestingAgentIDStr(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, out reason)) remoteClient.SendAgentAlertMessage(reason, false); } public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) { // Note: Permissions checking for modification rights is handled by the Groups Server/Service if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.UpdateMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, acceptNotices, listInProfile); } public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called in {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Scene.RegionInfo.RegionName); if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), UUID.Zero, name) != null) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; } // check user level ScenePresence avatar = null; Scene scene = (Scene)remoteClient.Scene; scene.TryGetScenePresence(remoteClient.AgentId, out avatar); if (avatar != null) { if (avatar.UserLevel < m_levelGroupCreate) { remoteClient.SendCreateGroupReply(UUID.Zero, false, String.Format("Insufficient permissions to create a group. Requires level {0}", m_levelGroupCreate)); return UUID.Zero; } } // check funds // is there is a money module present ? IMoneyModule money = scene.RequestModuleInterface<IMoneyModule>(); if (money != null) { // do the transaction, that is if the agent has got sufficient funds if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "Insufficient funds to create a group."); return UUID.Zero; } } string reason = string.Empty; UUID groupID = m_groupData.CreateGroup(remoteClient.AgentId, name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, remoteClient.AgentId, out reason); if (groupID != UUID.Zero) { if (money != null) money.ApplyCharge(remoteClient.AgentId, money.GroupCreationCharge, MoneyTransactionType.GroupCreate); remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly"); // Update the founder with new group information. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } else remoteClient.SendCreateGroupReply(groupID, false, reason); return groupID; } public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // ToDo: check if agent is a member of group and is allowed to see notices? List<ExtendedGroupNoticeData> notices = m_groupData.GetGroupNotices(GetRequestingAgentIDStr(remoteClient), groupID); List<GroupNoticeData> os_notices = new List<GroupNoticeData>(); foreach (ExtendedGroupNoticeData n in notices) { GroupNoticeData osn = n.ToGroupNoticeData(); os_notices.Add(osn); } return os_notices.ToArray(); } /// <summary> /// Get the title of the agent's current role. /// </summary> public string GetGroupTitle(UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero.ToString(), avatarID.ToString()); if (membership != null) { return membership.GroupTitle; } return string.Empty; } /// <summary> /// Change the current Active Group Role for Agent /// </summary> public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroupRole(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, titleRoleID); // TODO: Not sure what all is needed here, but if the active group role change is for the group // the client currently has set active, then we need to do a scene presence update too // if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID) UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient)); } public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Security Checks are handled in the Groups Service. switch ((OpenMetaverse.GroupRoleUpdate)updateType) { case OpenMetaverse.GroupRoleUpdate.Create: string reason = string.Empty; if (!m_groupData.AddGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, UUID.Random(), name, description, title, powers, out reason)) remoteClient.SendAgentAlertMessage("Unable to create role: " + reason, false); break; case OpenMetaverse.GroupRoleUpdate.Delete: m_groupData.RemoveGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, roleID); break; case OpenMetaverse.GroupRoleUpdate.UpdateAll: case OpenMetaverse.GroupRoleUpdate.UpdateData: case OpenMetaverse.GroupRoleUpdate.UpdatePowers: if (m_debugEnabled) { GroupPowers gp = (GroupPowers)powers; m_log.DebugFormat("[Groups]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString()); } m_groupData.UpdateGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, roleID, name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.NoUpdate: default: // No Op break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check switch (changes) { case 0: // Add m_groupData.AddAgentToGroupRole(GetRequestingAgentIDStr(remoteClient), memberID.ToString(), groupID, roleID); break; case 1: // Remove m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentIDStr(remoteClient), memberID.ToString(), groupID, roleID); break; default: m_log.ErrorFormat("[Groups]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called for notice {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupNoticeID); GridInstantMessage msg = CreateGroupNoticeIM(remoteClient.AgentId, groupNoticeID, (byte)InstantMessageDialog.GroupNoticeRequested); OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient)); } public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GridInstantMessage msg = new GridInstantMessage(); byte[] bucket; msg.imSessionID = groupNoticeID.Guid; msg.toAgentID = agentID.Guid; msg.dialog = dialog; // msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupNotice; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID.ToString(), groupNoticeID); if (info != null) { msg.fromAgentID = info.GroupID.Guid; msg.timestamp = info.noticeData.Timestamp; msg.fromAgentName = info.noticeData.FromName; msg.message = info.noticeData.Subject + "|" + info.Message; if (info.noticeData.HasAttachment) { byte[] name = System.Text.Encoding.UTF8.GetBytes(info.noticeData.AttachmentName); bucket = new byte[19 + name.Length]; bucket[0] = 1; // has attachment? bucket[1] = info.noticeData.AttachmentType; // attachment type name.CopyTo(bucket, 18); } else { bucket = new byte[19]; bucket[0] = 0; // Has att? bucket[1] = 0; // type bucket[18] = 0; // null terminated } info.GroupID.ToBytes(bucket, 2); msg.binaryBucket = bucket; } else { m_log.DebugFormat("[Groups]: Group Notice {0} not found, composing empty message.", groupNoticeID); msg.fromAgentID = UUID.Zero.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); ; msg.fromAgentName = string.Empty; msg.message = string.Empty; msg.binaryBucket = new byte[0]; } return msg; } public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Send agent information about his groups SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string reason = string.Empty; // Should check to see if OpenEnrollment, or if there's an outstanding invitation if (m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, UUID.Zero, string.Empty, out reason)) { remoteClient.SendJoinGroupReply(groupID, true); // Should this send updates to everyone in the group? SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); if (reason != string.Empty) // A warning remoteClient.SendAlertMessage("Warning: " + reason); } else remoteClient.SendJoinGroupReply(groupID, false); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID); remoteClient.SendLeaveGroupReply(groupID, true); remoteClient.SendAgentDropGroup(groupID); // SL sends out notifcations to the group messaging session that the person has left // Should this also update everyone who is in the group? SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) { EjectGroupMember(remoteClient, GetRequestingAgentID(remoteClient), groupID, ejecteeID); } public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID ejecteeID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check? m_groupData.RemoveAgentFromGroup(agentID.ToString(), ejecteeID.ToString(), groupID); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; remoteClient.SendEjectGroupMemberReply(agentID, groupID, true); } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; client.SendEjectGroupMemberReply(agentID, groupID, true); } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount acc = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (acc != null) { agentName = acc.FirstName + " " + acc.LastName; } else { agentName = "Unknown member"; } } } GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null); UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID); if ((groupInfo == null) || (account == null)) { return; } // Send Message to Ejectee GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; // msg.fromAgentID = info.GroupID; msg.toAgentID = ejecteeID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, ejecteeID); // Message to ejector // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presense server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; msg.toAgentID = agentID.Guid; msg.timestamp = 0; msg.fromAgentName = agentName; if (account != null) { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, account.FirstName + " " + account.LastName); } else { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, "Unknown member"); } msg.dialog = (byte)210; //interop msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, agentID); // SL sends out messages to everyone in the group // Who all should receive updates and what should they be updated with? UpdateAllClientsWithGroupInfo(ejecteeID); } public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID) { InviteGroup(remoteClient, GetRequestingAgentID(remoteClient), groupID, invitedAgentID, roleID); } public void InviteGroup(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID invitedAgentID, UUID roleID) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string agentName = m_UserManagement.GetUserName(agentID); RegionInfo regionInfo = m_sceneList[0].RegionInfo; GroupRecord group = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null); if (group == null) { m_log.DebugFormat("[Groups]: No such group {0}", groupID); return; } // Todo: Security check, probably also want to send some kind of notification UUID InviteID = UUID.Random(); if (m_groupData.AddAgentToGroupInvite(agentID.ToString(), InviteID, groupID, roleID, invitedAgentID.ToString())) { if (m_msgTransferModule != null) { Guid inviteUUID = InviteID.Guid; GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = inviteUUID; // msg.fromAgentID = agentID.Guid; msg.fromAgentID = groupID.Guid; msg.toAgentID = invitedAgentID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("{0} has invited you to join a group called {1}. There is no cost to join this group.", agentName, group.GroupName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[20]; OutgoingInstantMessage(msg, invitedAgentID); } } } public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query) { return m_groupData.FindGroups(GetRequestingAgentIDStr(remoteClient), query); } #endregion #region Client/Update Tools /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null) { if (!sp.IsChildAgent) { return sp.ControllingClient; } else { child = sp.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none return child; } /// <summary> /// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'. /// </summary> private void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, UUID dataForAgentID, GroupMembershipData[] data) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // NPCs currently don't have a CAPs structure or event queues. There is a strong argument for conveying this information // to them anyway since it makes writing server-side bots a lot easier, but for now we don't do anything. if (remoteClient.SceneAgent.PresenceType == PresenceType.Npc) return; OSDArray AgentData = new OSDArray(1); OSDMap AgentDataMap = new OSDMap(1); AgentDataMap.Add("AgentID", OSD.FromUUID(dataForAgentID)); AgentData.Add(AgentDataMap); OSDArray GroupData = new OSDArray(data.Length); OSDArray NewGroupData = new OSDArray(data.Length); foreach (GroupMembershipData membership in data) { if (GetRequestingAgentID(remoteClient) != dataForAgentID) { if (!membership.ListInProfile) { // If we're sending group info to remoteclient about another agent, // filter out groups the other agent doesn't want to share. continue; } } OSDMap GroupDataMap = new OSDMap(6); OSDMap NewGroupDataMap = new OSDMap(1); GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID)); GroupDataMap.Add("GroupPowers", OSD.FromULong(membership.GroupPowers)); GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices)); GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture)); GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution)); GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName)); NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile)); GroupData.Add(GroupDataMap); NewGroupData.Add(NewGroupDataMap); } OSDMap llDataStruct = new OSDMap(3); llDataStruct.Add("AgentData", AgentData); llDataStruct.Add("GroupData", GroupData); llDataStruct.Add("NewGroupData", NewGroupData); if (m_debugEnabled) { m_log.InfoFormat("[Groups]: {0}", OSDParser.SerializeJsonString(llDataStruct)); } IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); if (queue != null) { queue.Enqueue(queue.BuildEvent("AgentGroupDataUpdate", llDataStruct), GetRequestingAgentID(remoteClient)); } } private void SendScenePresenceUpdate(UUID AgentID, string Title) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: Updating scene title for {0} with title: {1}", AgentID, Title); ScenePresence presence = null; foreach (Scene scene in m_sceneList) { presence = scene.GetScenePresence(AgentID); if (presence != null) { if (presence.Grouptitle != Title) { presence.Grouptitle = Title; if (! presence.IsChildAgent) presence.SendAvatarDataToAllAgents(); } } } } /// <summary> /// Send updates to all clients who might be interested in groups data for dataForClientID /// </summary> private void UpdateAllClientsWithGroupInfo(UUID dataForClientID) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Probably isn't nessesary to update every client in every scene. // Need to examine client updates and do only what's nessesary. lock (m_sceneList) { foreach (Scene scene in m_sceneList) { scene.ForEachClient(delegate(IClientAPI client) { SendAgentGroupDataUpdate(client, dataForClientID); }); } } } /// <summary> /// Update remoteClient with group information about dataForAgentID /// </summary> private void SendAgentGroupDataUpdate(IClientAPI remoteClient, UUID dataForAgentID) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff OnAgentDataUpdateRequest(remoteClient, dataForAgentID, UUID.Zero); // Need to send a group membership update to the client // UDP version doesn't seem to behave nicely. But we're going to send it out here // with an empty group membership to hopefully remove groups being displayed due // to the core Groups Stub //remoteClient.SendGroupMembership(new GroupMembershipData[0]); GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, dataForAgentID); SendGroupMembershipInfoViaCaps(remoteClient, dataForAgentID, membershipArray); //remoteClient.SendAvatarGroupsReply(dataForAgentID, membershipArray); if (remoteClient.AgentId == dataForAgentID) remoteClient.RefreshGroupMembership(); } /// <summary> /// Get a list of groups memberships for the agent that are marked "ListInProfile" /// (unless that agent has a godLike aspect, in which case get all groups) /// </summary> /// <param name="dataForAgentID"></param> /// <returns></returns> private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID) { List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId.ToString(), dataForAgentID.ToString()); GroupMembershipData[] membershipArray; // cScene and property accessor 'isGod' are in support of the opertions to bypass 'hidden' group attributes for // those with a GodLike aspect. Scene cScene = (Scene)requestingClient.Scene; bool isGod = cScene.Permissions.IsGod(requestingClient.AgentId); if (isGod) { membershipArray = membershipData.ToArray(); } else { if (requestingClient.AgentId != dataForAgentID) { Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership) { return membership.ListInProfile; }; membershipArray = membershipData.FindAll(showInProfile).ToArray(); } else { membershipArray = membershipData.ToArray(); } } if (m_debugEnabled) { m_log.InfoFormat("[Groups]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); foreach (GroupMembershipData membership in membershipArray) { m_log.InfoFormat("[Groups]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers); } } return membershipArray; } private void SendAgentDataUpdate(IClientAPI remoteClient, UUID dataForAgentID, UUID activeGroupID, string activeGroupName, ulong activeGroupPowers, string activeGroupTitle) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff string firstname = "Unknown", lastname = "Unknown"; string name = m_UserManagement.GetUserName(dataForAgentID); if (!string.IsNullOrEmpty(name)) { string[] parts = name.Split(new char[] { ' ' }); if (parts.Length >= 2) { firstname = parts[0]; lastname = parts[1]; } } remoteClient.SendAgentDataUpdate(dataForAgentID, activeGroupID, firstname, lastname, activeGroupPowers, activeGroupName, activeGroupTitle); } #endregion #region IM Backed Processes private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); IClientAPI localClient = GetActiveClient(msgTo); if (localClient != null) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: MsgTo ({0}) is local, delivering directly", localClient.Name); localClient.SendInstantMessage(msg); } else if (m_msgTransferModule != null) { if (m_debugEnabled) m_log.InfoFormat("[Groups]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: Message Sent: {0}", success?"Succeeded":"Failed"); }); } } public void NotifyChange(UUID groupID) { // Notify all group members of a chnge in group roles and/or // permissions // } #endregion private string GetRequestingAgentIDStr(IClientAPI client) { return GetRequestingAgentID(client).ToString(); } private UUID GetRequestingAgentID(IClientAPI client) { UUID requestingAgentID = UUID.Zero; if (client != null) { requestingAgentID = client.AgentId; } return requestingAgentID; } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Scheme with colors support. /// </summary> [Serializable] public class ColorScheme : Scheme, IColorScheme { #region Fields private ColorCategoryCollection _categories; private float _opacity; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ColorScheme"/> class. /// </summary> public ColorScheme() { Configure(); } /// <summary> /// Initializes a new instance of the <see cref="ColorScheme"/> class using a predefined color scheme and the minimum and maximum specified /// from the raster itself. /// </summary> /// <param name="schemeType">The predefined scheme to use.</param> /// <param name="raster">The raster to obtain the minimum and maximum settings from.</param> public ColorScheme(ColorSchemeType schemeType, IRaster raster) { Configure(); ApplyScheme(schemeType, raster); } /// <summary> /// Initializes a new instance of the <see cref="ColorScheme"/> class, applying the specified color scheme, and using the minimum and maximum values indicated. /// </summary> /// <param name="schemeType">The predefined color scheme.</param> /// <param name="min">The minimum.</param> /// <param name="max">The maximum.</param> public ColorScheme(ColorSchemeType schemeType, double min, double max) { Configure(); ApplyScheme(schemeType, min, max); } #endregion #region Properties /// <summary> /// Gets or sets the raster categories. /// </summary> [Serialize("Categories")] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ColorCategoryCollection Categories { get { return _categories; } set { if (_categories != null) _categories.Scheme = null; _categories = value; if (_categories != null) _categories.Scheme = this; } } /// <summary> /// Gets or sets the raster editor settings associated with this scheme. /// </summary> [Serialize("EditorSettings")] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new RasterEditorSettings EditorSettings { get { return base.EditorSettings as RasterEditorSettings; } set { base.EditorSettings = value; } } /// <summary> /// Gets or sets the floating point value for the opacity. /// </summary> [Serialize("Opacity")] public float Opacity { get { return _opacity; } set { _opacity = value; } } #endregion #region Methods /// <summary> /// Adds the specified category. /// </summary> /// <param name="category">Category that gets added.</param> public override void AddCategory(ICategory category) { IColorCategory cc = category as IColorCategory; if (cc != null) _categories.Add(cc); } /// <summary> /// Applies the specified color scheme and uses the specified raster to define the /// minimum and maximum to use for the scheme. /// </summary> /// <param name="schemeType">Color scheme that gets applied.</param> /// <param name="raster">Raster that is used to define the minimum and maximum for the scheme.</param> public void ApplyScheme(ColorSchemeType schemeType, IRaster raster) { double min, max; if (!raster.IsInRam) { GetValues(raster); min = Statistics.Minimum; max = Statistics.Maximum; } else { min = raster.Minimum; max = raster.Maximum; } ApplyScheme(schemeType, min, max); } /// <summary> /// Applies the specified color scheme and uses the specified raster to define the /// minimum and maximum to use for the scheme. /// </summary> /// <param name="schemeType">ColorSchemeType.</param> /// <param name="min">THe minimum value to use for the scheme.</param> /// <param name="max">THe maximum value to use for the scheme.</param> public void ApplyScheme(ColorSchemeType schemeType, double min, double max) { if (Categories == null) { Categories = new ColorCategoryCollection(this); } else { Categories.Clear(); } IColorCategory eqCat = null, low = null, high = null; if (min == max) { // Create one category eqCat = new ColorCategory(min, max) { Range = { MaxIsInclusive = true, MinIsInclusive = true } }; eqCat.ApplyMinMax(EditorSettings); Categories.Add(eqCat); } else { // Create two categories low = new ColorCategory(min, (min + max) / 2) { Range = { MaxIsInclusive = true } }; high = new ColorCategory((min + max) / 2, max) { Range = { MaxIsInclusive = true } }; low.ApplyMinMax(EditorSettings); high.ApplyMinMax(EditorSettings); Categories.Add(low); Categories.Add(high); } Color lowColor, midColor, highColor; int alpha = Utils.ByteRange(Convert.ToInt32(_opacity * 255F)); switch (schemeType) { case ColorSchemeType.SummerMountains: lowColor = Color.FromArgb(alpha, 10, 100, 10); midColor = Color.FromArgb(alpha, 153, 125, 25); highColor = Color.FromArgb(alpha, 255, 255, 255); break; case ColorSchemeType.FallLeaves: lowColor = Color.FromArgb(alpha, 10, 100, 10); midColor = Color.FromArgb(alpha, 199, 130, 61); highColor = Color.FromArgb(alpha, 241, 220, 133); break; case ColorSchemeType.Desert: lowColor = Color.FromArgb(alpha, 211, 206, 97); midColor = Color.FromArgb(alpha, 139, 120, 112); highColor = Color.FromArgb(alpha, 255, 255, 255); break; case ColorSchemeType.Glaciers: lowColor = Color.FromArgb(alpha, 105, 171, 224); midColor = Color.FromArgb(alpha, 162, 234, 240); highColor = Color.FromArgb(alpha, 255, 255, 255); break; case ColorSchemeType.Meadow: lowColor = Color.FromArgb(alpha, 68, 128, 71); midColor = Color.FromArgb(alpha, 43, 91, 30); highColor = Color.FromArgb(alpha, 167, 220, 168); break; case ColorSchemeType.ValleyFires: lowColor = Color.FromArgb(alpha, 164, 0, 0); midColor = Color.FromArgb(alpha, 255, 128, 64); highColor = Color.FromArgb(alpha, 255, 255, 191); break; case ColorSchemeType.DeadSea: lowColor = Color.FromArgb(alpha, 51, 137, 208); midColor = Color.FromArgb(alpha, 226, 227, 166); highColor = Color.FromArgb(alpha, 151, 146, 117); break; case ColorSchemeType.Highway: lowColor = Color.FromArgb(alpha, 51, 137, 208); midColor = Color.FromArgb(alpha, 214, 207, 124); highColor = Color.FromArgb(alpha, 54, 152, 69); break; default: lowColor = midColor = highColor = Color.Transparent; break; } if (eqCat != null) { eqCat.LowColor = eqCat.HighColor = lowColor; } else { Debug.Assert(low != null, "low may not be null"); Debug.Assert(high != null, "high may not be null"); low.LowColor = lowColor; low.HighColor = midColor; high.LowColor = midColor; high.HighColor = highColor; } OnItemChanged(this); } /// <summary> /// Clears the categories. /// </summary> public override void ClearCategories() { _categories.Clear(); } /// <summary> /// Creates the categories for this scheme based on statistics and values /// sampled from the specified raster. /// </summary> /// <param name="raster">The raster to use when creating categories.</param> public void CreateCategories(IRaster raster) { GetValues(raster); CreateBreakCategories(); OnItemChanged(this); } /// <summary> /// Creates the category using a random fill color. /// </summary> /// <param name="fillColor">The base color to use for creating the category.</param> /// <param name="size">For points this is the larger dimension, for lines this is the largest width.</param> /// <returns>A new IFeatureCategory that matches the type of this scheme.</returns> public override ICategory CreateNewCategory(Color fillColor, double size) { return new ColorCategory(null, null, fillColor, fillColor); } /// <summary> /// Uses the settings on this scheme to create a random category. /// </summary> /// <returns>A new IFeatureCategory.</returns> public override ICategory CreateRandomCategory() { Random rnd = new Random(DateTime.Now.Millisecond); return CreateNewCategory(CreateRandomColor(rnd), 20); } /// <summary> /// Attempts to decrease the index value of the specified category, and returns /// true if the move was successfull. /// </summary> /// <param name="category">The category to decrease the index of.</param> /// <returns>True, if the move was successfull.</returns> public override bool DecreaseCategoryIndex(ICategory category) { IColorCategory cc = category as IColorCategory; return cc != null && _categories.DecreaseIndex(cc); } /// <summary> /// Draws the category in the specified location. /// </summary> /// <param name="index">Index of the category that gets drawn.</param> /// <param name="g">graphics object used for drawing.</param> /// <param name="bounds">Rectangle to draw the category to.</param> public override void DrawCategory(int index, Graphics g, Rectangle bounds) { _categories[index].LegendSymbolPainted(g, bounds); } /// <summary> /// Gets the values from the raster. If MaxSampleCount is less than the /// number of cells, then it randomly samples the raster with MaxSampleCount /// values. Otherwise it gets all the values in the raster. /// </summary> /// <param name="raster">The raster to sample.</param> public void GetValues(IRaster raster) { Values = raster.GetRandomValues(EditorSettings.MaxSampleCount); var keepers = Values.Where(val => val != raster.NoDataValue).ToList(); Values = keepers; Statistics.Calculate(Values); } /// <summary> /// Attempts to increase the position of the specified category, and returns true /// if the index increase was successful. /// </summary> /// <param name="category">The category to increase the position of.</param> /// <returns>Boolean, true if the item's position was increased.</returns> public override bool IncreaseCategoryIndex(ICategory category) { IColorCategory cc = category as IColorCategory; return cc != null && _categories.IncreaseIndex(cc); } /// <summary> /// Inserts the item at the specified index. /// </summary> /// <param name="index">Index where the category gets inserted.</param> /// <param name="category">Category that gets inserted.</param> public override void InsertCategory(int index, ICategory category) { IColorCategory cc = category as IColorCategory; if (cc != null) _categories.Insert(index, cc); } /// <summary> /// Removes the specified category. /// </summary> /// <param name="category">Category that gets removed.</param> public override void RemoveCategory(ICategory category) { IColorCategory cc = category as IColorCategory; if (cc != null) _categories.Remove(cc); } /// <summary> /// Allows the ChangeItem event to get passed on when changes are made. /// </summary> public override void ResumeEvents() { _categories.ResumeEvents(); } /// <summary> /// Suspends the change item event from firing as the list is being changed. /// </summary> public override void SuspendEvents() { _categories.SuspendEvents(); } /// <summary> /// Occurs when setting the parent item and updates the parent item pointers. /// </summary> /// <param name="value">The parent item.</param> protected override void OnSetParentItem(ILegendItem value) { base.OnSetParentItem(value); _categories.UpdateItemParentPointers(); } private void Configure() { _categories = new ColorCategoryCollection(this); _opacity = 1; EditorSettings = new RasterEditorSettings(); } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Contoso.Branding.ThemesWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { using System; using System.Globalization; using System.Text; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] [Serializable] [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.Versioning.NonVersionable] // This only applies to field layout public struct Guid : IFormattable, IComparable , IComparable<Guid>, IEquatable<Guid> { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid(byte[] b) { if (b==null) throw new ArgumentNullException(nameof(b)); if (b.Length != 16) throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"), nameof(b)); Contract.EndContractBlock(); _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)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(Environment.GetResourceString("Arg_GuidArrayCtor", "8"), nameof(d)); Contract.EndContractBlock(); _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; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal object m_failureMessageFormatArgument; internal string m_failureArgumentName; internal Exception m_innerException; internal void Init(GuidParseThrowStyle canThrow) { parsedGuid = Guid.Empty; throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { m_failure = ParseFailureKind.NativeException; m_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) { Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; m_failureArgumentName = failureArgumentName; m_innerException = innerException; if (throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.FormatWithInnerException: return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.NativeException: return m_innerException; default: Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("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)); } Contract.EndContractBlock(); this = Guid.Empty; GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g, GuidStyles.Any, ref result)) { this = result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(String input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Contract.EndContractBlock(); 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) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } public static Guid ParseExact(String input, String format) { if (input == null) throw new ArgumentNullException(nameof(input)); if (format == null) throw new ArgumentNullException(nameof(format)); if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { throw new FormatException(Environment.GetResourceString("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 (format == null || format.Length != 1) { result = Guid.Empty; return false; } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { // invalid guid format specification result = Guid.Empty; return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result) { if (g == null) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } String guidString = g.Trim(); //Remove Whitespace if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } // Check for dashes bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0); if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, "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, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, "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, "Format_GuidUnrecognized"); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, "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, "Format_GuidUnrecognized", null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, "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(String guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if(String.IsNullOrEmpty(guidString) || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace"); return false; } // Check for '0x' if(!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, "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, "Format_GuidComma"); return false; } if (!StringToInt(guidString.Substring(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, "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, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(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, "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, "Format_GuidComma"); return false; } // Read in the number if (!StringToShort(guidString.Substring(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, "Format_GuidBrace"); return false; } // Prepare for loop numLen++; byte[] bytes = new byte[8]; for(int i = 0; i < 8; i++) { // Check for '0x' if(!IsHexPrefix(guidString, numStart+numLen+1)) { result.SetFailure(ParseFailureKind.Format, "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, "Format_GuidComma"); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if(numLen <= 0) { result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber"); return false; } } // Read in the number int signedNumber; if (!StringToInt(guidString.Substring(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, "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, "Format_GuidEndBrace"); return false; } // Check if we have extra characters at the end if( numStart+numLen+1 != guidString.Length -1) { result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd"); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) { int startPos=0; int temp; long templ; int currentPos = 0; if(guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, "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.ToUpper(ch, CultureInfo.InvariantCulture); if(upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Substring(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, "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(String 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, "Format_GuidInvLen"); return false; } startPos=1; } else if (guidString[0]=='(') { if (guidString.Length!=38 || guidString[37]!=')') { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } startPos=1; } else if(guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen"); return false; } if (guidString[8+startPos] != '-' || guidString[13+startPos] != '-' || guidString[18+startPos] != '-' || guidString[23+startPos] != '-') { result.SetFailure(ParseFailureKind.Format, "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, "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; } // // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines; [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { return StringToShort(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { return StringToInt(str, null, requiredLength, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult); } } [System.Security.SecurityCritical] private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = (parsePos == null) ? 0 : (*parsePos); try { result = ParseNumbers.StringToInt(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("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 != null && (*parsePos) - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar"); return false; } return true; } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) { return StringToLong(str, null, flags, out result, ref parseResult); } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { fixed(int * ppos = &parsePos) { return StringToLong(str, ppos, flags, out result, ref parseResult); } } [System.Security.SecuritySafeCritical] private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(Environment.GetResourceString("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 String EatAllWhitespace(String str) { int newLength = 0; char[] chArr = new char[str.Length]; char curChar; // Now get each char from str and if it is not whitespace add it to chArr for(int i = 0; i < str.Length; i++) { curChar = str[i]; if(!Char.IsWhiteSpace(curChar)) { chArr[newLength++] = curChar; } } // Return a new string based on chArr return new String(chArr, 0, newLength); } private static bool IsHexPrefix(String str, int i) { if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x')) return true; else return false; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } // Returns the guid in "registry" format. public override String ToString() { return ToString("D",null); } [System.Security.SecuritySafeCritical] public unsafe override int GetHashCode() { // Simply XOR all the bits of the GUID 32 bits at a time. fixed (int* ptr = &this._a) return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[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 if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } public bool Equals(Guid g) { // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } 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(Environment.GetResourceString("Arg_MustBeGuid"), nameof(value)); } Guid g = (Guid)value; if (g._a!=this._a) { return GetResult((uint)this._a, (uint)g._a); } if (g._b!=this._b) { return GetResult((uint)this._b, (uint)g._b); } if (g._c!=this._c) { return GetResult((uint)this._c, (uint)g._c); } if (g._d!=this._d) { return GetResult((uint)this._d, (uint)g._d); } if (g._e!=this._e) { return GetResult((uint)this._e, (uint)g._e); } if (g._f!=this._f) { return GetResult((uint)this._f, (uint)g._f); } if (g._g!=this._g) { return GetResult((uint)this._g, (uint)g._g); } if (g._h!=this._h) { return GetResult((uint)this._h, (uint)g._h); } if (g._i!=this._i) { return GetResult((uint)this._i, (uint)g._i); } if (g._j!=this._j) { return GetResult((uint)this._j, (uint)g._j); } if (g._k!=this._k) { return GetResult((uint)this._k, (uint)g._k); } return 0; } public int CompareTo(Guid value) { if (value._a!=this._a) { return GetResult((uint)this._a, (uint)value._a); } if (value._b!=this._b) { return GetResult((uint)this._b, (uint)value._b); } if (value._c!=this._c) { return GetResult((uint)this._c, (uint)value._c); } if (value._d!=this._d) { return GetResult((uint)this._d, (uint)value._d); } if (value._e!=this._e) { return GetResult((uint)this._e, (uint)value._e); } if (value._f!=this._f) { return GetResult((uint)this._f, (uint)value._f); } if (value._g!=this._g) { return GetResult((uint)this._g, (uint)value._g); } if (value._h!=this._h) { return GetResult((uint)this._h, (uint)value._h); } if (value._i!=this._i) { return GetResult((uint)this._i, (uint)value._i); } if (value._j!=this._j) { return GetResult((uint)this._j, (uint)value._j); } if (value._k!=this._k) { return GetResult((uint)this._k, (uint)value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements if(a._a != b._a) return false; if(a._b != b._b) return false; if(a._c != b._c) return false; if(a._d != b._d) return false; if(a._e != b._e) return false; if(a._f != b._f) return false; if(a._g != b._g) return false; if(a._h != b._h) return false; if(a._i != b._i) return false; if(a._j != b._j) return false; if(a._k != b._k) return false; return true; } public static bool operator !=(Guid a, Guid b) { return !(a == b); } // This will create a new guid. Since we've now decided that constructors should 0-init, // we need a method that allows users to create a guid. [System.Security.SecuritySafeCritical] // auto-generated public static Guid NewGuid() { // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some // uniqueness guarantees. It should also never return a known GUID, but it's unclear // how extensively it checks for known values. Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); Guid guid; Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1)); return guid; } public String ToString(String format) { return ToString(format, null); } private static char HexToChar(int a) { a = a & 0xf; return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b) { return HexsToChars(guidChars, offset, a, b, false); } [System.Security.SecurityCritical] unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex) { if (hex) { guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(a>>4); guidChars[offset++] = HexToChar(a); if (hex) { guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(b>>4); guidChars[offset++] = HexToChar(b); return offset; } // IFormattable interface // We currently ignore provider [System.Security.SecuritySafeCritical] public String ToString(String format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; string guidString; int offset = 0; bool dash = true; bool hex = false; if( format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { guidString = string.FastAllocateString(36); } else if (formatCh == 'N' || formatCh == 'n') { guidString = string.FastAllocateString(32); dash = false; } else if (formatCh == 'B' || formatCh == 'b') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[37] = '}'; } } } else if (formatCh == 'P' || formatCh == 'p') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '('; guidChars[37] = ')'; } } } else if (formatCh == 'X' || formatCh == 'x') { guidString = string.FastAllocateString(68); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[67] = '}'; } } dash = false; hex = true; } else { throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification")); } unsafe { fixed (char* guidChars = guidString) { if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); guidChars[offset++] = ','; guidChars[offset++] = '{'; offset = HexsToChars(guidChars, offset, _d, _e, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _f, _g, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _h, _i, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _j, _k, true); guidChars[offset++] = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _d, _e); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _f, _g); offset = HexsToChars(guidChars, offset, _h, _i); offset = HexsToChars(guidChars, offset, _j, _k); } } } return guidString; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration namespace _4PosBackOffice.NET { internal partial class frmBlockTestSelect : System.Windows.Forms.Form { string testType; int testID; private void loadLanguage() { //frmBlockTestSelect = No code [Block Test] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmBlockTestSelect.Caption = rsLang("LanguageLayoutLnk_Description"): frmBlockTestSelect.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080; //Search|Checked if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //cmdEdit = No Code [Load Selected Test] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then cmdEdit.Caption = rsLang("LanguageLayoutLnk_Description"): cmdEdit.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //cmdNew = No Code [Create a N&ew Test] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then cmdNew.Caption = rsLang("LanguageLayoutLnk_Description"): cmdNew.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmBlockTestSelect.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } public void loadTest(ref string tType, ref int tID) { doSearch(); loadLanguage(); ShowDialog(); tType = testType; tID = testID; } private void cmdEdit_Click(System.Object eventSender, System.EventArgs eventArgs) { if (this.lvImport.FocusedItem == null) { } else { testType = "load"; testID = Convert.ToInt32(Strings.Mid(this.lvImport.FocusedItem.Name, 2)); this.Close(); } } private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs) { testType = "exit"; testID = 0; this.Close(); } private void cmdNew_Click(System.Object eventSender, System.EventArgs eventArgs) { testType = "new"; testID = 0; this.Close(); } private void cmdNewExist_Click(System.Object eventSender, System.EventArgs eventArgs) { testType = "select"; testID = 0; this.Close(); } private void doSearch() { ADODB.Recordset rs = default(ADODB.Recordset); string sql = null; string lString = null; System.Windows.Forms.ListViewItem listItem = null; lString = Strings.Trim(txtSearch.Text); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); if (string.IsNullOrEmpty(lString)) { } else { lString = " AND (BlockTest.BlockTest_Desc LIKE '%" + Strings.Replace(lString, " ", "%' AND BlockTest.BlockTest_Desc LIKE '%") + "%')"; } rs = modRecordSet.getRS(ref "SELECT BlockTest.BlockTestID, BlockTest.BlockTest_Date, BlockTest.BlockTest_MainItemID, BlockTest.BlockTest_PersonID, BlockTest.BlockTest_Desc, Person.Person_FirstName, Person.Person_LastName, StockItem.StockItem_Name, BlockTest.BlockTest_BlockTestStatusID FROM (BlockTest INNER JOIN Person ON BlockTest.BlockTest_PersonID = Person.PersonID) INNER JOIN StockItem ON BlockTest.BlockTest_MainItemID = StockItem.StockItemID WHERE ((BlockTest.BlockTest_BlockTestStatusID)>0) " + lString + " ORDER BY BlockTest.BlockTest_Desc;"); //Set rs = getRS("SELECT PurchaseOrder.PurchaseOrderID, Supplier.Supplier_Name, PurchaseOrder.PurchaseOrder_DateCreated, PurchaseOrder.PurchaseOrder_Reference, GRV.GRV_InvoiceNumber, GRV.GRV_InvoiceInclusive FROM ((PurchaseOrder INNER JOIN Supplier ON PurchaseOrder.PurchaseOrder_SupplierID = Supplier.SupplierID) INNER JOIN PurchaseOrderStatus ON PurchaseOrder.PurchaseOrder_PurchaseOrderStatusID = PurchaseOrderStatus.PurchaseOrderStatusID) LEFT JOIN GRV ON PurchaseOrder.PurchaseOrderID = GRV.GRV_PurchaseOrderID Where PurchaseOrderStatus.PurchaseOrderStatus_Complete = 0 And Supplier.Supplier_Disabled = 0 " & lString & " ORDER BY Supplier.Supplier_Name;") // ERROR: Not supported in C#: OnErrorStatement lvImport.Items.Clear(); //UPGRADE_WARNING: Couldn't resolve default property of object rs.EOF. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' while (!(rs.EOF)) { //UPGRADE_WARNING: Couldn't resolve default property of object rs(BlockTest_Desc). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //UPGRADE_WARNING: Couldn't resolve default property of object rs(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' listItem = this.lvImport.Items.Add("k" + rs("BlockTestID").Value, rs("BlockTest_Desc").Value, ""); cmddelete.Enabled = true; //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' //UPGRADE_WARNING: Couldn't resolve default property of object rs(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' if (listItem.SubItems.Count > 1) { listItem.SubItems[1].Text = Strings.Format(rs("BlockTest_Date"), "yyyy mmm dd"); } else { listItem.SubItems.Insert(1, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, Strings.Format(rs("BlockTest_Date"), "yyyy mmm dd"))); } //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' //UPGRADE_WARNING: Couldn't resolve default property of object rs(Person_LastName). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //UPGRADE_WARNING: Couldn't resolve default property of object rs(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' if (listItem.SubItems.Count > 2) { listItem.SubItems[2].Text = rs("Person_FirstName").Value + " " + rs("Person_LastName").Value; } else { listItem.SubItems.Insert(2, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs("Person_FirstName").Value + " " + rs("Person_LastName").Value)); } //If IsNull(rs("GRV_InvoiceInclusive")) Then //Else //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' //UPGRADE_WARNING: Couldn't resolve default property of object rs(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' if (listItem.SubItems.Count > 3) { listItem.SubItems[3].Text = rs("StockItem_Name"); } else { listItem.SubItems.Insert(3, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs("StockItem_Name"))); } // listItem.SubItems(4) = FormatNumber(rs("GRV_InvoiceInclusive"), 2) //End If //UPGRADE_WARNING: Couldn't resolve default property of object rs.moveNext. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' rs.moveNext(); } } private void txtSearch_Enter(System.Object eventSender, System.EventArgs eventArgs) { txtSearch.SelectionStart = 0; txtSearch.SelectionLength = 999; } private void txtSearch_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); switch (KeyAscii) { case 13: doSearch(); KeyAscii = 0; break; } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void lvImport_DoubleClick(System.Object eventSender, System.EventArgs eventArgs) { cmdEdit_Click(cmdEdit, new System.EventArgs()); } private void lvImport_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 13) cmdEdit_Click(cmdEdit, new System.EventArgs()); eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void loadBT() { ADODB.Recordset rs = default(ADODB.Recordset); System.Windows.Forms.ListViewItem listItem = null; lvImport.Items.Clear(); rs = modRecordSet.getRS(ref "SELECT StockItem.StockItemID, GRVimport.GRVimport_Key, GRVimport.GRVimport_Barcode, StockItem.StockItem_Name, Catalogue.Catalogue_Quantity, GRVimport.GRVimport_Quantity, GRVimport.GRVimport_Cost, GRVimport.GRVimport_Price FROM (GRVimport INNER JOIN Catalogue ON GRVimport.GRVimport_Barcode = Catalogue.Catalogue_Barcode) INNER JOIN StockItem ON Catalogue.Catalogue_StockItemID = StockItem.StockItemID;"); while (!(rs.EOF)) { listItem = this.lvImport.Items.Add("k" + rs.Fields("stockitemID").Value, rs.Fields("GRVimport_Barcode").Value, ""); //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 1) { listItem.SubItems[1].Text = rs.Fields("StockItem_Name").Value; } else { listItem.SubItems.Insert(1, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("StockItem_Name").Value)); } //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 2) { listItem.SubItems[2].Text = rs.Fields("Catalogue_Quantity").Value; } else { listItem.SubItems.Insert(2, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("Catalogue_Quantity").Value)); } //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 3) { listItem.SubItems[3].Text = rs.Fields("GRVimport_Quantity").Value; } else { listItem.SubItems.Insert(3, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("GRVimport_Quantity").Value)); } //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 4) { listItem.SubItems[4].Text = Strings.FormatNumber(rs.Fields("GRVimport_Cost").Value, 2); } else { listItem.SubItems.Insert(4, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, Strings.FormatNumber(rs.Fields("GRVimport_Cost").Value, 2))); } //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 5) { listItem.SubItems[5].Text = Strings.FormatNumber(rs.Fields("GRVimport_Price").Value, 2); } else { listItem.SubItems.Insert(5, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, Strings.FormatNumber(rs.Fields("GRVimport_Price").Value, 2))); } //UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"' if (listItem.SubItems.Count > 6) { listItem.SubItems[6].Text = rs.Fields("GRVimport_Key").Value; } else { listItem.SubItems.Insert(6, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("GRVimport_Key").Value)); } rs.moveNext(); } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.Collections.Generic; using System.Threading; using MindTouch; using MindTouch.Dream; using MindTouch.Tasking; namespace System { using ClockCallback = Action<DateTime /* when */, TimeSpan /* elapsed */, bool /* fastforward */>; using NamedClockCallback = KeyValuePair<string /* name */, Action<DateTime /* when */, TimeSpan /* elapsed */, bool /* fastforward */>>; /// <summary> /// Provides a global timing mechanism that accepts registration of callback to be invoked by the clock. In most cases, a /// <see cref="TaskTimer"/> should be used rather than registering a callback directly with the global clock. /// </summary> public static class GlobalClock { //--- Constants --- private const int INITIAL_CALLBACK_CAPACITY = 8; //--- Class Fields --- private static readonly object _syncRoot = new object(); private static readonly log4net.ILog _log = LogUtils.CreateLog(); private static volatile bool _running = true; private static readonly ManualResetEvent _stopped = new ManualResetEvent(false); private static NamedClockCallback[] _callbacks = new NamedClockCallback[INITIAL_CALLBACK_CAPACITY]; private static readonly int _intervalMilliseconds; private static object _suspendedTime; private static int _timeOffset; //--- Class Constructor --- static GlobalClock() { // TODO (steveb): make global clock interval configurable via app settings _intervalMilliseconds = 100; // start-up the tick thread for all global timed callbacks var thread = AsyncUtil.CreateThread(MasterTickThread); thread.Priority = ThreadPriority.Highest; thread.Name = "GlobalClock"; thread.Start(); } //--- Class Properties --- public static DateTime UtcNow { get { return ((DateTime?)_suspendedTime) ?? (DateTime.UtcNow + TimeSpan.FromMilliseconds(_timeOffset)); } } //--- Class Methods --- /// <summary> /// Add a named callback to the clock. /// </summary> /// <param name="name">Unique key for the callback.</param> /// <param name="callback">Callback action.</param> public static void AddCallback(string name, ClockCallback callback) { if(string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name", "name cannot be null or empty"); } if(callback == null) { throw new ArgumentNullException("callback"); } // add callback lock(_syncRoot) { int index; // check if there is an empty slot in the callbacks array for(index = 0; index < _callbacks.Length; ++index) { if(_callbacks[index].Value == null) { _callbacks[index] = new NamedClockCallback(name, callback); return; } } // make room to add a new thread by doubling the array size and copying over the existing entries var newArray = new NamedClockCallback[2 * _callbacks.Length]; Array.Copy(_callbacks, newArray, _callbacks.Length); // assign new thread newArray[index] = new NamedClockCallback(name, callback); // update instance field _callbacks = newArray; } } /// <summary> /// Remove a callback by reference. /// </summary> /// <param name="callback">Callback to remove.</param> public static void RemoveCallback(ClockCallback callback) { // remove callback lock(_syncRoot) { for(var i = 0; i < _callbacks.Length; ++i) { if(_callbacks[i].Value == callback) { _callbacks[i] = new NamedClockCallback(null, null); } } } } /// <summary> /// Fast-forward time for the global clock. /// </summary> /// <param name="time">Timespan to fast-forward the global clock (cannot be negative).</param> /// <param name="cancelFastForward">Optional callback to prematurely cancel the fast-fwoard operation.</param> /// <remarks>DO NOT USE FOR PRODUCTION CODE!!!</remarks> public static DateTime FastForward(TimeSpan time, Func<bool> cancelFastForward = null) { // TODO (2015-07-30, steveb): add flag to detect if this code is running in production and throw an exception if it is! if(time <= TimeSpan.Zero) { throw new ArgumentException("time must be positive"); } lock(_syncRoot) { var timeMilliseconds = (int)time.TotalMilliseconds; var intervalMilliseconds = _intervalMilliseconds; do { var elapsed = Math.Min(timeMilliseconds, intervalMilliseconds); Interlocked.Add(ref _timeOffset, elapsed); var now = UtcNow; MasterTick(now, TimeSpan.FromMilliseconds(elapsed), true); if((cancelFastForward != null) && cancelFastForward()) { return now; } timeMilliseconds -= elapsed; } while(timeMilliseconds > 0); return UtcNow; } } /// <summary> /// Suspend the global clock from progressing. /// </summary> /// <returns>Object that when disposed resumes the global clock.</returns> /// <remarks>DO NOT USE FOR PRODUCTION CODE!!!</remarks> public static IDisposable Suspend() { // TODO (2015-07-30, steveb): add flag to detect if this code is running in production and throw an exception if it is! Monitor.Enter(_syncRoot); var suspendedTime = Interlocked.Exchange(ref _suspendedTime, (DateTime?)UtcNow); return new DisposeCallback(() => { Interlocked.Exchange(ref _suspendedTime, suspendedTime); Monitor.Exit(_syncRoot); }); } internal static bool Shutdown(TimeSpan timeout) { // stop the thread timer _running = false; if((timeout != TimeSpan.MaxValue && !_stopped.WaitOne((int)timeout.TotalMilliseconds, true)) || (timeout == TimeSpan.MaxValue && !_stopped.WaitOne()) ) { _log.ErrorExceptionMethodCall(new TimeoutException("GlobalClock thread shutdown timed out"), "Shutdown"); return false; } return true; } private static void MasterTickThread() { var last = UtcNow; while(_running) { // wait until next iteration Thread.Sleep(_intervalMilliseconds); // get current time and calculate delta var now = UtcNow; var elapsed = now - last; last = now; // execute all callbacks lock(_syncRoot) { MasterTick(now, elapsed, false); } } // indicate that this thread has exited _stopped.Set(); } private static void MasterTick(DateTime now, TimeSpan elapsed, bool fastforward) { var callbacks = _callbacks; foreach(var callback in callbacks) { if(callback.Value != null) { try { callback.Value(now, elapsed, fastforward); } catch(Exception e) { _log.ErrorExceptionMethodCall(e, "GlobalClock callback failed", callback.Key); } } } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.Threading; using System.Xml; // Note on locking: // The following rule must be followed in order to avoid deadlocks: ReliableRequestContext // locks MUST NOT be taken while under the ReliableReplySessionChannel lock. // // lock(context)-->lock(channel) ok. // lock(channel)-->lock(context) BAD! // sealed class ReliableReplySessionChannel : ReplyChannel, IReplySessionChannel { List<Int64> acked = new List<Int64>(); static Action<object> asyncReceiveComplete = new Action<object>(AsyncReceiveCompleteStatic); IServerReliableChannelBinder binder; ReplyHelper closeSequenceReplyHelper; ReliableInputConnection connection; bool contextAborted; DeliveryStrategy<RequestContext> deliveryStrategy; ReliableRequestContext lastReply; bool lastReplyAcked; Int64 lastReplySequenceNumber = Int64.MinValue; ReliableChannelListenerBase<IReplySessionChannel> listener; InterruptibleWaitObject messagingCompleteWaitObject; Int64 nextReplySequenceNumber; static AsyncCallback onReceiveCompleted = Fx.ThunkCallback(new AsyncCallback(OnReceiveCompletedStatic)); string perfCounterId; Dictionary<Int64, ReliableRequestContext> requestsByRequestSequenceNumber = new Dictionary<Int64, ReliableRequestContext>(); Dictionary<Int64, ReliableRequestContext> requestsByReplySequenceNumber = new Dictionary<Int64, ReliableRequestContext>(); ServerReliableSession session; ReplyHelper terminateSequenceReplyHelper; public ReliableReplySessionChannel( ReliableChannelListenerBase<IReplySessionChannel> listener, IServerReliableChannelBinder binder, FaultHelper faultHelper, UniqueId inputID, UniqueId outputID) : base(listener, binder.LocalAddress) { this.listener = listener; this.connection = new ReliableInputConnection(); this.connection.ReliableMessagingVersion = this.listener.ReliableMessagingVersion; this.binder = binder; this.session = new ServerReliableSession(this, listener, binder, faultHelper, inputID, outputID); this.session.UnblockChannelCloseCallback = this.UnblockClose; if (this.listener.Ordered) this.deliveryStrategy = new OrderedDeliveryStrategy<RequestContext>(this, this.listener.MaxTransferWindowSize, true); else this.deliveryStrategy = new UnorderedDeliveryStrategy<RequestContext>(this, this.listener.MaxTransferWindowSize); this.binder.Faulted += OnBinderFaulted; this.binder.OnException += OnBinderException; if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { this.messagingCompleteWaitObject = new InterruptibleWaitObject(false); } this.session.Open(TimeSpan.Zero); if (PerformanceCounters.PerformanceCountersEnabled) this.perfCounterId = this.listener.Uri.ToString().ToUpperInvariant(); if (binder.HasSession) { try { this.StartReceiving(false); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.session.OnUnknownException(e); } } } public IServerReliableChannelBinder Binder { get { return this.binder; } } bool IsMessagingCompleted { get { lock (this.ThisLock) { return this.connection.AllAdded && (this.requestsByRequestSequenceNumber.Count == 0) && this.lastReplyAcked; } } } MessageVersion MessageVersion { get { return this.listener.MessageVersion; } } int PendingRequestContexts { get { lock (this.ThisLock) { return (this.requestsByRequestSequenceNumber.Count - this.requestsByReplySequenceNumber.Count); } } } public IInputSession Session { get { return this.session; } } void AbortContexts() { lock (this.ThisLock) { if (this.contextAborted) return; this.contextAborted = true; } Dictionary<Int64, ReliableRequestContext>.ValueCollection contexts = this.requestsByRequestSequenceNumber.Values; foreach (ReliableRequestContext request in contexts) { request.Abort(); } this.requestsByRequestSequenceNumber.Clear(); this.requestsByReplySequenceNumber.Clear(); if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (this.lastReply != null) this.lastReply.Abort(); } } void AddAcknowledgementHeader(Message message) { WsrmUtilities.AddAcknowledgementHeader( this.listener.ReliableMessagingVersion, message, this.session.InputID, this.connection.Ranges, this.connection.IsLastKnown, this.listener.MaxTransferWindowSize - this.deliveryStrategy.EnqueuedCount); } static void AsyncReceiveCompleteStatic(object state) { IAsyncResult result = (IAsyncResult)state; ReliableReplySessionChannel channel = (ReliableReplySessionChannel)(result.AsyncState); try { if (channel.HandleReceiveComplete(result)) { channel.StartReceiving(true); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } channel.session.OnUnknownException(e); } } IAsyncResult BeginCloseBinder(TimeSpan timeout, AsyncCallback callback, object state) { return this.binder.BeginClose(timeout, MaskingMode.Handled, callback, state); } IAsyncResult BeginCloseOutput(TimeSpan timeout, AsyncCallback callback, object state) { if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { ReliableRequestContext reply = this.lastReply; if (reply == null) return new CloseOutputCompletedAsyncResult(callback, state); else return reply.BeginReplyInternal(null, timeout, callback, state); } else { lock (this.ThisLock) { this.ThrowIfClosed(); this.CreateCloseSequenceReplyHelper(); } return this.closeSequenceReplyHelper.BeginWaitAndReply(timeout, callback, state); } } IAsyncResult BeginUnregisterChannel(TimeSpan timeout, AsyncCallback callback, object state) { return this.listener.OnReliableChannelBeginClose(this.session.InputID, this.session.OutputID, timeout, callback, state); } Message CreateAcknowledgement(SequenceRangeCollection ranges) { Message message = WsrmUtilities.CreateAcknowledgmentMessage( this.MessageVersion, this.listener.ReliableMessagingVersion, this.session.InputID, ranges, this.connection.IsLastKnown, this.listener.MaxTransferWindowSize - this.deliveryStrategy.EnqueuedCount); return message; } Message CreateSequenceClosedFault() { Message message = new SequenceClosedFault(this.session.InputID).CreateMessage( this.listener.MessageVersion, this.listener.ReliableMessagingVersion); this.AddAcknowledgementHeader(message); return message; } bool CreateCloseSequenceReplyHelper() { if (this.State == CommunicationState.Faulted || this.Aborted) { return false; } if (this.closeSequenceReplyHelper == null) { this.closeSequenceReplyHelper = new ReplyHelper(this, CloseSequenceReplyProvider.Instance, true); } return true; } bool CreateTerminateSequenceReplyHelper() { if (this.State == CommunicationState.Faulted || this.Aborted) { return false; } if (this.terminateSequenceReplyHelper == null) { this.terminateSequenceReplyHelper = new ReplyHelper(this, TerminateSequenceReplyProvider.Instance, false); } return true; } void CloseOutput(TimeSpan timeout) { if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { ReliableRequestContext reply = this.lastReply; if (reply != null) reply.ReplyInternal(null, timeout); } else { lock (this.ThisLock) { this.ThrowIfClosed(); this.CreateCloseSequenceReplyHelper(); } this.closeSequenceReplyHelper.WaitAndReply(timeout); } } bool ContainsRequest(Int64 requestSeqNum) { lock (this.ThisLock) { bool haveRequestInDictionary = this.requestsByRequestSequenceNumber.ContainsKey(requestSeqNum); if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { return (haveRequestInDictionary || ((this.lastReply != null) && (this.lastReply.RequestSequenceNumber == requestSeqNum) && (!this.lastReplyAcked))); } else { return haveRequestInDictionary; } } } void EndCloseBinder(IAsyncResult result) { this.binder.EndClose(result); } void EndCloseOutput(IAsyncResult result) { if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (result is CloseOutputCompletedAsyncResult) CloseOutputCompletedAsyncResult.End(result); else this.lastReply.EndReplyInternal(result); } else { this.closeSequenceReplyHelper.EndWaitAndReply(result); } } void EndUnregisterChannel(IAsyncResult result) { this.listener.OnReliableChannelEndClose(result); } public override T GetProperty<T>() { if (typeof(T) == typeof(IReplySessionChannel)) { return (T)(object)this; } T baseProperty = base.GetProperty<T>(); if (baseProperty != null) { return baseProperty; } T innerProperty = this.binder.Channel.GetProperty<T>(); if ((innerProperty == null) && (typeof(T) == typeof(FaultConverter))) { return (T)(object)FaultConverter.GetDefaultFaultConverter(this.listener.MessageVersion); } else { return innerProperty; } } bool HandleReceiveComplete(IAsyncResult result) { RequestContext context; if (this.Binder.EndTryReceive(result, out context)) { if (context == null) { bool terminated = false; lock (this.ThisLock) { terminated = this.connection.Terminate(); } if (!terminated && (this.Binder.State == CommunicationState.Opened)) { Exception e = new CommunicationException(SR.GetString(SR.EarlySecurityClose)); this.session.OnLocalFault(e, (Message)null, null); } return false; } WsrmMessageInfo info = WsrmMessageInfo.Get(this.listener.MessageVersion, this.listener.ReliableMessagingVersion, this.binder.Channel, this.binder.GetInnerSession(), context.RequestMessage); this.StartReceiving(false); this.ProcessRequest(context, info); return false; } return true; } protected override void OnAbort() { if (this.closeSequenceReplyHelper != null) { this.closeSequenceReplyHelper.Abort(); } this.connection.Abort(this); if (this.terminateSequenceReplyHelper != null) { this.terminateSequenceReplyHelper.Abort(); } this.session.Abort(); this.AbortContexts(); if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { this.messagingCompleteWaitObject.Abort(this); } this.listener.OnReliableChannelAbort(this.session.InputID, this.session.OutputID); base.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { this.ThrowIfCloseInvalid(); bool wsrmFeb2005 = this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005; OperationWithTimeoutBeginCallback[] beginOperations = new OperationWithTimeoutBeginCallback[] { new OperationWithTimeoutBeginCallback (this.BeginCloseOutput), wsrmFeb2005 ? new OperationWithTimeoutBeginCallback(this.connection.BeginClose) : new OperationWithTimeoutBeginCallback(this.BeginTerminateSequence), wsrmFeb2005 ? new OperationWithTimeoutBeginCallback(this.messagingCompleteWaitObject.BeginWait) : new OperationWithTimeoutBeginCallback(this.connection.BeginClose), new OperationWithTimeoutBeginCallback(this.session.BeginClose), new OperationWithTimeoutBeginCallback(this.BeginCloseBinder), new OperationWithTimeoutBeginCallback(this.BeginUnregisterChannel), new OperationWithTimeoutBeginCallback(base.OnBeginClose) }; OperationEndCallback[] endOperations = new OperationEndCallback[] { new OperationEndCallback(this.EndCloseOutput), wsrmFeb2005 ? new OperationEndCallback(this.connection.EndClose) : new OperationEndCallback(this.EndTerminateSequence), wsrmFeb2005 ? new OperationEndCallback(this.messagingCompleteWaitObject.EndWait) : new OperationEndCallback(this.connection.EndClose), new OperationEndCallback(this.session.EndClose), new OperationEndCallback(this.EndCloseBinder), new OperationEndCallback(this.EndUnregisterChannel), new OperationEndCallback(base.OnEndClose) }; return OperationWithTimeoutComposer.BeginComposeAsyncOperations(timeout, beginOperations, endOperations, callback, state); } void OnBinderException(IReliableChannelBinder sender, Exception exception) { if (exception is QuotaExceededException) this.session.OnLocalFault(exception, (Message)null, null); else this.EnqueueAndDispatch(exception, null, false); } void OnBinderFaulted(IReliableChannelBinder sender, Exception exception) { this.binder.Abort(); exception = new CommunicationException(SR.GetString(SR.EarlySecurityFaulted), exception); this.session.OnLocalFault(exception, (Message)null, null); } protected override void OnClose(TimeSpan timeout) { this.ThrowIfCloseInvalid(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.CloseOutput(timeoutHelper.RemainingTime()); if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { this.connection.Close(timeoutHelper.RemainingTime()); this.messagingCompleteWaitObject.Wait(timeoutHelper.RemainingTime()); } else { this.TerminateSequence(timeoutHelper.RemainingTime()); this.connection.Close(timeoutHelper.RemainingTime()); } this.session.Close(timeoutHelper.RemainingTime()); this.binder.Close(timeoutHelper.RemainingTime(), MaskingMode.Handled); this.listener.OnReliableChannelClose(this.session.InputID, this.session.OutputID, timeoutHelper.RemainingTime()); base.OnClose(timeoutHelper.RemainingTime()); } protected override void OnClosed() { this.deliveryStrategy.Dispose(); this.binder.Faulted -= this.OnBinderFaulted; if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (this.lastReply != null) { this.lastReply.Abort(); } } base.OnClosed(); } protected override void OnEndClose(IAsyncResult result) { OperationWithTimeoutComposer.EndComposeAsyncOperations(result); } protected override void OnFaulted() { this.session.OnFaulted(); this.UnblockClose(); base.OnFaulted(); if (PerformanceCounters.PerformanceCountersEnabled) PerformanceCounters.SessionFaulted(this.perfCounterId); } static void OnReceiveCompletedStatic(IAsyncResult result) { if (result.CompletedSynchronously) return; ReliableReplySessionChannel channel = (ReliableReplySessionChannel)(result.AsyncState); try { if (channel.HandleReceiveComplete(result)) { channel.StartReceiving(true); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } channel.session.OnUnknownException(e); } } void OnTerminateSequenceCompleted() { if ((this.session.Settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) && this.connection.IsSequenceClosed) { lock (this.ThisLock) { this.connection.Terminate(); } } } bool PrepareReply(ReliableRequestContext context) { lock (this.ThisLock) { if (this.Aborted || this.State == CommunicationState.Faulted || this.State == CommunicationState.Closed) return false; long requestSequenceNumber = context.RequestSequenceNumber; bool wsrmFeb2005 = this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005; if (wsrmFeb2005 && (this.connection.Last == requestSequenceNumber)) { if (this.lastReply == null) this.lastReply = context; this.requestsByRequestSequenceNumber.Remove(requestSequenceNumber); bool canReply = this.connection.AllAdded && (this.State == CommunicationState.Closing); if (!canReply) return false; } else { if (this.State == CommunicationState.Closing) return false; if (!context.HasReply) { this.requestsByRequestSequenceNumber.Remove(requestSequenceNumber); return true; } } // won't throw if you do not need next sequence number if (this.nextReplySequenceNumber == Int64.MaxValue) { MessageNumberRolloverFault fault = new MessageNumberRolloverFault(this.session.OutputID); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(fault.CreateException()); } context.SetReplySequenceNumber(++this.nextReplySequenceNumber); if (wsrmFeb2005 && (this.connection.Last == requestSequenceNumber)) { if (!context.HasReply) this.lastReplyAcked = true; //If Last Reply has no user data, it does not need to be acked. Here we just set it as its ack received. this.lastReplySequenceNumber = this.nextReplySequenceNumber; context.SetLastReply(this.lastReplySequenceNumber); } else if (context.HasReply) { this.requestsByReplySequenceNumber.Add(this.nextReplySequenceNumber, context); } return true; } } Message PrepareReplyMessage(Int64 replySequenceNumber, bool isLast, SequenceRangeCollection ranges, Message reply) { this.AddAcknowledgementHeader(reply); WsrmUtilities.AddSequenceHeader( this.listener.ReliableMessagingVersion, reply, this.session.OutputID, replySequenceNumber, isLast); return reply; } void ProcessAcknowledgment(WsrmAcknowledgmentInfo info) { lock (this.ThisLock) { if (this.Aborted || this.State == CommunicationState.Faulted || this.State == CommunicationState.Closed) return; if (this.requestsByReplySequenceNumber.Count > 0) { Int64 reply; this.acked.Clear(); foreach (KeyValuePair<Int64, ReliableRequestContext> pair in this.requestsByReplySequenceNumber) { reply = pair.Key; if (info.Ranges.Contains(reply)) { this.acked.Add(reply); } } for (int i = 0; i < this.acked.Count; i++) { reply = this.acked[i]; this.requestsByRequestSequenceNumber.Remove( this.requestsByReplySequenceNumber[reply].RequestSequenceNumber); this.requestsByReplySequenceNumber.Remove(reply); } if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (!this.lastReplyAcked && (this.lastReplySequenceNumber != Int64.MinValue)) { this.lastReplyAcked = info.Ranges.Contains(this.lastReplySequenceNumber); } } } } } void ProcessAckRequested(RequestContext context) { try { using (Message reply = CreateAcknowledgement(this.connection.Ranges)) { context.Reply(reply); } } finally { context.RequestMessage.Close(); context.Close(); } } void ProcessShutdown11(RequestContext context, WsrmMessageInfo info) { bool cleanup = true; try { bool isTerminate = (info.TerminateSequenceInfo != null); WsrmRequestInfo requestInfo = isTerminate ? (WsrmRequestInfo)info.TerminateSequenceInfo : (WsrmRequestInfo)info.CloseSequenceInfo; Int64 last = isTerminate ? info.TerminateSequenceInfo.LastMsgNumber : info.CloseSequenceInfo.LastMsgNumber; if (!WsrmUtilities.ValidateWsrmRequest(this.session, requestInfo, this.binder, context)) { cleanup = false; return; } bool scheduleShutdown = false; Exception remoteFaultException = null; ReplyHelper closeHelper = null; bool haveAllReplyAcks = true; bool isLastLargeEnough = true; bool isLastConsistent = true; lock (this.ThisLock) { if (!this.connection.IsLastKnown) { // All requests and replies must be acknowledged. if (this.requestsByRequestSequenceNumber.Count == 0) { if (isTerminate) { if (this.connection.SetTerminateSequenceLast(last, out isLastLargeEnough)) { scheduleShutdown = true; } else if (isLastLargeEnough) { remoteFaultException = new ProtocolException(SR.GetString(SR.EarlyTerminateSequence)); } } else { scheduleShutdown = this.connection.SetCloseSequenceLast(last); isLastLargeEnough = scheduleShutdown; } if (scheduleShutdown) { // (1) !isTerminate && !IsLastKnown, CloseSequence received before TerminateSequence. // - Need to ensure helper to delay the reply until Close. // (2) isTerminate && !IsLastKnown, TerminateSequence received before CloseSequence. // - Close not required, ensure it is created so we can bypass it. if (!this.CreateCloseSequenceReplyHelper()) { return; } // Capture the helper in order to unblock it. if (isTerminate) { closeHelper = this.closeSequenceReplyHelper; } this.session.SetFinalAck(this.connection.Ranges); this.deliveryStrategy.Dispose(); } } else { haveAllReplyAcks = false; } } else { isLastConsistent = (last == this.connection.Last); } } WsrmFault fault = null; if (!isLastLargeEnough) { string faultString = SR.GetString(SR.SequenceTerminatedSmallLastMsgNumber); string exceptionString = SR.GetString(SR.SmallLastMsgNumberExceptionString); fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID, faultString, exceptionString); } else if (!haveAllReplyAcks) { string faultString = SR.GetString(SR.SequenceTerminatedNotAllRepliesAcknowledged); string exceptionString = SR.GetString(SR.NotAllRepliesAcknowledgedExceptionString); fault = SequenceTerminatedFault.CreateProtocolFault(this.session.OutputID, faultString, exceptionString); } else if (!isLastConsistent) { string faultString = SR.GetString(SR.SequenceTerminatedInconsistentLastMsgNumber); string exceptionString = SR.GetString(SR.InconsistentLastMsgNumberExceptionString); fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID, faultString, exceptionString); } else if (remoteFaultException != null) { Message message = WsrmUtilities.CreateTerminateMessage(this.MessageVersion, this.listener.ReliableMessagingVersion, this.session.OutputID); this.AddAcknowledgementHeader(message); using (message) { context.Reply(message); } this.session.OnRemoteFault(remoteFaultException); return; } if (fault != null) { this.session.OnLocalFault(fault.CreateException(), fault, context); cleanup = false; return; } if (isTerminate) { if (closeHelper != null) { closeHelper.UnblockWaiter(); } lock (this.ThisLock) { if (!this.CreateTerminateSequenceReplyHelper()) { return; } } } ReplyHelper replyHelper = isTerminate ? this.terminateSequenceReplyHelper : this.closeSequenceReplyHelper; if (!replyHelper.TransferRequestContext(context, info)) { replyHelper.Reply(context, info, this.DefaultSendTimeout, MaskingMode.All); if (isTerminate) { this.OnTerminateSequenceCompleted(); } } else { cleanup = false; } if (scheduleShutdown) { ActionItem.Schedule(this.ShutdownCallback, null); } } finally { if (cleanup) { context.RequestMessage.Close(); context.Close(); } } } public void ProcessDemuxedRequest(RequestContext context, WsrmMessageInfo info) { try { this.ProcessRequest(context, info); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) throw; this.session.OnUnknownException(e); } } void ProcessRequest(RequestContext context, WsrmMessageInfo info) { bool closeMessage = true; bool closeContext = true; try { if (!this.session.ProcessInfo(info, context)) { closeMessage = false; closeContext = false; return; } if (!this.session.VerifyDuplexProtocolElements(info, context)) { closeMessage = false; closeContext = false; return; } this.session.OnRemoteActivity(false); if (info.CreateSequenceInfo != null) { EndpointAddress acksTo; if (WsrmUtilities.ValidateCreateSequence<IReplySessionChannel>(info, this.listener, this.binder.Channel, out acksTo)) { Message response = WsrmUtilities.CreateCreateSequenceResponse(this.listener.MessageVersion, this.listener.ReliableMessagingVersion, true, info.CreateSequenceInfo, this.listener.Ordered, this.session.InputID, acksTo); using (context) { using (response) { if (this.Binder.AddressResponse(info.Message, response)) context.Reply(response, this.DefaultSendTimeout); } } } else { this.session.OnLocalFault(info.FaultException, info.FaultReply, context); } closeContext = false; return; } closeContext = false; if (info.AcknowledgementInfo != null) { ProcessAcknowledgment(info.AcknowledgementInfo); closeContext = (info.Action == WsrmIndex.GetSequenceAcknowledgementActionString(this.listener.ReliableMessagingVersion)); } if (!closeContext) { closeMessage = false; if (info.SequencedMessageInfo != null) { ProcessSequencedMessage(context, info.Action, info.SequencedMessageInfo); } else if (info.TerminateSequenceInfo != null) { if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { ProcessTerminateSequenceFeb2005(context, info); } else if (info.TerminateSequenceInfo.Identifier == this.session.InputID) { ProcessShutdown11(context, info); } else // Identifier == OutputID { WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID, SR.GetString(SR.SequenceTerminatedUnsupportedTerminateSequence), SR.GetString(SR.UnsupportedTerminateSequenceExceptionString)); this.session.OnLocalFault(fault.CreateException(), fault, context); closeMessage = false; closeContext = false; return; } } else if (info.CloseSequenceInfo != null) { ProcessShutdown11(context, info); } else if (info.AckRequestedInfo != null) { ProcessAckRequested(context); } } if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (this.IsMessagingCompleted) { this.messagingCompleteWaitObject.Set(); } } } finally { if (closeMessage) info.Message.Close(); if (closeContext) context.Close(); } } // A given reliable request can be in one of three states: // 1. Known and Processing: A ReliableRequestContext exists in requestTable but the outcome for // for the request is unknown. Any transport request referencing this reliable request // (by means of the sequence number) must be held until the outcome becomes known. // 2. Known and Processed: A ReliableRequestContext exists in the requestTable and the outcome for // for the request is known. The ReliableRequestContext holds that outcome. Any transport requests // referening this reliable request must send the response dictated by the outcome. // 3. Unknown: No ReliableRequestContext exists in the requestTable for the referenced reliable request. // In this case a new ReliableRequestContext is added to the requestTable to await some outcome. // // There are 4 possible outcomes for a reliable request: // a. It is captured and the user replies. Transport replies are then copies of the user's reply. // b. It is captured and the user closes the context. Transport replies are then acknowledgments // that include the sequence number of the reliable request. // c. It is captured and and the user aborts the context. Transport contexts are then aborted. // d. It is not captured. In this case an acknowledgment that includes all sequence numbers // previously captured is sent. Note two sub-cases here: // 1. It is not captured because it is dropped (e.g. it doesn't fit in the buffer). In this // case the reliable request's sequence number is not in the acknowledgment. // 2. It is not captured because it is a duplicate. In this case the reliable request's // sequence number is included in the acknowledgment. // // By following these rules it is possible to support one-way and two-operations without having // knowledge of them (the user drives using the request context we give them) and at the same time // it is possible to forget about past replies once acknowledgments for them are received. void ProcessSequencedMessage(RequestContext context, string action, WsrmSequencedMessageInfo info) { ReliableRequestContext reliableContext = null; WsrmFault fault = null; bool needDispatch = false; bool scheduleShutdown = false; bool wsrmFeb2005 = this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005; bool wsrm11 = this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11; Int64 requestSequenceNumber = info.SequenceNumber; bool isLast = wsrmFeb2005 && info.LastMessage; bool isLastOnly = wsrmFeb2005 && (action == WsrmFeb2005Strings.LastMessageAction); bool isDupe; Message message = null; lock (this.ThisLock) { if (this.Aborted || this.State == CommunicationState.Faulted || this.State == CommunicationState.Closed) { context.RequestMessage.Close(); context.Abort(); return; } isDupe = this.connection.Ranges.Contains(requestSequenceNumber); if (!this.connection.IsValid(requestSequenceNumber, isLast)) { if (wsrmFeb2005) { fault = new LastMessageNumberExceededFault(this.session.InputID); } else { message = this.CreateSequenceClosedFault(); if (PerformanceCounters.PerformanceCountersEnabled) PerformanceCounters.MessageDropped(this.perfCounterId); } } else if (isDupe) { if (PerformanceCounters.PerformanceCountersEnabled) PerformanceCounters.MessageDropped(this.perfCounterId); if (!this.requestsByRequestSequenceNumber.TryGetValue(info.SequenceNumber, out reliableContext)) { if ((this.lastReply != null) && (this.lastReply.RequestSequenceNumber == info.SequenceNumber)) reliableContext = this.lastReply; else reliableContext = new ReliableRequestContext(context, info.SequenceNumber, this, true); } reliableContext.SetAckRanges(this.connection.Ranges); } else if ((this.State == CommunicationState.Closing) && !isLastOnly) { if (wsrmFeb2005) { fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID, SR.GetString(SR.SequenceTerminatedSessionClosedBeforeDone), SR.GetString(SR.SessionClosedBeforeDone)); } else { message = this.CreateSequenceClosedFault(); if (PerformanceCounters.PerformanceCountersEnabled) PerformanceCounters.MessageDropped(this.perfCounterId); } } // In the unordered case we accept no more than MaxSequenceRanges ranges to limit the // serialized ack size and the amount of memory taken by the ack ranges. In the // ordered case, the delivery strategy MaxTransferWindowSize quota mitigates this // threat. else if (this.deliveryStrategy.CanEnqueue(requestSequenceNumber) && (this.requestsByReplySequenceNumber.Count < this.listener.MaxTransferWindowSize) && (this.listener.Ordered || this.connection.CanMerge(requestSequenceNumber))) { this.connection.Merge(requestSequenceNumber, isLast); reliableContext = new ReliableRequestContext(context, info.SequenceNumber, this, false); reliableContext.SetAckRanges(this.connection.Ranges); if (!isLastOnly) { needDispatch = this.deliveryStrategy.Enqueue(reliableContext, requestSequenceNumber); this.requestsByRequestSequenceNumber.Add(info.SequenceNumber, reliableContext); } else { this.lastReply = reliableContext; } scheduleShutdown = this.connection.AllAdded; } else { if (PerformanceCounters.PerformanceCountersEnabled) PerformanceCounters.MessageDropped(this.perfCounterId); } } if (fault != null) { this.session.OnLocalFault(fault.CreateException(), fault, context); return; } if (reliableContext == null) { if (message != null) { using (message) { context.Reply(message); } } context.RequestMessage.Close(); context.Close(); return; } if (isDupe && reliableContext.CheckForReplyOrAddInnerContext(context)) { reliableContext.SendReply(context, MaskingMode.All); return; } if (!isDupe && isLastOnly) { reliableContext.Close(); } if (needDispatch) { this.Dispatch(); } if (scheduleShutdown) { ActionItem.Schedule(this.ShutdownCallback, null); } } void ProcessTerminateSequenceFeb2005(RequestContext context, WsrmMessageInfo info) { bool cleanup = true; try { Message message = null; bool isTerminateEarly; bool haveAllReplyAcks; lock (this.ThisLock) { isTerminateEarly = !this.connection.Terminate(); haveAllReplyAcks = this.requestsByRequestSequenceNumber.Count == 0; } WsrmFault fault = null; if (isTerminateEarly) { fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID, SR.GetString(SR.SequenceTerminatedEarlyTerminateSequence), SR.GetString(SR.EarlyTerminateSequence)); } else if (!haveAllReplyAcks) { fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID, SR.GetString(SR.SequenceTerminatedBeforeReplySequenceAcked), SR.GetString(SR.EarlyRequestTerminateSequence)); } if (fault != null) { this.session.OnLocalFault(fault.CreateException(), fault, context); cleanup = false; return; } message = WsrmUtilities.CreateTerminateMessage(this.MessageVersion, this.listener.ReliableMessagingVersion, this.session.OutputID); this.AddAcknowledgementHeader(message); using (message) { context.Reply(message); } } finally { if (cleanup) { context.RequestMessage.Close(); context.Close(); } } } void StartReceiving(bool canBlock) { while (true) { IAsyncResult result = this.binder.BeginTryReceive(TimeSpan.MaxValue, onReceiveCompleted, this); if (!result.CompletedSynchronously) { return; } if (!canBlock) { ActionItem.Schedule(asyncReceiveComplete, result); return; } if (!this.HandleReceiveComplete(result)) break; } } void ShutdownCallback(object state) { this.Shutdown(); } void TerminateSequence(TimeSpan timeout) { lock (this.ThisLock) { this.ThrowIfClosed(); this.CreateTerminateSequenceReplyHelper(); } this.terminateSequenceReplyHelper.WaitAndReply(timeout); this.OnTerminateSequenceCompleted(); } IAsyncResult BeginTerminateSequence(TimeSpan timeout, AsyncCallback callback, object state) { lock (this.ThisLock) { this.ThrowIfClosed(); this.CreateTerminateSequenceReplyHelper(); } return this.terminateSequenceReplyHelper.BeginWaitAndReply(timeout, callback, state); } void EndTerminateSequence(IAsyncResult result) { this.terminateSequenceReplyHelper.EndWaitAndReply(result); this.OnTerminateSequenceCompleted(); } void ThrowIfCloseInvalid() { bool shouldFault = false; if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (this.PendingRequestContexts != 0 || this.connection.Ranges.Count > 1) { shouldFault = true; } } else if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { if (this.PendingRequestContexts != 0) { shouldFault = true; } } if (shouldFault) { WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID, SR.GetString(SR.SequenceTerminatedSessionClosedBeforeDone), SR.GetString(SR.SessionClosedBeforeDone)); this.session.OnLocalFault(null, fault, null); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(fault.CreateException()); } } void UnblockClose() { this.AbortContexts(); if (this.listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { this.messagingCompleteWaitObject.Fault(this); } else { if (this.closeSequenceReplyHelper != null) { this.closeSequenceReplyHelper.Fault(); } if (this.terminateSequenceReplyHelper != null) { this.terminateSequenceReplyHelper.Fault(); } } this.connection.Fault(this); } class CloseOutputCompletedAsyncResult : CompletedAsyncResult { public CloseOutputCompletedAsyncResult(AsyncCallback callback, object state) : base(callback, state) { } } class ReliableRequestContext : RequestContextBase { MessageBuffer bufferedReply; ReliableReplySessionChannel channel; List<RequestContext> innerContexts = new List<RequestContext>(); bool isLastReply; bool outcomeKnown; SequenceRangeCollection ranges; Int64 requestSequenceNumber; Int64 replySequenceNumber; public ReliableRequestContext(RequestContext context, Int64 requestSequenceNumber, ReliableReplySessionChannel channel, bool outcome) : base(context.RequestMessage, channel.DefaultCloseTimeout, channel.DefaultSendTimeout) { this.channel = channel; this.requestSequenceNumber = requestSequenceNumber; this.outcomeKnown = outcome; if (!outcome) this.innerContexts.Add(context); } public bool CheckForReplyOrAddInnerContext(RequestContext innerContext) { lock (this.ThisLock) { if (this.outcomeKnown) return true; this.innerContexts.Add(innerContext); return false; } } public bool HasReply { get { return (this.bufferedReply != null); } } public Int64 RequestSequenceNumber { get { return this.requestSequenceNumber; } } void AbortInnerContexts() { for (int i = 0; i < this.innerContexts.Count; i++) { this.innerContexts[i].Abort(); this.innerContexts[i].RequestMessage.Close(); } this.innerContexts.Clear(); } internal IAsyncResult BeginReplyInternal(Message reply, TimeSpan timeout, AsyncCallback callback, object state) { bool needAbort = true; bool needReply = true; try { lock (this.ThisLock) { if (this.ranges == null) { throw Fx.AssertAndThrow("this.ranges != null"); } if (this.Aborted) { needAbort = false; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.GetString(SR.RequestContextAborted))); } if (this.outcomeKnown) { needAbort = false; needReply = false; } else { if ((reply != null) && (this.bufferedReply == null)) this.bufferedReply = reply.CreateBufferedCopy(int.MaxValue); if (!this.channel.PrepareReply(this)) { needAbort = false; needReply = false; } else { this.outcomeKnown = true; } } } if (!needReply) return new ReplyCompletedAsyncResult(callback, state); IAsyncResult result = new ReplyAsyncResult(this, timeout, callback, state); needAbort = false; return result; } finally { if (needAbort) { this.AbortInnerContexts(); this.Abort(); } } } internal void EndReplyInternal(IAsyncResult result) { if (result is ReplyCompletedAsyncResult) { ReplyCompletedAsyncResult.End(result); return; } bool throwing = true; try { ReplyAsyncResult.End(result); this.innerContexts.Clear(); throwing = false; } finally { if (throwing) { this.AbortInnerContexts(); this.Abort(); } } } protected override void OnAbort() { bool outcome; lock (this.ThisLock) { outcome = this.outcomeKnown; this.outcomeKnown = true; } if (!outcome) { this.AbortInnerContexts(); } if (this.channel.ContainsRequest(this.requestSequenceNumber)) { Exception e = new ProtocolException(SR.GetString(SR.ReliableRequestContextAborted)); this.channel.session.OnLocalFault(e, (Message)null, null); } } protected override IAsyncResult OnBeginReply(Message reply, TimeSpan timeout, AsyncCallback callback, object state) { return this.BeginReplyInternal(reply, timeout, callback, state); } protected override void OnClose(TimeSpan timeout) { // ReliableRequestContext.Close() relies on base.Close() to call reply if reply is not initiated. if (!this.ReplyInitiated) this.OnReply(null, timeout); } protected override void OnEndReply(IAsyncResult result) { this.EndReplyInternal(result); } protected override void OnReply(Message reply, TimeSpan timeout) { this.ReplyInternal(reply, timeout); } internal void ReplyInternal(Message reply, TimeSpan timeout) { bool needAbort = true; try { lock (this.ThisLock) { if (this.ranges == null) { throw Fx.AssertAndThrow("this.ranges != null"); } if (this.Aborted) { needAbort = false; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.GetString(SR.RequestContextAborted))); } if (this.outcomeKnown) { needAbort = false; return; } if ((reply != null) && (this.bufferedReply == null)) this.bufferedReply = reply.CreateBufferedCopy(int.MaxValue); if (!this.channel.PrepareReply(this)) { needAbort = false; return; } this.outcomeKnown = true; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < this.innerContexts.Count; i++) SendReply(this.innerContexts[i], MaskingMode.Handled, ref timeoutHelper); this.innerContexts.Clear(); needAbort = false; } finally { if (needAbort) { this.AbortInnerContexts(); this.Abort(); } } } public void SetAckRanges(SequenceRangeCollection ranges) { if (this.ranges == null) this.ranges = ranges; } public void SetLastReply(Int64 sequenceNumber) { this.replySequenceNumber = sequenceNumber; this.isLastReply = true; if (this.bufferedReply == null) this.bufferedReply = Message.CreateMessage(this.channel.MessageVersion, WsrmFeb2005Strings.LastMessageAction).CreateBufferedCopy(int.MaxValue); } public void SendReply(RequestContext context, MaskingMode maskingMode) { TimeoutHelper timeoutHelper = new TimeoutHelper(this.DefaultSendTimeout); SendReply(context, maskingMode, ref timeoutHelper); } void SendReply(RequestContext context, MaskingMode maskingMode, ref TimeoutHelper timeoutHelper) { Message reply; if (!this.outcomeKnown) { throw Fx.AssertAndThrow("this.outcomeKnown"); } if (this.bufferedReply != null) { reply = this.bufferedReply.CreateMessage(); this.channel.PrepareReplyMessage(this.replySequenceNumber, this.isLastReply, this.ranges, reply); } else { reply = this.channel.CreateAcknowledgement(this.ranges); } this.channel.binder.SetMaskingMode(context, maskingMode); using (reply) { context.Reply(reply, timeoutHelper.RemainingTime()); } context.Close(timeoutHelper.RemainingTime()); } public void SetReplySequenceNumber(Int64 sequenceNumber) { this.replySequenceNumber = sequenceNumber; } class ReplyCompletedAsyncResult : CompletedAsyncResult { public ReplyCompletedAsyncResult(AsyncCallback callback, object state) : base(callback, state) { } } class ReplyAsyncResult : AsyncResult { ReliableRequestContext context; int currentContext; Message reply; TimeoutHelper timeoutHelper; static AsyncCallback replyCompleteStatic = Fx.ThunkCallback(new AsyncCallback(ReplyCompleteStatic)); public ReplyAsyncResult(ReliableRequestContext thisContext, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.timeoutHelper = new TimeoutHelper(timeout); this.context = thisContext; if (this.SendReplies()) { this.Complete(true); } } public static void End(IAsyncResult result) { AsyncResult.End<ReplyAsyncResult>(result); } void HandleReplyComplete(IAsyncResult result) { RequestContext thisInnerContext = this.context.innerContexts[this.currentContext]; try { thisInnerContext.EndReply(result); thisInnerContext.Close(this.timeoutHelper.RemainingTime()); this.currentContext++; } finally { this.reply.Close(); this.reply = null; } } static void ReplyCompleteStatic(IAsyncResult result) { if (result.CompletedSynchronously) return; Exception ex = null; ReplyAsyncResult thisPtr = null; bool complete = false; try { thisPtr = (ReplyAsyncResult)result.AsyncState; thisPtr.HandleReplyComplete(result); complete = thisPtr.SendReplies(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; ex = e; complete = true; } if (complete) thisPtr.Complete(false, ex); } bool SendReplies() { while (this.currentContext < this.context.innerContexts.Count) { if (this.context.bufferedReply != null) { this.reply = this.context.bufferedReply.CreateMessage(); this.context.channel.PrepareReplyMessage( this.context.replySequenceNumber, this.context.isLastReply, this.context.ranges, this.reply); } else { this.reply = this.context.channel.CreateAcknowledgement(this.context.ranges); } RequestContext thisInnerContext = this.context.innerContexts[this.currentContext]; this.context.channel.binder.SetMaskingMode(thisInnerContext, MaskingMode.Handled); IAsyncResult result = thisInnerContext.BeginReply(this.reply, this.timeoutHelper.RemainingTime(), replyCompleteStatic, this); if (!result.CompletedSynchronously) return false; this.HandleReplyComplete(result); } return true; } } } class ReplyHelper { Message asyncMessage; bool canTransfer = true; ReliableReplySessionChannel channel; WsrmMessageInfo info; ReplyProvider replyProvider; RequestContext requestContext; bool throwTimeoutOnWait; InterruptibleWaitObject waitHandle; internal ReplyHelper(ReliableReplySessionChannel channel, ReplyProvider replyProvider, bool throwTimeoutOnWait) { this.channel = channel; this.replyProvider = replyProvider; this.throwTimeoutOnWait = throwTimeoutOnWait; this.waitHandle = new InterruptibleWaitObject(false, this.throwTimeoutOnWait); } object ThisLock { get { return this.channel.ThisLock; } } internal void Abort() { this.Cleanup(true); } void Cleanup(bool abort) { lock (this.ThisLock) { this.canTransfer = false; } if (abort) { this.waitHandle.Abort(this.channel); } else { this.waitHandle.Fault(this.channel); } } internal void Fault() { this.Cleanup(false); } internal void Reply(RequestContext context, WsrmMessageInfo info, TimeSpan timeout, MaskingMode maskingMode) { using (Message message = this.replyProvider.Provide(this.channel, info)) { this.channel.binder.SetMaskingMode(context, maskingMode); context.Reply(message, timeout); } } IAsyncResult BeginReply(TimeSpan timeout, AsyncCallback callback, object state) { lock (this.ThisLock) { this.canTransfer = false; } if (this.requestContext == null) { return new ReplyCompletedAsyncResult(callback, state); } this.asyncMessage = this.replyProvider.Provide(this.channel, info); bool throwing = true; try { this.channel.binder.SetMaskingMode(this.requestContext, MaskingMode.Handled); IAsyncResult result = this.requestContext.BeginReply(this.asyncMessage, timeout, callback, state); throwing = false; return result; } finally { if (throwing) { this.asyncMessage.Close(); this.asyncMessage = null; } } } void EndReply(IAsyncResult result) { ReplyCompletedAsyncResult completedResult = result as ReplyCompletedAsyncResult; if (completedResult != null) { completedResult.End(); return; } try { this.requestContext.EndReply(result); } finally { if (this.asyncMessage != null) { this.asyncMessage.Close(); } } } internal bool TransferRequestContext(RequestContext requestContext, WsrmMessageInfo info) { RequestContext oldContext = null; WsrmMessageInfo oldInfo = null; lock (this.ThisLock) { if (!this.canTransfer) { return false; } else { oldContext = this.requestContext; oldInfo = this.info; this.requestContext = requestContext; this.info = info; } } this.waitHandle.Set(); if (oldContext != null) { oldInfo.Message.Close(); oldContext.Close(); } return true; } internal void UnblockWaiter() { this.TransferRequestContext(null, null); } internal void WaitAndReply(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.waitHandle.Wait(timeoutHelper.RemainingTime()); lock (this.ThisLock) { this.canTransfer = false; if (this.requestContext == null) { return; } } this.Reply(this.requestContext, this.info, timeoutHelper.RemainingTime(), MaskingMode.Handled); } internal IAsyncResult BeginWaitAndReply(TimeSpan timeout, AsyncCallback callback, object state) { OperationWithTimeoutBeginCallback[] beginOperations = new OperationWithTimeoutBeginCallback[] { new OperationWithTimeoutBeginCallback (this.waitHandle.BeginWait), new OperationWithTimeoutBeginCallback (this.BeginReply), }; OperationEndCallback[] endOperations = new OperationEndCallback[] { new OperationEndCallback (this.waitHandle.EndWait), new OperationEndCallback(this.EndReply), }; return OperationWithTimeoutComposer.BeginComposeAsyncOperations(timeout, beginOperations, endOperations, callback, state); } internal void EndWaitAndReply(IAsyncResult result) { OperationWithTimeoutComposer.EndComposeAsyncOperations(result); } class ReplyCompletedAsyncResult : CompletedAsyncResult { internal ReplyCompletedAsyncResult(AsyncCallback callback, object state) : base(callback, state) { } public void End() { AsyncResult.End<ReplyCompletedAsyncResult>(this); } } } abstract class ReplyProvider { internal abstract Message Provide(ReliableReplySessionChannel channel, WsrmMessageInfo info); } class CloseSequenceReplyProvider : ReplyProvider { static CloseSequenceReplyProvider instance = new CloseSequenceReplyProvider(); CloseSequenceReplyProvider() { } static internal ReplyProvider Instance { get { if (instance == null) { instance = new CloseSequenceReplyProvider(); } return instance; } } internal override Message Provide(ReliableReplySessionChannel channel, WsrmMessageInfo requestInfo) { Message message = WsrmUtilities.CreateCloseSequenceResponse(channel.MessageVersion, requestInfo.CloseSequenceInfo.MessageId, channel.session.InputID); channel.AddAcknowledgementHeader(message); return message; } } class TerminateSequenceReplyProvider : ReplyProvider { static TerminateSequenceReplyProvider instance = new TerminateSequenceReplyProvider(); TerminateSequenceReplyProvider() { } static internal ReplyProvider Instance { get { if (instance == null) { instance = new TerminateSequenceReplyProvider(); } return instance; } } internal override Message Provide(ReliableReplySessionChannel channel, WsrmMessageInfo requestInfo) { Message message = WsrmUtilities.CreateTerminateResponseMessage(channel.MessageVersion, requestInfo.TerminateSequenceInfo.MessageId, channel.session.InputID); channel.AddAcknowledgementHeader(message); return message; } } } }
// // X509CertificateExtensions.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Text; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.X509; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto.Digests; namespace MimeKit.Cryptography { /// <summary> /// X509Certificate extension methods. /// </summary> /// <remarks> /// A collection of useful extension methods for an <see cref="Org.BouncyCastle.X509.X509Certificate"/>. /// </remarks> public static class X509CertificateExtensions { /// <summary> /// Gets the issuer name info. /// </summary> /// <remarks> /// For a list of available identifiers, see <see cref="Org.BouncyCastle.Asn1.X509.X509Name"/>. /// </remarks> /// <returns>The issuer name info.</returns> /// <param name="certificate">The certificate.</param> /// <param name="identifier">The name identifier.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static string GetIssuerNameInfo (this X509Certificate certificate, DerObjectIdentifier identifier) { if (certificate == null) throw new ArgumentNullException ("certificate"); // FIXME: GetValueList() should be fixed to return IList<string> var list = certificate.IssuerDN.GetValueList (identifier); if (list.Count == 0) return null; return (string) list[0]; } /// <summary> /// Gets the issuer name info. /// </summary> /// <remarks> /// For a list of available identifiers, see <see cref="Org.BouncyCastle.Asn1.X509.X509Name"/>. /// </remarks> /// <returns>The issuer name info.</returns> /// <param name="certificate">The certificate.</param> /// <param name="identifier">The name identifier.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static string GetSubjectNameInfo (this X509Certificate certificate, DerObjectIdentifier identifier) { if (certificate == null) throw new ArgumentNullException ("certificate"); // FIXME: GetValueList() should be fixed to return IList<string> var list = certificate.SubjectDN.GetValueList (identifier); if (list.Count == 0) return null; return (string) list[0]; } /// <summary> /// Gets the common name of the certificate. /// </summary> /// <remarks> /// Gets the common name of the certificate. /// </remarks> /// <returns>The common name.</returns> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static string GetCommonName (this X509Certificate certificate) { return certificate.GetSubjectNameInfo (X509Name.CN); } /// <summary> /// Gets the subject name of the certificate. /// </summary> /// <remarks> /// Gets the subject name of the certificate. /// </remarks> /// <returns>The subject name.</returns> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static string GetSubjectName (this X509Certificate certificate) { return certificate.GetSubjectNameInfo (X509Name.Name); } /// <summary> /// Gets the subject email address of the certificate. /// </summary> /// <remarks> /// The email address component of the certificate's Subject identifier is /// sometimes used as a way of looking up certificates for a particular /// user if a fingerprint is not available. /// </remarks> /// <returns>The subject email address.</returns> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static string GetSubjectEmailAddress (this X509Certificate certificate) { return certificate.GetSubjectNameInfo (X509Name.EmailAddress); } /// <summary> /// Gets the fingerprint of the certificate. /// </summary> /// <remarks> /// A fingerprint is a SHA-1 hash of the raw certificate data and is often used /// as a unique identifier for a particular certificate in a certificate store. /// </remarks> /// <returns>The fingerprint.</returns> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static string GetFingerprint (this X509Certificate certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); var encoded = certificate.GetEncoded (); var fingerprint = new StringBuilder (); var sha1 = new Sha1Digest (); var data = new byte[20]; sha1.BlockUpdate (encoded, 0, encoded.Length); sha1.DoFinal (data, 0); for (int i = 0; i < data.Length; i++) fingerprint.Append (data[i].ToString ("x2")); return fingerprint.ToString (); } internal static X509KeyUsageFlags GetKeyUsageFlags (bool[] usage) { var flags = X509KeyUsageFlags.None; if (usage != null) { if (usage[(int) X509KeyUsageBits.DigitalSignature]) flags |= X509KeyUsageFlags.DigitalSignature; if (usage[(int) X509KeyUsageBits.NonRepudiation]) flags |= X509KeyUsageFlags.NonRepudiation; if (usage[(int) X509KeyUsageBits.KeyEncipherment]) flags |= X509KeyUsageFlags.KeyEncipherment; if (usage[(int) X509KeyUsageBits.DataEncipherment]) flags |= X509KeyUsageFlags.DataEncipherment; if (usage[(int) X509KeyUsageBits.KeyAgreement]) flags |= X509KeyUsageFlags.KeyAgreement; if (usage[(int) X509KeyUsageBits.KeyCertSign]) flags |= X509KeyUsageFlags.KeyCertSign; if (usage[(int) X509KeyUsageBits.CrlSign]) flags |= X509KeyUsageFlags.CrlSign; if (usage[(int) X509KeyUsageBits.EncipherOnly]) flags |= X509KeyUsageFlags.EncipherOnly; if (usage[(int) X509KeyUsageBits.DecipherOnly]) flags |= X509KeyUsageFlags.DecipherOnly; } return flags; } /// <summary> /// Gets the key usage flags. /// </summary> /// <remarks> /// The X.509 Key Usage Flags are used to determine which operations a certificate /// may be used for. /// </remarks> /// <returns>The key usage flags.</returns> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static X509KeyUsageFlags GetKeyUsageFlags (this X509Certificate certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); return GetKeyUsageFlags (certificate.GetKeyUsage ()); } internal static bool IsDelta (this X509Crl crl) { var critical = crl.GetCriticalExtensionOids (); return critical.Contains (X509Extensions.DeltaCrlIndicator.Id); } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System; using Stratus.Editor; namespace Stratus { namespace Editor { /// <summary> /// Handles splitting a given GUI rect into multiple rects that can be /// resized and moved by an user /// </summary> public class GUISplitter { //----------------------------------------------------------------------/ // Classes //----------------------------------------------------------------------/ /// <summary> /// A split represents a drawable area /// </summary> public class Split { //--------------------------------------------------------------------/ // Properties //--------------------------------------------------------------------/ public Vector2 Position { get; set; } public float Scale { get; private set; } public float Width { get; set; } public float Height { get; set; } public Vector2 ScrollPosition { get; set; } public Vector2 Size { get { return new Vector2(Width, Height); } set { Width = value.x; Height = value.y; } } public Vector2 MinimumSize { get; private set; } public float MinimumScale { get { return 0.4f; } } //--------------------------------------------------------------------/ // Fields //--------------------------------------------------------------------/ public System.Action<Rect> OnDraw; private bool IsInitialized { get; set; } //--------------------------------------------------------------------/ // Methods //--------------------------------------------------------------------/ public Split(float scale, Action<Rect> onDraw) { this.Scale = scale; this.OnDraw = onDraw; } public void Initialize(Vector2 position, OrientationType orientation) { if (IsInitialized) throw new Exception("This split has already been initialized!"); this.Width = (orientation == OrientationType.Horizontal ? Scale * position.x : position.x); this.Height = (orientation == OrientationType.Vertical ? Scale * position.y : position.y); this.MinimumSize = new Vector2(Width * MinimumScale, Height * MinimumScale); IsInitialized = true; } } // I can do immediate mode if I ask the user to pass in a struct // containing the splits; that way they can save them on their side? //public class SplitGroup //{ // private List<Split> Splits; // public void Add(float scale, Action<Rect> onDraw) //} /// <summary> /// A splitter manages the sizes (w/h) of adjacent splits /// </summary> private class Splitter { public bool Dragging { get; set; } } public enum OrientationType { Horizontal, Vertical } //----------------------------------------------------------------------/ // Properties //----------------------------------------------------------------------/ /// <summary> /// The window this splitter belongs to /// </summary> private EditorWindow Window { get; set; } /// <summary> /// The initial position of the editor window (used for keeping /// scale relative as the window size changes. /// </summary> private Vector2 InitialWindowSize { get; set; } /// <summary> /// The initial position of the splitter area within the window /// (before being scaled) /// </summary> private Rect InitialPosition { get; set; } /// <summary> /// Keeps the scale of the splits a constant relative by comparing /// the initial window scale with the current one /// </summary> private Vector2 SizeModifier { get { float width = Window.position.width / InitialWindowSize.x; float height = Window.position.height / InitialWindowSize.y; return new Vector2(width, height); } } /// <summary> /// How much of the splitter's total rect has been filled /// by all the splits In the initialization step, after /// all splits have been added, this is asserted to be 100% (1f) /// </summary> private float FillPercentage { get; set; } /// <summary> /// Whether the Spliter has been initialized. It does the initialization /// procedure on the very first update (rather than construction) for /// reasons /// </summary> private bool IsInitialized { get; set; } //----------------------------------------------------------------------/ // Fields //----------------------------------------------------------------------/ // Lists, ho! private OrientationType Orientation; private List<Split> Splits = new List<Split>(); private List<Splitter> Splitters = new List<Splitter>(); private static float SplitterWidth = 5f; // Functions private System.Action<GUILayoutOption[]> BeginControlGroupFunction; private System.Action EndControlGroupFunction; private Func<float, GUILayoutOption> DefaultScaleControlFunction, MinScaleControlFunction, MaxScaleControlFunction; //private Func<bool, GUILayoutOption> ExpandControlFunction; MouseCursor CursorType; //----------------------------------------------------------------------/ // Methods: Constructor //----------------------------------------------------------------------/ public GUISplitter(EditorWindow window, OrientationType type) { this.Window = window; this.Orientation = type; switch (this.Orientation) { case OrientationType.Horizontal: BeginControlGroupFunction = GUILayout.BeginHorizontal; EndControlGroupFunction = GUILayout.EndHorizontal; DefaultScaleControlFunction = GUILayout.Width; MinScaleControlFunction = GUILayout.MinWidth; MaxScaleControlFunction = GUILayout.MaxWidth; //ExpandControlFunction = GUILayout.ExpandHeight; CursorType = MouseCursor.ResizeHorizontal; break; case OrientationType.Vertical: BeginControlGroupFunction = GUILayout.BeginVertical; EndControlGroupFunction = GUILayout.EndVertical; DefaultScaleControlFunction = GUILayout.Height; MinScaleControlFunction = GUILayout.MinHeight; MaxScaleControlFunction = GUILayout.MaxHeight; //ExpandControlFunction = GUILayout.ExpandWidth; CursorType = MouseCursor.ResizeVertical; break; } } private void Initialize(Rect position) { InitialWindowSize = Window.position.size; InitialPosition = position; //Trace.Script("Splitter position = " + position); // If the percentages alloted to all splits is not equal to 1 (100%), // throw an error! if (FillPercentage != 1f) { Window.Close(); throw new Exception("The scale percentages for all splits must all add up to 1"); } // Set the intiial size of all splits foreach (var split in Splits) split.Initialize(position.size, this.Orientation); // Add a splitter for every 2 splits var numSplitters = Splits.Count - 1; for (var i = 0; i < numSplitters; ++i) { // Use the initial position of the second split to start the splitter var secondSplit = Splits[i + 1]; var initialPosition = secondSplit.Size; Splitters.Add(new Splitter()); //Trace.Script("Splitter at " + initialPosition); } IsInitialized = true; } //----------------------------------------------------------------------/ // Methods: ... //----------------------------------------------------------------------/ /// <summary> /// Adds a split, given an initial possition and a function that will be /// called to draw its elements inside it /// </summary> /// <param name="initialPosition"></param> /// <param name="scale">The initial scale of this split, a value between 0 and 1</param> /// <param name="onDraw"></param> public void Add(float scale, System.Action<Rect> onDraw) { // Keep track of the percentages allotted to all splits FillPercentage += scale; var split = new Split(scale, onDraw); Splits.Add(split); } //----------------------------------------------------------------------/ // Methods: GUI //----------------------------------------------------------------------/ public void Draw(Rect position) { if (!IsInitialized) Initialize(position); //var info = "Window Position = " + Window.position + ", Splitter Position = " + position; //Trace.Script(info); // Grab the current event: we will check if the user // wants to drag one of the splits var currentEvent = UnityEngine.Event.current; var currentMousePosition = currentEvent.mousePosition; // Record the current positions for each split var currentPos = new Vector2(); GUILayout.BeginArea(position); BeginControlGroupFunction(null); // For every splitter, draw the splits to its sides for (var i = 0; i < Splitters.Count; ++i) { var currentSplitter = Splitters[i]; var currentSplit = Splits[i]; var nextSplit = Splits[i + 1]; // Draw the current split DrawSplit(currentSplit, currentPos); // Update the position for the next split if (Orientation == OrientationType.Horizontal) currentPos.x += currentSplit.Width; else if (Orientation == OrientationType.Vertical) currentPos.y += currentSplit.Height; // Draw the splitter //var splitterRect = new Rect(currentPos, CalculateSplitterSize(position)); var splitterRect = DrawSplitter(currentSplitter, currentPos, position); splitterRect.y += position.y; //EditorGUIUtility.AddCursorRect(splitterRect, CursorType); // Now handle events for this splitter if (currentEvent != null && currentEvent.type != EventType.Used) { switch (currentEvent.type) { case EventType.MouseDown: //Trace.Script("Clicked on " + currentMousePosition); if (splitterRect.Contains(currentMousePosition)) { currentSplitter.Dragging = true; currentEvent.Use(); } break; case EventType.MouseDrag: if (currentSplitter.Dragging) { // If the size of the splits was modified (by the splitter) // we will repaint the window next frame if (ResizeSplitter(currentSplit, nextSplit, currentEvent.delta)) Window.Repaint(); } break; case EventType.MouseUp: currentSplitter.Dragging = false; break; } } } // At the end, draw the last split var lastSplit = Splits[Splits.Count - 1]; DrawSplit(lastSplit, currentPos); EndControlGroupFunction(); GUILayout.EndArea(); } private Vector2 CalculateSplitterSize(Vector2 position) { var width = (this.Orientation == OrientationType.Horizontal ? SplitterWidth : position.x); var height = (this.Orientation == OrientationType.Vertical ? SplitterWidth : position.y); return new Vector2(width, height); } private void DrawSplit(Split split, Vector2 position) { var scaledPosition = new Rect(position.x * SizeModifier.x, position.y * SizeModifier.y, split.Width * SizeModifier.x, split.Height * SizeModifier.y); split.Position = position; split.ScrollPosition = GUILayout.BeginScrollView(split.ScrollPosition, ScaleControl(DefaultScaleControlFunction, scaledPosition.size), ScaleControl(MaxScaleControlFunction, scaledPosition.size), ScaleControl(MinScaleControlFunction, scaledPosition.size) ); split.OnDraw(scaledPosition); GUILayout.EndScrollView(); } private Rect DrawSplitter(Splitter splitter, Vector2 nextSplitPosition, Rect position) { var x = (this.Orientation == OrientationType.Horizontal ? nextSplitPosition.x - (SplitterWidth / 2f) : nextSplitPosition.x); var y = (this.Orientation == OrientationType.Vertical ? nextSplitPosition.y - (SplitterWidth / 2f): nextSplitPosition.y); var width = (this.Orientation == OrientationType.Horizontal ? SplitterWidth : position.width); var height = (this.Orientation == OrientationType.Vertical ? SplitterWidth : position.height); x *= SizeModifier.x; y *= SizeModifier.y; if (Orientation == OrientationType.Horizontal) GUILayout.Box(GUIContent.none, StratusGUIStyles.editorLine, GUILayout.Width(1f), GUILayout.Height(height)); else if (Orientation == OrientationType.Vertical) GUILayout.Box(GUIContent.none, StratusGUIStyles.editorLine, GUILayout.Width(width), GUILayout.Height(1f)); //GUILayout.Box(GUIContent.none, Styles.EditorLine, GUILayout.Width(width), GUILayout.Height(1f)); //var splitterRect = GUILayoutUtility.GetLastRect(); var splitterRect = new Rect(x, y, width, height); EditorGUIUtility.AddCursorRect(splitterRect, CursorType); return splitterRect; } GUILayoutOption ScaleControl(Func<float, GUILayoutOption> func, Vector2 size) { if (this.Orientation == OrientationType.Horizontal) return func(size.x); else return func(size.y); } private bool ResizeSplitter(Split currentSplit, Split nextSplit, Vector2 mouseDelta) { if (this.Orientation == OrientationType.Horizontal) { mouseDelta.y = 0f; } else if (this.Orientation == OrientationType.Vertical) { mouseDelta.x = 0f; } // Maintain a minimum size for this split and the next var currentSplitModifiedSize = currentSplit.Size + mouseDelta; if (currentSplitModifiedSize.x < currentSplit.MinimumSize.x || currentSplitModifiedSize.y < currentSplit.MinimumSize.y) return false; var nextSplitModifiedSize = nextSplit.Size - mouseDelta; if (nextSplitModifiedSize.x < nextSplit.MinimumSize.x || nextSplitModifiedSize.y < nextSplit.MinimumSize.y) return false; // Modify the width of this split, and the next one currentSplit.Size = currentSplitModifiedSize; nextSplit.Size = nextSplitModifiedSize; return true; } /// <summary> /// How the split allocation will be determined /// </summary> public enum FillType { Relative, Absolute } private class SplitterFrame { public SplitterFrame(GUISplitter splitter, Rect position) { this.Splitter = splitter; this.Position = position; } public GUISplitter Splitter { get; private set; } public Rect Position { get; private set; } } private static Stack<SplitterFrame> FrameStack = new Stack<SplitterFrame>(); private static SplitterFrame CurrentFrame { get { return FrameStack.Peek(); } } //private static Rect CurrentPosition { get; set; } public static void BeginHorizontalSplitGroup(EditorWindow window, Rect position) { FrameStack.Push(new SplitterFrame(new GUISplitter(window, OrientationType.Horizontal), position)); } public static float AddSplit(float scale, System.Action<Rect> onDraw) { throw new NotImplementedException(); //CurrentFrame.Splitter.Add(scale, onDraw); } public static void EndHorizontalSplitGroup() { CurrentFrame.Splitter.Draw(CurrentFrame.Position); FrameStack.Pop(); } } } } //public class GUISplitterExampleTwo : EditorWindow //{ // GUISplitter Splitter; // // Set the splitter position within the window // Rect SplitterPosition // { // get // { // var splitterX = 0f; // this.position.width / 2f; ; // var splitterY = this.position.height / 2f; // var splitterWidth = this.position.width; // / 2f; // var splitterHeight = this.position.height / 2f; // return new Rect(splitterX, splitterY, splitterWidth, splitterHeight); // } // } // [MenuItem("GUI/GUISplitter Two")] // static void Init() // { // GUISplitterExampleTwo window = GetWindow<GUISplitterExampleTwo>(); // } // private void OnEnable() // { // this.position = new Rect(Screen.currentResolution.width / 2, // Screen.currentResolution.height / 2, // 600, // 400); // Splitter = new GUISplitter(this, GUISplitter.OrientationType.Horizontal); // Splitter.Add(0.25f, Split); // Splitter.Add(0.25f, Split); // Splitter.Add(0.5f, Split); // } // private void OnGUI() // { // Splitter.Draw(SplitterPosition); // } // void Split(Rect position) // { // GUILayout.Box("Rect = " + position, // GUI.skin.box, // GUILayout.ExpandWidth(true), // GUILayout.ExpandHeight(true)); // } //}
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using OpenADK.Library.Global; using OpenADK.Library.Tools.Mapping; using OpenADK.Library.Tools.XPath; namespace OpenADK.Library { /// <summary> The abstract base class for all root-level SIF Data Object classes. /// SifDataObject encapsulates top-level data objects defined by SIF Working /// Groups, including <c>&lt;StudentPersonal&gt;</c>, /// <c>&lt;LibraryPatronStatus&gt;</c>, <c>&lt;BusInfo&gt;</c>, /// and so on. /// /// /// <b>Setting Elements &amp; Attributes of a SIF Data Object</b> /// /// There are two general approaches to getting and setting the element/attribute /// values of a SifDataObject. First, you can call the getXxx and setXxx methods /// of the subclass to manipulate the elements and attributes in an object-oriented /// fashion. For example, to assign a first and last name to a StudentPersonal /// object, create a Name object and attach it to the StudentPersonal with the /// setName method: /// /// <c>&nbsp;&nbsp;&nbsp;&nbsp;// Build a StudentPersonal object<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;StudentPersonal sp = new StudentPersonal();<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setRefId( Adk.makeGUID() );<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setName( new Name( "Davis", "Alan" ) );</br> /// </c> /// /// The second approach to getting and setting element/attribute values is to /// call the <c>setElementOrAttribute</c> and <c>getElementOrAttribute</c> /// methods, which accept an XPath-like query string that identifies a specific /// SIF element or attribute relative to the SifDataObject. (See also the /// Mappings class for a higher-level mechanism that performs much of the work /// involved in dynamically mapping application fields to SIF elements and /// attributes). /// /// <c>&nbsp;&nbsp;&nbsp;&nbsp;// Build a StudentPersonal object<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;StudentPersonal sp = new StudentPersonal();<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setRefId( Adk.makeGUID() );<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setElementOrAttribute( "Name[@Type='02']/LastName", "Davis", null );<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setElementOrAttribute( "Name[@Type='02']/FirstName", "Brian", null );<br/> /// </c> /// /// XPath-like query strings can include substitution tokens and can even call /// static .Net methods. For example, the following uses name/value pairs defined /// in a Map to select the first and last name. The static <c>capitalize</c> /// method of the "MyFunctions" class is called to capitalize the last name: /// /// /// <c>&nbsp;&nbsp;&nbsp;&nbsp;// Prepare a table with field values<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;HashMap values = new HashMap();<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;values.put( "LASTNAME", "Davis" );<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;values.put( "FIRSTNAME", "Brian" );<br/><br/> /// &nbsp;&nbsp;&nbsp;&nbsp;// Build a StudentPersonal object<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;StudentPersonal sp = new StudentPersonal();<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setRefId( Adk.makeGUID() );<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setElementOrAttribute( "Name[@Type='02']/[email protected]( $(LASTNAME) )", null, values );<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;sp.setElementOrAttribute( "Name[@Type='02']/FirstName=$(FIRSTNAME)", null, values );<br/> /// </c> /// /// <b>Object Type</b> /// /// The <c>getObjectType</c> method returns the an ElementDef constant /// from the SifDtd class that identifies the SIF Data Object. The the /// <c>getObjectTag</c> convenience method returns the element tag name of /// the object for the version of SIF associated with the instance. For example, /// /// /// <c> /// &nbsp;&nbsp;&nbsp;&nbsp;// Lookup a Topic instance<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;SifDataObject data = new SifDataObject( Adk.Dtd().STUDENTPERSONAL );<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;TopicFactory factory = myAgent.getTopicFactory();<br/> /// &nbsp;&nbsp;&nbsp;&nbsp;Topic t = factory.getInstance( data.getObjectType() );<br/> /// </c> /// /// /// <b>SIF Version</b> /// /// Each SifDataObject is associated with a SifVersion instance. The version /// is used by the SifWriter class when rendering the object as XML. By default, /// it is assumed to be the version of SIF in effect for this agent; that is, /// the value passed to the <c>Adk.initialize</c> method. However, to /// support mixed environments where an agent may send and receive objects /// using different versions of SIF, the version may be changed by the Adk /// during message processing: /// /// <ul> /// <li> /// When constructing a SifDataObject instance from parsed XML content, /// the SifParser class sets its SifVersion to the version identified by /// the <i>xmlns</i> attribute of the <c>&lt;SIF_Message&gt;</c> /// envelope.<br/><br/> /// </li> /// <li> /// The version may be changed by the Adk prior to rendering a /// SifDataObject as XML. For example, when your agent responds to a /// &lt;SIF_Request&gt; message that specifically identifies a version /// to use for the results, the Adk will change the version of the /// SifDataObject when generating &lt;SIF_Response&gt; messages. Once /// messages have been generated, it restores the SifVersion to its /// original setting. /// <br/><br/> /// </li> /// <li> /// An agent may manually change the SifVersion associated with a /// SifDataObject by calling the <c>setSIFVersion</c> method. /// </li> /// </ul> /// /// /// </summary> /// <author> Eric Petersen /// </author> /// <version> Adk 1.0 /// </version> [Serializable] public abstract class SifDataObject : SifKeyedElement //, ISerializable { /// <summary> Constructs a SifDataObject</summary> /// <param name="version">The version of SIF that should be used to render this /// SifDataObject and its child elements. If this SifDataObject is the /// result of parsing a SIF message, this is the version of SIF /// identified by the message envelope. /// /// </param> /// <param name="def">The IElementDef that provides metadata for this element /// </param> public SifDataObject( SifVersion version, IElementDef def ) : base( def ) { fVersion = version; } /// <summary> /// This object does not define a key field /// </summary> /// <returns></returns> public override IElementDef[] KeyFields { get { return new IElementDef[0]; } } /// <value> A SifVersion /// </value> /// <summary> Changes the version of SIF that should be used to render this SifDataObject /// and its children. The calling thread may change the way a SifDataObject /// is rendered by calling this method. It is recommended the version be /// restored to its original value after rendering is completed. /// </summary> public override SifVersion SifVersion { get { return fVersion; } set { fVersion = value; } } /// <summary> Gets the ElementDef that identifies this SIF Data Object type</summary> /// <returns> An ElementDef constant defined by the SifDtd class /// </returns> public virtual IElementDef ObjectType { get { return ElementDef; } } /// <summary> Gets the element tag name of this object</summary> /// <returns> The element tag for the version of SIF associated with the object /// </returns> public virtual string ObjectTag { get { return ElementDef.Tag( fVersion ); } } /// <summary> Returns the XML representation of this SIF Data Object</summary> public virtual string ToXml() { using ( StringWriter buffer = new StringWriter() ) { SifWriter w = new SifWriter( buffer ); w.Write( this ); w.Flush(); return buffer.ToString(); } } ///// <summary>Gets or Sets all SIF_ExtendedElements/SIF_ExtendedElement children of this object.</summary> ///// <value>An array of SIF_ExtendedElement instances. If no SIF_ExtendedElements child element was ///// found, an empty array is returned. Setting this property replaces all items in the list ///// </value> ///// <remarks> ///// Since Adk 1.5 ///// </remarks> //public virtual SIF_ExtendedElement[] SIFExtendedElements //{ // get // { // if ( SifDtd.SIF_EXTENDEDELEMENTS == null ) // { // return new SIF_ExtendedElement[0]; // } // SIF_ExtendedElements container = ( SIF_ExtendedElements ) GetChild( SifDtd.SIF_EXTENDEDELEMENTS ); // if ( container == null ) // { // return new SIF_ExtendedElement[0]; // } // SifElement[] ch = container.GetChildren(); // SIF_ExtendedElement[] arr = new SIF_ExtendedElement[ch.Length]; // for ( int i = 0; i < arr.Length; i++ ) // { // arr[ i ] = ( SIF_ExtendedElement ) ch[ i ]; // } // return arr; // } // set // { // SIFExtendedElementsContainer.SetSIF_ExtendedElements( value ); // } //} /// <summary> The version of SIF that should be used to render this SifDataObject and /// its child elements. If this SifDataObject is the result of parsing a SIF /// message, this is the version of SIF identified by the message envelope. /// The version is initially set by the constructor but may be changed at /// any time by the <c>setVersion</c> method. /// </summary> protected internal SifVersion fVersion; /// <summary> Gets this object's <i>RefId</i>. /// /// Most SIF Data Object elements define a RefId value to uniquely identify /// the object. However, some objects such as SIF_ZoneStatus and StudentMeal /// do not have a RefId. For these, a blank string will be returned. /// /// /// </summary> /// <returns> The value of this object's <i>RefId</i> element /// </returns> public virtual string RefId { get { return ""; } set { throw new AdkNotSupportedException ( "Cannot set RefID on object of type " + GetType().FullName ); } } /// <summary>Sets an element or attribute value identified by an XPath-like query string.</summary> /// <remarks> /// NOTE: This method makes calls to SIFXPathContext. If multiple calls to /// <c>setElementOrAttribute</c> are being done, it is much more efficient to create /// a new <c>SIFXPathContext</c> by calling <c>SIFXPathContext.newInstance(sdo)</c> and then /// calling <c>.setElementorAttributeon</c> on that SifXPathContext instance /// </remarks> /// <param name="xpath">An XPath-like query string that identifies identifies /// the element or attribute to set. The string must reference elements /// and attributes by their <i>version-independent</i> names. /// </param> /// <param name="valu">The value of the element or attribute /// </param> public virtual void SetElementOrAttribute( string xpath, string valu ) { SifVersion = Adk.SifVersion; SifXPathContext spc = SifXPathContext.NewSIFContext( this ); spc.SetElementOrAttribute( xpath, valu ); } /// <summary>Sets an element or attribute value identified by an XPath-like query string.</summary> /// <remarks> /// NOTE: This method makes calls to SIFXPathContext. If multiple calls to /// <c>setElementOrAttribute</c> are being done, it is much more efficient to create /// a new <c>SifXPathContext</c> by calling <c>SifXPathContext.NewInstance(sdo)</c> and then /// calling <c>.SetElementorAttributeon</c> on that SifXPathContext instance /// </remarks> /// <param name="xpath">An XPath-like query string that identifies the element or /// attribute to set. The string must reference elements and attributes /// by their <i>version-independent</i> names. /// </param> /// <param name="valu">The value to assign to the element or attribute if the /// query string does not set a value; may be null /// </param> /// <param name="adaptor"> A data source may be used for variable /// substitutions within the query string /// </param> public virtual void SetElementOrAttribute( string xpath, string valu, IFieldAdaptor adaptor ) { SifVersion = Adk.SifVersion; SifXPathContext spc = SifXPathContext.NewSIFContext( this ); if ( adaptor is IXPathVariableLibrary ) { spc.AddVariables( "", (IXPathVariableLibrary) adaptor ); } spc.SetElementOrAttribute( xpath, valu ); } /// <summary>Sets an element or attribute value identified by an XPath-like query string.</summary> /// <remarks> /// NOTE: This method makes calls to SIFXPathContext. If multiple calls to /// <c>setElementOrAttribute</c> are being done, it is much more efficient to create /// a new <c>SifXPathContext</c> by calling <c>SifXPathContext.NewInstance(sdo)</c> and then /// calling <c>.SetElementorAttributeon</c> on that SifXPathContext instance /// </remarks> /// <param name="xpath">An XPath-like query string that identifies the element or /// attribute to set. The string must reference elements and attributes /// by their <i>version-independent</i> names. /// </param> /// <param name="valu">The value to assign to the element or attribute if the /// query string does not set a value; may be null /// </param> /// <param name="valueBuilder">a ValueBuilder implementation that evaluates /// expressions in XPath-like query strings using name/value pairs in /// the <i>variables</i> map /// </param> public virtual void SetElementOrAttribute( string xpath, string valu, IValueBuilder valueBuilder ) { valu = valueBuilder == null ? valu : valueBuilder.Evaluate( valu ); SetElementOrAttribute( xpath, valu ); } /// <summary>Gets an element or attribute value identified by an XPath-like query string.</summary> /// NOTE: This method makes calls to SIFXPathContext. If multiple calls to /// <c>GetElementOrAttribute</c> are being done, it is much more efficient to create /// a new <c>SifXPathContext</c> by calling <c>SifXPathContext.NewInstance(sdo)</c> and then /// calling <c>.GetElementorAttributeon</c> on that SifXPathContext instance /// </remarks> /// <param name="xpath">An XPath-like query string that identifies the element or /// attribute to get. The string must reference elements and attributes /// by their <i>version-independent</i> names. /// </param> /// <returns> An Element instance encapsulating the element or attribute if /// found. If not found, <c>null</c> is returned. To retrieve the /// value of the Element, call its <c>getTextValue</c> method. /// </returns> public virtual Element GetElementOrAttribute( string xpath ) { // XPath Navigation using this API causes the object to have to // remember the SIF Version being evaluated if (fVersion == null) { fVersion = Adk.SifVersion; } SifXPathContext spc = SifXPathContext.NewSIFContext( this ); return spc.GetElementOrAttribute( xpath ); } //* Sets the SIF_ExtendedElements container for this object.<P> //* Normally, agents can just call {@link #addSIFExtendedElement(String, String)}, //* which automatically creates a SIF_ExtendedElements container, if necessary and //* allows for easy addition of SIF_ExtendedElements.<p> //* This method is provided as a convenience to agents that need more control or //* wish to set or completely replace the existing SIF_ExtendedElements container. public void AddSifExtendedElementsContainer( SIF_ExtendedElements container ) { RemoveChild( GlobalDTD.SIF_EXTENDEDELEMENTS ); AddChild( container ); } /** * Sets an array of <code>SIF_ExtendedElement</code> objects. All existing * <code>SIF_ExtendedElement</code> instances * are removed and replaced with this list. Calling this method with the * parameter value set to null removes all <code>SIF_ExtendedElements</code>. * @param elements The SIF_Extended elements instances to set on this object * * @since ADK 1.5 */ //public void SetSifExtendedElements(SIF_ExtendedElement[] elements) //{ // SIF_ExtendedElements = elements; //} /// <summary> Sets a SIF_ExtendedElement.</summary> /// <param name="name">The element name /// </param> /// <param name="valu">The element value /// /// @since Adk 1.5 /// </param> public virtual void AddSIFExtendedElement( string name, string valu ) { if ( GlobalDTD.SIF_EXTENDEDELEMENTS == null || name == null || valu == null ) { return; } SIF_ExtendedElement ele = null; // Lookup existing SIF_ExtendedElements container SIF_ExtendedElements see = (SIF_ExtendedElements) GetChild( GlobalDTD.SIF_EXTENDEDELEMENTS ); if ( see == null ) { // Create a new SIF_ExtendedElements container see = new SIF_ExtendedElements(); AddChild( see ); } else { // Lookup existing SIF_ExtendedElement with this name ele = see[name]; } // Create/update SIF_ExtendedElement if ( ele == null ) { ele = new SIF_ExtendedElement( name, valu ); see.AddChild( ele ); } else { ele.TextValue = valu; } } /// <summary> Gets the SIF_ExtendedElement with the specified Name attribute.</summary> /// <param name="name">The value of the SIF_ExtendedElement/@Name attribute to search for /// </param> /// <returns> The SIF_ExtendedElement that has a Name attribute matching the /// <c>name</c> parameter, or null if no such element exists /// <since>ADK 1.5</since> /// </returns> public virtual SIF_ExtendedElement GetSIFExtendedElement( string name ) { if ( GlobalDTD.SIF_EXTENDEDELEMENTS == null || name == null ) { return null; } SIF_ExtendedElements container = (SIF_ExtendedElements) GetChild( GlobalDTD.SIF_EXTENDEDELEMENTS ); if ( container == null ) { return null; } return container[name]; } /** * Gets all SIF_ExtendedElements/SIF_ExtendedElement children of this object.<p> * @return An array of SIF_ExtendedElement instances. If no SIF_ExtendedElements * child element was found, an empty array is returned * * @since ADK 1.5 */ public SIF_ExtendedElement[] SIFExtendedElements { get { if ( GlobalDTD.SIF_EXTENDEDELEMENTS == null ) return new SIF_ExtendedElement[0]; SIF_ExtendedElements container = (SIF_ExtendedElements) GetChild( GlobalDTD.SIF_EXTENDEDELEMENTS ); if ( container == null ) { return new SIF_ExtendedElement[0]; } return container.ToArray(); } set { SIFExtendedElementsContainer.SetChildren( value ); } } /// <summary> /// Gets the SIF_ExtendedElements container in which all child SIF_ExtendedElement /// elements are placed by the {@link #setSIFExtendedElement(String, String)} /// method. Note if there is currently no container element, one is created and /// added as a child of the SIFDataObject. /// </summary> /// <remarks> /// This method is provided as a convenience to agents that wish to obtain the /// SIF_ExtendedElements container element in order to manually add extended /// elements to it. This is useful, for example, if you need to call methods on /// the extended element before adding it to the container (e.g. the <c>DoNotEncode</c> /// method). /// </remarks> /// <example> /// The equivalent functionality is possible by making this call: /// <code> /// SIF_ExtendedElements container = (SIF_ExtendedElements)GetChild( SifDtd.SIF_EXTENDEDELEMENTS ); /// </code> /// </example> /// <returns>The SIF_ExtendedElements container element, which is created and /// added as a child to this SIFDataObject if it does not currently exist.</returns> public SIF_ExtendedElements SIFExtendedElementsContainer { get { SIF_ExtendedElements container = (SIF_ExtendedElements) GetChild( GlobalDTD.SIF_EXTENDEDELEMENTS ); if ( container == null ) { container = new SIF_ExtendedElements(); AddChild( container ); } return container; } set { RemoveChild( GlobalDTD.SIF_EXTENDEDELEMENTS ); AddChild( GlobalDTD.SIF_EXTENDEDELEMENTS, value ); } } /// <summary> /// Changes the default behavior of SIFElement so that /// the root element and attributes of a SIFData object are always /// written, even if setChanged(false) is called. Callers can /// call this method to ensure that the root elements and attibutes /// are always rendered even if a previous call to setChanged(false) was done. /// </summary> /// <remarks> /// The reason for this is that the ADK uses the change tracking to determine /// whether an element should be written out or not when a Query is received with /// conditions. No matter what, even if the object does not have element specified as /// a query condition, the root SIFDataObjectElement and its mandatory attributes /// should still be rendered. /// </remarks> public void EnsureRootElementRendered() { // Make sure that the root element and attributes are written out this.SetChildChanged(); lock ( fSyncLock ) { if ( fFields != null ) { foreach ( SimpleField field in fFields.Values ) { if ( field.ElementDef.IsAttribute( this.SifVersion ) ) { field.SetChanged( true ); } } } } } #region Serialization // TODO: Andy E Serialization still does not work in the .Net ADK. We need to modify // adkgen so that the protected serialization constructor is added to each // subclass of Element [SecurityPermission( SecurityAction.Demand, SerializationFormatter = true )] protected SifDataObject( SerializationInfo info, StreamingContext context ) : base( info, context ) { string versionString = info.GetString( "fVersion" ); fVersion = SifVersion.Parse( versionString ); } //protected override void OnGetObjectData(SerializationInfo info, // StreamingContext context) //{ // info.AddValue("fVersion", this.SifVersion.ToString()); //} #endregion } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Concurrent; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Web; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.Fields; using Glass.Mapper.Sc.Pipelines.GetChromeData; using Glass.Mapper.Sc.RenderField; using Glass.Mapper.Sc.Web.Ui; using Sitecore.Collections; using Sitecore.Data; using Sitecore.Data.Events; using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Pipelines; using Sitecore.Pipelines.RenderField; using Sitecore.SecurityModel; using Sitecore.Text; using Sitecore.Web; namespace Glass.Mapper.Sc { /// <summary> /// This class contains a set of helpers that make converting items mapped in Glass.Sitecore.Mapper to HTML /// </summary> public class GlassHtml : IGlassHtml { private static readonly Type ImageType = typeof(Image); private static readonly Type LinkType = typeof(Link); private static ConcurrentDictionary<string, object> _compileCache = new ConcurrentDictionary<string, object>(); private readonly Context _context; static GlassHtml() { } public const string Parameters = "Parameters"; /// <summary> /// The image width /// </summary> public const string ImageWidth = "width"; /// <summary> /// The image height /// </summary> public const string ImageHeight = "height"; /// <summary> /// The image tag format /// </summary> public static string ImageTagFormat = "<img src={2}{0}{2} {1}/>"; public static string LinkTagFormat = "<a href={3}{0}{3} {1}>{2}"; public static string QuotationMark = "'"; protected Func<T, string> GetCompiled<T>(Expression<Func<T, string>> expression) { if (!SitecoreContext.Config.UseGlassHtmlLambdaCache) { return expression.Compile(); } var key = typeof(T).FullName + expression.Body; if (_compileCache.ContainsKey(key)) { return (Func<T, string>)_compileCache[key]; } var compiled = expression.Compile(); _compileCache.TryAdd(key, compiled); return compiled; } protected Func<T, object> GetCompiled<T>(Expression<Func<T, object>> expression) { if (SitecoreContext.Config == null || !SitecoreContext.Config.UseGlassHtmlLambdaCache) { return expression.Compile(); } var key = typeof(T).FullName + expression.Body; if (_compileCache.ContainsKey(key)) { return (Func<T, object>)_compileCache[key]; } var compiled = expression.Compile(); _compileCache.TryAdd(key, compiled); return compiled; } /// <summary> /// Gets the sitecore context. /// </summary> /// <value> /// The sitecore context. /// </value> public ISitecoreContext SitecoreContext { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="GlassHtml"/> class. /// </summary> /// <param name="sitecoreContext">The service that will be used to load and save data</param> public GlassHtml(ISitecoreContext sitecoreContext) { SitecoreContext = sitecoreContext; _context = sitecoreContext.GlassContext; } /// <summary> /// Edits the frame. /// </summary> /// <param name="buttons">The buttons.</param> /// <param name="path">The path.</param> /// <param name="output">The output text writer</param> /// <param name="title">The title for the edit frame</param> /// <returns> /// GlassEditFrame. /// </returns> public GlassEditFrame EditFrame(string title, string buttons, string path = null, TextWriter output = null) { if (output == null) { output = HttpContext.Current.Response.Output; } var frame = new GlassEditFrame(title, buttons, output, path); frame.RenderFirstPart(); return frame; } public GlassEditFrame EditFrame<T>(T model, string title = null, TextWriter output = null, params Expression<Func<T, object>>[] fields) where T : class { if (IsInEditingMode && Sitecore.Context.IsLoggedIn && model != null) { if (fields.Any()) { var fieldNames = fields.Select(x => Mapper.Utilities.GetGlassProperty<T, SitecoreTypeConfiguration>(x, this.SitecoreContext.GlassContext, model)) .Cast<SitecoreFieldConfiguration>() .Where(x => x != null) .Select(x => x.FieldName); var buttonPath = "{0}{1}".Formatted( EditFrameBuilder.BuildToken, fieldNames.Aggregate((x, y) => x + "|" + y)); if (title.IsNotNullOrEmpty()) { buttonPath += "<title>{0}<title>".Formatted(title); } var field = fields.FirstOrDefault(); var config = Mapper.Utilities.GetTypeConfig<T, SitecoreTypeConfiguration>(field, SitecoreContext.GlassContext, model); var pathConfig = config.Properties .OfType<SitecoreInfoConfiguration>() .FirstOrDefault(x => x.Type == SitecoreInfoType.Path); var path = string.Empty; if (pathConfig == null) { var id = config.GetId(model); if (id == ID.Null) { throw new MapperException( "Failed to find ID. Ensure that you have an ID property on your model."); } var item = SitecoreContext.Database.GetItem(id); path = item.Paths.Path; } else { path = pathConfig.PropertyGetter(model) as string; } return EditFrame(title, buttonPath, path, output); } } return new GlassNullEditFrame(); } /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The model object that contains the item to be edited</param> /// <param name="field">The field that should be made editable</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> public virtual string Editable<T>(T target, Expression<Func<T, object>> field, object parameters = null) { return MakeEditable(field, null, target, parameters); } /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The model object that contains the item to be edited</param> /// <param name="field">The field that should be made editable</param> /// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> public virtual string Editable<T>(T target, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null) { return MakeEditable(field, standardOutput, target, parameters); } public virtual T GetRenderingParameters<T>(string parameters, ID renderParametersTemplateId) where T : class { var nameValueCollection = WebUtil.ParseUrlParameters(parameters); return GetRenderingParameters<T>(nameValueCollection, renderParametersTemplateId); } public T GetRenderingParameters<T>(NameValueCollection parameters, ID renderParametersTemplateId) where T : class { var item = Utilities.CreateFakeItem(null, renderParametersTemplateId, SitecoreContext.Database, "renderingParameters"); using (new SecurityDisabler()) { using (new EventDisabler()) { using (new VersionCountDisabler()) { item.Editing.BeginEdit(); foreach (var key in parameters.AllKeys) { item[key] = parameters[key]; } T obj = item.GlassCast<T>(this.SitecoreContext); item.Editing.EndEdit(); item.Delete(); //added for clean up return obj; } } } } /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public virtual T GetRenderingParameters<T>(string parameters) where T : class { if (String.IsNullOrEmpty(parameters)) { return default(T); } var nameValueCollection = WebUtil.ParseUrlParameters(parameters); return GetRenderingParameters<T>(nameValueCollection); } /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public virtual T GetRenderingParameters<T>(NameValueCollection parameters) where T : class { if (parameters == null) { return default(T); } var config = SitecoreContext.GlassContext[typeof(T)] as SitecoreTypeConfiguration; if (config == null) { SitecoreContext.GlassContext.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(T))); } config = SitecoreContext.GlassContext[typeof(T)] as SitecoreTypeConfiguration; return GetRenderingParameters<T>(parameters, config.TemplateId); } public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, TextWriter writer, object parameters = null, bool isEditable = false) { NameValueCollection attrs; if (parameters is NameValueCollection) { attrs = parameters as NameValueCollection; } else { attrs = Utilities.GetPropertiesCollection(parameters, true); } if (IsInEditingMode && isEditable) { if (attrs != null) { attrs.Add("haschildren", "true"); return MakeEditable(field, null, model, attrs, _context, SitecoreContext.Database, writer); } return MakeEditable(field, null, model, "haschildren=true", _context, SitecoreContext.Database, writer); } else { return BeginRenderLink(field.Compile().Invoke(model) as Link, attrs, string.Empty, writer); } } /// <summary> /// Checks it and attribute is part of the NameValueCollection and updates it with the /// default if it isn't. /// </summary> /// <param name="collection">The collection of parameters</param> /// <param name="name">The name of the attribute in the collection</param> /// <param name="defaultValue">The default value for the attribute</param> public static void AttributeCheck(SafeDictionary<string> collection, string name, string defaultValue) { if (collection[name].IsNullOrEmpty() && !defaultValue.IsNullOrEmpty()) collection[name] = defaultValue; } /// <summary> /// Render HTML for a link /// </summary> /// <param name="model">The model containing the link</param> /// <param name="field">An expression that points to the link</param> /// <param name="attributes">A collection of parameters to added to the link</param> /// <param name="isEditable">Indicate if the link should be editable in the page editor</param> /// <param name="contents">Content to go in the link</param> /// <returns>An "a" HTML element</returns> public virtual string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null) { NameValueCollection attrs; if (attributes is NameValueCollection) { attrs = attributes as NameValueCollection; } else { attrs = Utilities.GetPropertiesCollection(attributes, true); } var sb = new StringBuilder(); var writer = new StringWriter(sb); RenderingResult result; if (IsInEditingMode && isEditable) { if (contents.HasValue()) { attrs.Add("haschildren", "true"); attrs.Add("text",contents); } result = MakeEditable( field, null, model, attrs, _context, SitecoreContext.Database, writer); if (contents.IsNotNullOrEmpty()) { sb.Append(contents); } } else { result = BeginRenderLink( GetCompiled(field).Invoke(model) as Link, attrs, contents, writer ); } result.Dispose(); writer.Flush(); writer.Close(); return sb.ToString(); } /// <summary> /// Indicates if the site is in editing mode /// </summary> /// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value> public static bool IsInEditingMode { get { return Sitecore.Context.PageMode.IsPageEditorEditing; } } private string MakeEditable<T>(Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, T target, object parameters) { StringBuilder sb = new StringBuilder(); var writer = new StringWriter(sb); var result = MakeEditable(field, standardOutput, target, parameters, _context, SitecoreContext.Database, writer); result.Dispose(); writer.Flush(); writer.Close(); return sb.ToString(); } #region Statics /// <summary> /// Render HTML for a link /// </summary> /// <param name="link">The link to render</param> /// <param name="attributes">Addtiional parameters to add. Do not include href or title</param> /// <param name="contents">Content to go in the link instead of the standard text</param> /// <returns>An "a" HTML element</returns> [Obsolete("Use the SafeDictionary Overload")] public static RenderingResult BeginRenderLink(Link link, NameValueCollection attributes, string contents, TextWriter writer) { return BeginRenderLink(link, attributes.ToSafeDictionary(), contents, writer); } /// <summary> /// Render HTML for a link /// </summary> /// <param name="link">The link to render</param> /// <param name="attributes">Addtiional parameters to add. Do not include href or title</param> /// <param name="contents">Content to go in the link instead of the standard text</param> /// <returns>An "a" HTML element</returns> public static RenderingResult BeginRenderLink(Link link, SafeDictionary<string> attributes, string contents, TextWriter writer) { if (link == null) return new RenderingResult(writer, string.Empty, string.Empty); if (attributes == null) attributes = new SafeDictionary<string>(); contents = contents == null ? link.Text ?? link.Title : contents; AttributeCheck(attributes, "class", link.Class); AttributeCheck(attributes, "target", link.Target); AttributeCheck(attributes, "title", link.Title); var url = link.BuildUrl(attributes); url = HttpUtility.HtmlEncode(url); string firstPart = LinkTagFormat.Formatted(url, Utilities.ConvertAttributes(attributes, QuotationMark), contents, QuotationMark); string lastPart = "</a>"; return new RenderingResult(writer, firstPart, lastPart); } /// <summary> /// Makes the editable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="field">The field.</param> /// <param name="standardOutput">The standard output.</param> /// <param name="model">The model.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> /// <exception cref="Glass.Mapper.MapperException"> /// To many parameters in linq expression {0}.Formatted(field.Body) /// or /// Expression doesn't evaluate to a member {0}.Formatted(field.Body) /// or /// Page editting error. Could not find property {0} on type {1}.Formatted(memberExpression.Member.Name, config.Type.FullName) /// or /// Page editting error. Could not find data handler for property {2} {0}.{1}.Formatted( /// prop.DeclaringType, prop.Name, prop.MemberType) /// </exception> /// <exception cref="System.NullReferenceException">Context cannot be null</exception> private RenderingResult MakeEditable<T>( Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, T model, object parameters, Context context, Database database, TextWriter writer) { string firstPart = string.Empty; string lastPart = string.Empty; try { if (field == null) throw new NullReferenceException("No field set"); if (model == null) throw new NullReferenceException("No model set"); string parametersStringTemp = string.Empty; SafeDictionary<string> dictionary = new SafeDictionary<string>(); if (parameters == null) { parametersStringTemp = string.Empty; } else if (parameters is string) { parametersStringTemp = parameters as string; dictionary = WebUtil.ParseQueryString(parametersStringTemp ?? string.Empty); } else if (parameters is NameValueCollection) { var collection = (NameValueCollection)parameters; foreach (var key in collection.AllKeys) { dictionary.Add(key, collection[key]); } } else { var collection = Utilities.GetPropertiesCollection(parameters, true); foreach (var key in collection.AllKeys) { dictionary.Add(key, collection[key]); } } if (IsInEditingMode) { MemberExpression memberExpression; var finalTarget = Mapper.Utilities.GetTargetObjectOfLamba(field, model, out memberExpression); var config = Mapper.Utilities.GetTypeConfig<T, SitecoreTypeConfiguration>(field, context, model); var dataHandler = Mapper.Utilities.GetGlassProperty<T, SitecoreTypeConfiguration>(field, context, model); var scClass = config.ResolveItem(finalTarget, database); using (new ContextItemSwitcher(scClass)) { RenderFieldArgs renderFieldArgs = new RenderFieldArgs(); renderFieldArgs.Item = scClass; var fieldConfig = (SitecoreFieldConfiguration)dataHandler; if (fieldConfig.FieldId != (ID)null && fieldConfig.FieldId != ID.Null) { renderFieldArgs.FieldName = fieldConfig.FieldId.ToString(); } else { renderFieldArgs.FieldName = fieldConfig.FieldName; } renderFieldArgs.Parameters = dictionary; renderFieldArgs.DisableWebEdit = false; CorePipeline.Run("renderField", (PipelineArgs)renderFieldArgs); firstPart = renderFieldArgs.Result.FirstPart; lastPart = renderFieldArgs.Result.LastPart; } } else { if (standardOutput != null) { firstPart = GetCompiled(standardOutput)(model).ToString(); } else { object target = (GetCompiled(field)(model) ?? string.Empty); if (ImageType.IsInstanceOfType(target)) { var image = target as Image; firstPart = RenderImage(image, dictionary); } else if (LinkType.IsInstanceOfType(target)) { var link = target as Link; var sb = new StringBuilder(); var linkWriter = new StringWriter(sb); var result = BeginRenderLink(link, dictionary, null, linkWriter); result.Dispose(); linkWriter.Flush(); linkWriter.Close(); firstPart = sb.ToString(); } else { firstPart = target.ToString(); } } } } catch (Exception ex) { firstPart = "<p>{0}</p><pre>{1}</pre>".Formatted(ex.Message, ex.StackTrace); Log.Error("Failed to render field", ex, typeof(IGlassHtml)); } return new RenderingResult(writer, firstPart, lastPart); //return field.Compile().Invoke(model).ToString(); } #endregion /// <summary> /// Renders an image allowing simple page editor support /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model that contains the image field</param> /// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param> /// <param name="parameters">Image parameters, e.g. width, height</param> /// <param name="isEditable">Indicates if the field should be editable</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be output when rendering the image</param> /// <returns></returns> public virtual string RenderImage<T>(T model, Expression<Func<T, object>> field, object parameters = null, bool isEditable = false, bool outputHeightWidth = false) { var attrs = Utilities.GetPropertiesCollection(parameters, true).ToSafeDictionary(); if (IsInEditingMode && isEditable) { var url = new UrlString(); foreach (var pair in attrs) { url.Parameters.Add(pair.Key, pair.Value); } return Editable(model, field, url.Query); } else { return RenderImage(GetCompiled(field).Invoke(model) as Image, parameters == null ? null : attrs, outputHeightWidth); } } /// <summary> /// Renders HTML for an image /// </summary> /// <param name="image">The image to render</param> /// <param name="attributes">Additional parameters to add. Do not include alt or src</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be output when rendering the image</param> /// <returns>An img HTML element</returns> public virtual string RenderImage( Image image, SafeDictionary<string> attributes, bool outputHeightWidth = false ) { if (image == null) { return string.Empty; } if (attributes == null) { attributes = new SafeDictionary<string>(); } var origionalKeys = attributes.Keys.ToList(); //should there be some warning about these removals? AttributeCheck(attributes, ImageParameterKeys.CLASS, image.Class); if (!attributes.ContainsKey(ImageParameterKeys.ALT)) { attributes[ImageParameterKeys.ALT] = image.Alt; } AttributeCheck(attributes, ImageParameterKeys.BORDER, image.Border); if (image.HSpace > 0) AttributeCheck(attributes, ImageParameterKeys.HSPACE, image.HSpace.ToString(CultureInfo.InvariantCulture)); if (image.VSpace > 0) AttributeCheck(attributes, ImageParameterKeys.VSPACE, image.VSpace.ToString(CultureInfo.InvariantCulture)); if (image.Width > 0) AttributeCheck(attributes, ImageParameterKeys.WIDTHHTML, image.Width.ToString(CultureInfo.InvariantCulture)); if (image.Height > 0) AttributeCheck(attributes, ImageParameterKeys.HEIGHTHTML, image.Height.ToString(CultureInfo.InvariantCulture)); var urlParams = new SafeDictionary<string>(); var htmlParams = new SafeDictionary<string>(); /* * ME - This method is used to render images rather than going back to the fieldrender * because it stops another call having to be passed to Sitecore. */ if (image == null || image.Src.IsNullOrWhiteSpace()) return String.Empty; if (attributes == null) attributes = new SafeDictionary<string>(); Action<string> remove = key => attributes.Remove(key); Action<string> url = key => { urlParams.Add(key, attributes[key]); remove(key); }; Action<string> html = key => { htmlParams.Add(key, attributes[key]); remove(key); }; Action<string> both = key => { htmlParams.Add(key, attributes[key]); urlParams.Add(key, attributes[key]); remove(key); }; var keys = attributes.Keys.ToList(); foreach (var key in keys) { //if we have not config we just add it to both if (SitecoreContext.Config == null) { both(key); } else { bool found = false; if (SitecoreContext.Config.ImageAttributes.Contains(key)) { html(key); found = true; } if (SitecoreContext.Config.ImageQueryString.Contains(key)) { url(key); found = true; } if (!found) { html(key); } } } //copy width and height across to url if (!urlParams.ContainsKey(ImageParameterKeys.WIDTH) && !urlParams.ContainsKey(ImageParameterKeys.HEIGHT)) { if (origionalKeys.Contains(ImageParameterKeys.WIDTHHTML)) { urlParams[ImageParameterKeys.WIDTH] = htmlParams[ImageParameterKeys.WIDTHHTML]; } if (origionalKeys.Contains(ImageParameterKeys.HEIGHTHTML)) { urlParams[ImageParameterKeys.HEIGHT] = htmlParams[ImageParameterKeys.HEIGHTHTML]; } } if (!urlParams.ContainsKey(ImageParameterKeys.LANGUAGE) && image.Language != null) { urlParams[ImageParameterKeys.LANGUAGE] = image.Language.Name; } //calculate size var finalSize = Utilities.ResizeImage( image.Width, image.Height, urlParams[ImageParameterKeys.SCALE].ToFlaot(), urlParams[ImageParameterKeys.WIDTH].ToInt(), urlParams[ImageParameterKeys.HEIGHT].ToInt(), urlParams[ImageParameterKeys.MAX_WIDTH].ToInt(), urlParams[ImageParameterKeys.MAX_HEIGHT].ToInt()); urlParams[ImageParameterKeys.HEIGHT] = finalSize.Height.ToString(); urlParams[ImageParameterKeys.WIDTH] = finalSize.Width.ToString(); Action<string, string> originalAttributeClean = (exists, missing) => { if (origionalKeys.Contains(exists) && !origionalKeys.Contains(missing)) { urlParams.Remove(missing); htmlParams.Remove(missing); } }; //we do some smart clean up originalAttributeClean(ImageParameterKeys.WIDTHHTML, ImageParameterKeys.HEIGHTHTML); originalAttributeClean(ImageParameterKeys.HEIGHTHTML, ImageParameterKeys.WIDTHHTML); if (!outputHeightWidth) { htmlParams.Remove(ImageParameterKeys.WIDTHHTML); htmlParams.Remove(ImageParameterKeys.HEIGHTHTML); } var builder = new UrlBuilder(image.Src); foreach (var key in urlParams.Keys) { builder.AddToQueryString(key, urlParams[key]); } string mediaUrl = builder.ToString(); #if (SC81 || SC80 || SC75) mediaUrl = ProtectMediaUrl(mediaUrl); #endif mediaUrl = HttpUtility.HtmlEncode(mediaUrl); return ImageTagFormat.Formatted(mediaUrl, Utilities.ConvertAttributes(htmlParams, QuotationMark), QuotationMark); } #if (SC81 || SC80 || SC75) public virtual string ProtectMediaUrl(string url) { return Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl(url); } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.IO.FileSystem.DriveInfoTests { public class Set_VolumeLabel { [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool GetVolumeInformation(String drive, StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, StringBuilder fileSystemName, int fileSystemNameBufLen); [Fact] public void Test01() { DriveInfo[] drives; Dictionary<string, string> originalVolumeInfo; String tempVolumeName; Boolean volumeSettable; int chCount = 0; DriveInfo drive; List<string> nonDriveLetters; List<string> driveLetters; //This is both a settable and gettable property. We test the get part of it here. There is a Win32 API that gives this information. //But since this is settable, we can also use that to make sure that this property works as expected. We will make sure that we will leave //the drives with the original volume labels //Scenario 1 - Confirm with Pinvoke drives = DriveInfo.GetDrives(); originalVolumeInfo = new Dictionary<string, string>(); for (int i = 0; i < drives.Length; i++) { const int volNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); const int fileSystemNameLen = 50; StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen); int serialNumber, maxFileNameLen, fileSystemFlags; bool r = GetVolumeInformation(drives[i].Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen); if (!r) { if (drives[i].IsReady) { Assert.False(true, string.Format("Unexpected error returned from Win32 fn. Drive Name: {1}, Volume: {2}", i, drives[i].Name, drives[i].VolumeLabel)); } } else { if (volumeName.ToString() != drives[i].VolumeLabel) { Assert.False(true, string.Format("Error, Wrong volume label returned. Expected: {1}, Returned: {2}", i, volumeName.ToString(), drives[i].VolumeLabel)); } originalVolumeInfo.Add(drives[i].Name, drives[i].VolumeLabel); } } //Scenario 2: Change the volume label and check tempVolumeName = "BCLTest"; for (int i = 0; i < drives.Length; i++) { if (drives[i].IsReady) { volumeSettable = true; try { drives[i].VolumeLabel = tempVolumeName; } catch (UnauthorizedAccessException) { volumeSettable = false; } if (volumeSettable) { if (String.Compare(drives[i].VolumeLabel, tempVolumeName, StringComparison.CurrentCultureIgnoreCase) != 0) { Assert.False(true, string.Format("Error, Wrong volume label returned. Expected: {1}, Returned: {2}", i, tempVolumeName, drives[i].VolumeLabel)); } } } } //Scenario 3: Invalid string values. This is really mute since we dont do any error checking in our code. We pass the down to Win32 and report //Any error conditions. And we dont want to test the Win32 API here :-) for (int i = 0; i < drives.Length; i++) { if (drives[i].IsReady && drives[i].DriveType != DriveType.CDRom && drives[i].DriveType != DriveType.Network) { volumeSettable = true; try { drives[i].VolumeLabel = null; } catch (UnauthorizedAccessException) { volumeSettable = false; } if (volumeSettable && drives[i].VolumeLabel != String.Empty) { Assert.False(true, string.Format("Error, Wrong result returned, <{0}>", drives[i].VolumeLabel)); } } if (drives[i].IsReady && (drives[i].DriveType == DriveType.CDRom || drives[i].DriveType == DriveType.Network)) { Assert.Throws<UnauthorizedAccessException>(() => { drives[i].VolumeLabel = null; }); } if (!drives[i].IsReady) { try { drives[i].VolumeLabel = null; } catch (IOException) { } catch (System.UnauthorizedAccessException) { } } if (drives[i].IsReady && (drives[i].DriveType != DriveType.CDRom) && (drives[i].DriveType != DriveType.Network)) { //There is a char limit for every file system when setting a volume label switch (drives[i].DriveFormat) { case "FAT": chCount = 12; break; case "FAT32": chCount = 12; break; case "NTFS": chCount = 33; break; default: chCount = 50; Assert.False(true, "Test Failed"); break; } String sT = new String('a', chCount); try { drives[i].VolumeLabel = sT; Assert.False(true, "Expected IOException."); } catch (IOException) { } catch (UnauthorizedAccessException) { } } } //Scenario 4: We will revert to the original volume value and check for (int i = 0; i < drives.Length; i++) { if (originalVolumeInfo.ContainsKey(drives[i].Name)) { try { drives[i].VolumeLabel = (String)originalVolumeInfo[drives[i].Name]; } catch (UnauthorizedAccessException) { } } if (drives[i].IsReady) { if (String.Compare((String)originalVolumeInfo[drives[i].Name], drives[i].VolumeLabel, StringComparison.CurrentCultureIgnoreCase) != 0) { Assert.False(true, string.Format("Error, Wrong volume label returned. Expected: {1}, Returned: {2}", i, (String)originalVolumeInfo[drives[i].Name], drives[i].VolumeLabel)); } } } //Scenario 5: Checking for drives that do not exist drives = DriveInfo.GetDrives(); driveLetters = new List<string>(); for (int i = 0; i < drives.Length; i++) driveLetters.Add(drives[i].Name[0].ToString().ToUpper()); nonDriveLetters = new List<string>(); for (int i = 0; i < 26; i++) if (!driveLetters.Contains(((Char)(65 + i)).ToString())) nonDriveLetters.Add(((Char)(65 + i)).ToString()); foreach (String letter in nonDriveLetters) { drive = new DriveInfo(letter); Assert.Throws<DriveNotFoundException>(() => { drive.VolumeLabel = "NOCANDO"; }); } } } }
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using GSF.ASN1; using GSF.ASN1.Attributes; using GSF.ASN1.Coders; using GSF.ASN1.Types; namespace GSF.MMS.Model { [ASN1PreparedElement] [ASN1Sequence(Name = "Event_Enrollment_instance", IsSet = false)] public class Event_Enrollment_instance : IASN1PreparedElement { private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Event_Enrollment_instance)); private DefinitionChoiceType definition_; private ObjectName name_; [ASN1Element(Name = "name", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)] public ObjectName Name { get { return name_; } set { name_ = value; } } [ASN1Element(Name = "definition", IsOptional = false, HasTag = false, HasDefaultValue = false)] public DefinitionChoiceType Definition { get { return definition_; } set { definition_ = value; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } [ASN1PreparedElement] [ASN1Choice(Name = "definition")] public class DefinitionChoiceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType)); private DetailsSequenceType details_; private bool details_selected; private ObjectIdentifier reference_; private bool reference_selected; [ASN1ObjectIdentifier(Name = "")] [ASN1Element(Name = "reference", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public ObjectIdentifier Reference { get { return reference_; } set { selectReference(value); } } [ASN1Element(Name = "details", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)] public DetailsSequenceType Details { get { return details_; } set { selectDetails(value); } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isReferenceSelected() { return reference_selected; } public void selectReference(ObjectIdentifier val) { reference_ = val; reference_selected = true; details_selected = false; } public bool isDetailsSelected() { return details_selected; } public void selectDetails(DetailsSequenceType val) { details_ = val; details_selected = true; reference_selected = false; } [ASN1PreparedElement] [ASN1Sequence(Name = "details", IsSet = false)] public class DetailsSequenceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType)); private AlarmAckRule aaRule_; private bool aaRule_present; private Access_Control_List_instance accessControl_; private ApplicationReference clientApplication_; private bool clientApplication_present; private DisplayEnhancementChoiceType displayEnhancement_; private EE_Duration duration_; private bool duration_present; private Transitions ecTransitions_; private EE_Class eeClass_; private Event_Action_instance eventAction_; private bool eventAction_present; private Event_Condition_instance eventCondition_; private RemainingDelayChoiceType remainingDelay_; private bool remainingDelay_present; [ASN1Element(Name = "accessControl", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)] public Access_Control_List_instance AccessControl { get { return accessControl_; } set { accessControl_ = value; } } [ASN1Element(Name = "eeClass", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)] public EE_Class EeClass { get { return eeClass_; } set { eeClass_ = value; } } [ASN1Element(Name = "eventCondition", IsOptional = false, HasTag = true, Tag = 5, HasDefaultValue = false)] public Event_Condition_instance EventCondition { get { return eventCondition_; } set { eventCondition_ = value; } } [ASN1Element(Name = "ecTransitions", IsOptional = false, HasTag = true, Tag = 6, HasDefaultValue = false)] public Transitions EcTransitions { get { return ecTransitions_; } set { ecTransitions_ = value; } } [ASN1Element(Name = "remainingDelay", IsOptional = true, HasTag = false, HasDefaultValue = false)] public RemainingDelayChoiceType RemainingDelay { get { return remainingDelay_; } set { remainingDelay_ = value; remainingDelay_present = true; } } [ASN1Element(Name = "eventAction", IsOptional = true, HasTag = true, Tag = 9, HasDefaultValue = false)] public Event_Action_instance EventAction { get { return eventAction_; } set { eventAction_ = value; eventAction_present = true; } } [ASN1Element(Name = "duration", IsOptional = true, HasTag = true, Tag = 10, HasDefaultValue = false)] public EE_Duration Duration { get { return duration_; } set { duration_ = value; duration_present = true; } } [ASN1Element(Name = "clientApplication", IsOptional = true, HasTag = true, Tag = 11, HasDefaultValue = false)] public ApplicationReference ClientApplication { get { return clientApplication_; } set { clientApplication_ = value; clientApplication_present = true; } } [ASN1Element(Name = "aaRule", IsOptional = true, HasTag = true, Tag = 12, HasDefaultValue = false)] public AlarmAckRule AaRule { get { return aaRule_; } set { aaRule_ = value; aaRule_present = true; } } [ASN1Element(Name = "displayEnhancement", IsOptional = false, HasTag = false, HasDefaultValue = false)] public DisplayEnhancementChoiceType DisplayEnhancement { get { return displayEnhancement_; } set { displayEnhancement_ = value; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isRemainingDelayPresent() { return remainingDelay_present; } public bool isEventActionPresent() { return eventAction_present; } public bool isDurationPresent() { return duration_present; } public bool isClientApplicationPresent() { return clientApplication_present; } public bool isAaRulePresent() { return aaRule_present; } [ASN1PreparedElement] [ASN1Choice(Name = "displayEnhancement")] public class DisplayEnhancementChoiceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DisplayEnhancementChoiceType)); private NullObject none_; private bool none_selected; private long number_; private bool number_selected; private MMSString text_; private bool text_selected; [ASN1Element(Name = "text", IsOptional = false, HasTag = true, Tag = 13, HasDefaultValue = false)] public MMSString Text { get { return text_; } set { selectText(value); } } [ASN1Integer(Name = "")] [ASN1Element(Name = "number", IsOptional = false, HasTag = true, Tag = 14, HasDefaultValue = false)] public long Number { get { return number_; } set { selectNumber(value); } } [ASN1Null(Name = "none")] [ASN1Element(Name = "none", IsOptional = false, HasTag = true, Tag = 15, HasDefaultValue = false)] public NullObject None { get { return none_; } set { selectNone(value); } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isTextSelected() { return text_selected; } public void selectText(MMSString val) { text_ = val; text_selected = true; number_selected = false; none_selected = false; } public bool isNumberSelected() { return number_selected; } public void selectNumber(long val) { number_ = val; number_selected = true; text_selected = false; none_selected = false; } public bool isNoneSelected() { return none_selected; } public void selectNone() { selectNone(new NullObject()); } public void selectNone(NullObject val) { none_ = val; none_selected = true; text_selected = false; number_selected = false; } } [ASN1PreparedElement] [ASN1Choice(Name = "remainingDelay")] public class RemainingDelayChoiceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(RemainingDelayChoiceType)); private NullObject forever_; private bool forever_selected; private long time_; private bool time_selected; [ASN1Integer(Name = "")] [ASN1Element(Name = "time", IsOptional = false, HasTag = true, Tag = 7, HasDefaultValue = false)] public long Time { get { return time_; } set { selectTime(value); } } [ASN1Null(Name = "forever")] [ASN1Element(Name = "forever", IsOptional = false, HasTag = true, Tag = 8, HasDefaultValue = false)] public NullObject Forever { get { return forever_; } set { selectForever(value); } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isTimeSelected() { return time_selected; } public void selectTime(long val) { time_ = val; time_selected = true; forever_selected = false; } public bool isForeverSelected() { return forever_selected; } public void selectForever() { selectForever(new NullObject()); } public void selectForever(NullObject val) { forever_ = val; forever_selected = true; time_selected = false; } } } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Oranikle.Studio.Controls { [System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.GroupBox))] [System.ComponentModel.DefaultProperty("Caption")] public class CtrlLineWithText : System.Windows.Forms.UserControl { private string _Caption; private int _CaptionMarginSpace; private Oranikle.Studio.Controls.CaptionOrizontalAlign _CaptionOrizontalAlign; private int _CaptionPadding; private System.Drawing.Color _LineColor; private Oranikle.Studio.Controls.LineVerticalAlign _LineVerticalAlign; private System.ComponentModel.Container components; [System.ComponentModel.Category("Appearance")] [System.ComponentModel.DefaultValue("")] [System.ComponentModel.Description("The caption text displayed on the line. If the caption is \"\" (the default) the line is not broken")] public string Caption { get { return _Caption; } set { _Caption = value; Invalidate(); } } [System.ComponentModel.Description("The distance in pixels form the control margin to caption text")] [System.ComponentModel.Category("Appearance")] [System.ComponentModel.DefaultValue(16)] public int CaptionMarginSpace { get { return _CaptionMarginSpace; } set { _CaptionMarginSpace = value; Invalidate(); } } [System.ComponentModel.Description("Tell where the text caption is aligned in the control")] [System.ComponentModel.Category("Appearance")] [System.ComponentModel.DefaultValue(Oranikle.Studio.Controls.CaptionOrizontalAlign.Left)] public Oranikle.Studio.Controls.CaptionOrizontalAlign CaptionOrizontalAlign { get { return _CaptionOrizontalAlign; } set { _CaptionOrizontalAlign = value; Invalidate(); } } [System.ComponentModel.Description("The space in pixels arrownd text caption")] [System.ComponentModel.DefaultValue(2)] [System.ComponentModel.Category("Appearance")] public int CaptionPadding { get { return _CaptionPadding; } set { _CaptionPadding = value; Invalidate(); } } [System.ComponentModel.Description("Color of the line.")] [System.ComponentModel.Category("Appearance")] [System.ComponentModel.DefaultValue("")] public System.Drawing.Color LineColor { get { return _LineColor; } set { _LineColor = value; Invalidate(); } } [System.ComponentModel.Category("Appearance")] [System.ComponentModel.DefaultValue(Oranikle.Studio.Controls.LineVerticalAlign.Middle)] [System.ComponentModel.Description("The vertical alignement of the line within the space of the control")] public Oranikle.Studio.Controls.LineVerticalAlign LineVerticalAlign { get { return _LineVerticalAlign; } set { _LineVerticalAlign = value; Invalidate(); } } public CtrlLineWithText() { _Caption = ""; _CaptionMarginSpace = 16; _CaptionPadding = 2; _LineColor = System.Drawing.Color.DimGray; _LineVerticalAlign = Oranikle.Studio.Controls.LineVerticalAlign.Middle; InitializeComponent(); TabStop = false; } private void InitializeComponent() { Name = "CtrlLineWithText"; Size = new System.Drawing.Size(100, Font.Height); } protected override void Dispose(bool disposing) { if (disposing && (components != null)) components.Dispose(); base.Dispose(disposing); } protected override void OnFontChanged(System.EventArgs e) { base.OnResize(e); base.OnFontChanged(e); } protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { int i1, i3, i4; base.OnPaint(e); switch (LineVerticalAlign) { case Oranikle.Studio.Controls.LineVerticalAlign.Top: i1 = 0; break; case Oranikle.Studio.Controls.LineVerticalAlign.Middle: System.Drawing.Size size1 = Size; i1 = System.Convert.ToInt32(System.Math.Ceiling(new System.Decimal(size1.Height / 2))) - 1; break; case Oranikle.Studio.Controls.LineVerticalAlign.Bottom: System.Drawing.Size size2 = Size; i1 = size2.Height - 2; break; default: i1 = 0; break; } System.Drawing.SizeF sizeF = e.Graphics.MeasureString(Caption, Font, Width - (CaptionMarginSpace * 2), System.Drawing.StringFormat.GenericDefault); int i2 = System.Convert.ToInt32(sizeF.Width); if (Caption == "") { i3 = i4 = CaptionMarginSpace; } else { switch (CaptionOrizontalAlign) { case Oranikle.Studio.Controls.CaptionOrizontalAlign.Left: i3 = CaptionMarginSpace; i4 = CaptionMarginSpace + (CaptionPadding * 2) + i2; break; case Oranikle.Studio.Controls.CaptionOrizontalAlign.Center: i3 = ((Width - i2) / 2) - CaptionPadding; i4 = ((Width - i2) / 2) + i2 + CaptionPadding; break; case Oranikle.Studio.Controls.CaptionOrizontalAlign.Right: i3 = Width - (CaptionMarginSpace * 2) - i2; i4 = Width - CaptionMarginSpace; break; default: i3 = i4 = CaptionMarginSpace; break; } } System.Drawing.Point[] pointArr1 = new System.Drawing.Point[3]; pointArr1[0] = new System.Drawing.Point(0, i1 + 1); pointArr1[1] = new System.Drawing.Point(0, i1); pointArr1[2] = new System.Drawing.Point(i3, i1); e.Graphics.DrawLines(new System.Drawing.Pen(_LineColor, 1.0F), pointArr1); System.Drawing.Point[] pointArr2 = new System.Drawing.Point[2]; pointArr2[0] = new System.Drawing.Point(i4, i1); pointArr2[1] = new System.Drawing.Point(Width, i1); e.Graphics.DrawLines(new System.Drawing.Pen(_LineColor, 1.0F), pointArr2); System.Drawing.Point[] pointArr3 = new System.Drawing.Point[2]; pointArr3[0] = new System.Drawing.Point(0, i1 + 1); pointArr3[1] = new System.Drawing.Point(i3, i1 + 1); e.Graphics.DrawLines(new System.Drawing.Pen(System.Drawing.Color.White, 1.0F), pointArr3); System.Drawing.Point[] pointArr4 = new System.Drawing.Point[3]; pointArr4[0] = new System.Drawing.Point(i4, i1 + 1); pointArr4[1] = new System.Drawing.Point(Width, i1 + 1); pointArr4[2] = new System.Drawing.Point(Width, i1); e.Graphics.DrawLines(new System.Drawing.Pen(System.Drawing.Color.White, 1.0F), pointArr4); if (Caption != "") e.Graphics.DrawString(Caption, Font, new System.Drawing.SolidBrush(ForeColor), (float)(i3 + CaptionPadding), 1.0F); } protected override void OnResize(System.EventArgs e) { base.OnResize(e); Height = Font.Height + 2; Invalidate(); } } // class CtrlLineWithText }
using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using smg.Common.Exceptions; using smg.Common.StateDescription.LogicalRelations; namespace smg.UnitTests { /// <summary> /// Tests the functionality <see cref="ILogicalRelation"/>'s implementations. /// </summary> [TestClass] public class LogicalRelationsUnitTests { #region Private Static Fields /// <summary> /// An instance used to test <see cref="OrLogicalRelation"/>. /// </summary> private static readonly OrLogicalRelation OR_LOGICAL_RELATION; /// <summary> /// An instance used to test <see cref="XorLogicalRelation"/>. /// </summary> private static readonly XorLogicalRelation XOR_LOGICAL_RELATION; /// <summary> /// An instance used to test <see cref="AndLogicalRelation"/>. /// </summary> private static readonly AndLogicalRelation AND_LOGICAL_RELATION; /// <summary> /// Contains a set of state groups to be used for testing logical relations. /// </summary> private static readonly Dictionary<string, string[]> STATE_GROUPS; #endregion #region Constructors /// <summary> /// Initializes <see cref="LogicalRelationsUnitTests"/>. /// </summary> static LogicalRelationsUnitTests() { OR_LOGICAL_RELATION = new OrLogicalRelation(); XOR_LOGICAL_RELATION = new XorLogicalRelation(); AND_LOGICAL_RELATION = new AndLogicalRelation(); STATE_GROUPS = new Dictionary<string, string[]> { { "Group1", new [] { "State1", "State2", "State3" } }, { "Group2", new [] { "State4", "State5" } }, { "Group3", new [] { "State6", "State7" } } }; } #endregion #region OrLogicalState /// <summary> /// Test whether a given permutation is available for specific states under <see cref="OrLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(OrLogicalRelation))] public void Or_ValidPermutationWhenTwoStatesFit_ExpectedTrue() { string[] permutation = { "State1", "State4", "State6" }; string[] availableForStates = { "State1", "State2", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, OR_LOGICAL_RELATION, true); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="OrLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(OrLogicalRelation))] public void Or_ValidPermutationWhenOneStateFits_ExpectedTrue() { string[] permutation = { "State1", "State5", "State6" }; string[] availableForStates = { "State1", "State2", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, OR_LOGICAL_RELATION, true); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="OrLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(OrLogicalRelation))] public void Or_ValidPermutationNoStateFits_ExpectedFalse() { string[] permutation = { "State3", "State5", "State6" }; string[] availableForStates = { "State1", "State2", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, OR_LOGICAL_RELATION, false); } #endregion #region XorLogicalState /// <summary> /// Test whether a given permutation is available for specific states under <see cref="XorLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(XorLogicalRelation))] public void Xor_ValidPermutationWhenTwoStatesFit_ExpectedTrue() { string[] permutation = { "State1", "State4", "State6" }; string[] availableForStates = { "State1", "State2", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, XOR_LOGICAL_RELATION, false); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="XorLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(XorLogicalRelation))] public void Xor_ValidPermutationWhenOneStateFits_ExpectedTrue() { string[] permutation = { "State1", "State5", "State6" }; string[] availableForStates = { "State1", "State2", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, XOR_LOGICAL_RELATION, true); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="XorLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(XorLogicalRelation))] public void Xor_ValidPermutationNoStateFits_ExpectedFalse() { string[] permutation = { "State3", "State5", "State6" }; string[] availableForStates = { "State1", "State2", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, XOR_LOGICAL_RELATION, false); } #endregion #region AndLogicalState /// <summary> /// Test whether a given permutation is available for specific states under <see cref="AndLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(AndLogicalRelation))] public void And_ValidPermutationNoStatesToTest_ExpectedTrue() { string[] permutation = { "State1", "State4", "State6" }; string[] availableForStates = Enumerable.Empty<string>().ToArray(); AssertPermutationIsAvailable(permutation, availableForStates, AND_LOGICAL_RELATION, true); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="AndLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(AndLogicalRelation))] public void And_ValidPermutationWhenOneStateFits_ExpectedTrue() { string[] permutation = { "State1", "State4", "State6" }; string[] availableForStates = { "State1" }; AssertPermutationIsAvailable(permutation, availableForStates, AND_LOGICAL_RELATION, true); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="AndLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(AndLogicalRelation))] public void And_ValidPermutationWhenTwoStatesFit_ExpectedTrue() { string[] permutation = { "State1", "State4", "State6" }; string[] availableForStates = { "State1", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, AND_LOGICAL_RELATION, true); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="AndLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(AndLogicalRelation))] public void And_ValidPermutationWhenTwoStatesOneMissing_ExpectedFalse() { string[] permutation = { "State1", "State5", "State6" }; string[] availableForStates = { "State1", "State4" }; AssertPermutationIsAvailable(permutation, availableForStates, AND_LOGICAL_RELATION, false); } /// <summary> /// Test whether a given permutation is available for specific states under <see cref="AndLogicalRelation"/>. /// </summary> [TestMethod] [TestCategory(nameof(AndLogicalRelation))] [ExpectedException(typeof(InvalidStateRepresentationException), "Using an AndLogicalRelation for two states of the same state group should throw an exception.")] public void And_ValidPermutationWhenExpectTwoOfSameGroup_ExpectedException() { string[] permutation = { "State1", "State5", "State6" }; string[] availableForStates = { "State1", "State2", "State4" }; AND_LOGICAL_RELATION.IsPermutationValid(STATE_GROUPS, permutation, availableForStates); } #endregion #region Private Static Methods /// <summary> /// Asserts that a given permutation is available for specific states under a given <see cref="ILogicalRelation"/>. /// </summary> /// <param name="permutation">A permutation of states for which the condition will be asserted.</param> /// <param name="availableForStates">The states for which the given permutation should be available or not.</param> /// <param name="relation">The relation under which the given permutation should be available or not for the given state set.</param> /// <param name="shouldBeAvailable">A value indicating whether the given permutation should be available for the given states under the given <see cref="ILogicalRelation"/>.</param> private static void AssertPermutationIsAvailable(string[] permutation, string[] availableForStates, ILogicalRelation relation, bool shouldBeAvailable) { bool result = relation.IsPermutationValid(STATE_GROUPS, permutation, availableForStates); if (shouldBeAvailable) { Assert.IsTrue(result, $"Permutation {FormatPermutation(permutation)} should be available for states {FormatPermutation(availableForStates)} under {relation.GetType().Name}."); } else { Assert.IsFalse(result, $"Permutation {FormatPermutation(permutation)} should not be available for states {FormatPermutation(availableForStates)} under {relation.GetType().Name}."); } } /// <summary> /// Formats a given permutation to a displayable <see cref="string"/>. /// </summary> /// <param name="permutation">A permutation to be formatted to a displayable <see cref="string"/>.</param> /// <returns>A displayable <see cref="string"/> which describes a given permutation.</returns> private static string FormatPermutation(string[] permutation) { return $"{{{string.Join(", ", permutation)}}}"; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.Text.Json { /// <summary> /// Represents a specific JSON value within a <see cref="JsonDocument"/>. /// </summary> public readonly partial struct JsonElement { private readonly JsonDocument _parent; private readonly int _idx; /// <summary> /// This is an implementation detail and MUST NOT be called by source-package consumers. /// </summary> internal JsonElement(JsonDocument parent, int idx) { // parent is usually not null, but the Current property // on the enumerators (when initialized as `default`) can // get here with a null. Debug.Assert(idx >= 0); _parent = parent; _idx = idx; } private JsonTokenType TokenType => _parent?.GetJsonTokenType(_idx) ?? JsonTokenType.None; /// <summary> /// The <see cref="JsonValueType"/> that the value is. /// </summary> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public JsonValueType Type => TokenType.ToValueType(); /// <summary> /// Get the value at a specified index when the current value is a /// <see cref="JsonValueType.Array"/>. /// </summary> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Array"/>. /// </exception> /// <exception cref="IndexOutOfRangeException"> /// <paramref name="index"/> is not in the range [0, <see cref="GetArrayLength"/>()). /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public JsonElement this[int index] { get { CheckValidInstance(); return _parent.GetArrayIndexElement(_idx, index); } } /// <summary> /// Get the number of values contained within the current array value. /// </summary> /// <returns>The number of values contained within the current array value.</returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Array"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public int GetArrayLength() { CheckValidInstance(); return _parent.GetArrayLength(_idx); } /// <summary> /// Gets a <see cref="JsonElement"/> representing the value of a required property identified /// by <paramref name="propertyName"/>. /// </summary> /// <remarks> /// Property name matching is performed as an ordinal, case-sensitive, comparison. /// /// If a property is defined multiple times for the same object, the last such definition is /// what is matched. /// </remarks> /// <param name="propertyName">Name of the property whose value to return.</param> /// <returns> /// A <see cref="JsonElement"/> representing the value of the requested property. /// </returns> /// <seealso cref="EnumerateObject"/> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Object"/>. /// </exception> /// <exception cref="KeyNotFoundException"> /// No property was found with the requested name. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="propertyName"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public JsonElement GetProperty(string propertyName) { if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); if (TryGetProperty(propertyName, out JsonElement property)) { return property; } throw new KeyNotFoundException(); } /// <summary> /// Gets a <see cref="JsonElement"/> representing the value of a required property identified /// by <paramref name="propertyName"/>. /// </summary> /// <remarks> /// <para> /// Property name matching is performed as an ordinal, case-sensitive, comparison. /// </para> /// /// <para> /// If a property is defined multiple times for the same object, the last such definition is /// what is matched. /// </para> /// </remarks> /// <param name="propertyName">Name of the property whose value to return.</param> /// <returns> /// A <see cref="JsonElement"/> representing the value of the requested property. /// </returns> /// <seealso cref="EnumerateObject"/> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Object"/>. /// </exception> /// <exception cref="KeyNotFoundException"> /// No property was found with the requested name. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public JsonElement GetProperty(ReadOnlySpan<char> propertyName) { if (TryGetProperty(propertyName, out JsonElement property)) { return property; } throw new KeyNotFoundException(); } /// <summary> /// Gets a <see cref="JsonElement"/> representing the value of a required property identified /// by <paramref name="utf8PropertyName"/>. /// </summary> /// <remarks> /// <para> /// Property name matching is performed as an ordinal, case-sensitive, comparison. /// </para> /// /// <para> /// If a property is defined multiple times for the same object, the last such definition is /// what is matched. /// </para> /// </remarks> /// <param name="utf8PropertyName"> /// The UTF-8 (with no Byte-Order-Mark (BOM)) representation of the name of the property to return. /// </param> /// <returns> /// A <see cref="JsonElement"/> representing the value of the requested property. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Object"/>. /// </exception> /// <exception cref="KeyNotFoundException"> /// No property was found with the requested name. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> /// <seealso cref="EnumerateObject"/> public JsonElement GetProperty(ReadOnlySpan<byte> utf8PropertyName) { if (TryGetProperty(utf8PropertyName, out JsonElement property)) { return property; } throw new KeyNotFoundException(); } /// <summary> /// Looks for a property named <paramref name="propertyName"/> in the current object, returning /// whether or not such a property existed. When the property exists <paramref name="value"/> /// is assigned to the value of that property. /// </summary> /// <remarks> /// <para> /// Property name matching is performed as an ordinal, case-sensitive, comparison. /// </para> /// /// <para> /// If a property is defined multiple times for the same object, the last such definition is /// what is matched. /// </para> /// </remarks> /// <param name="propertyName">Name of the property to find.</param> /// <param name="value">Receives the value of the located property.</param> /// <returns> /// <see langword="true"/> if the property was found, <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Object"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="propertyName"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> /// <seealso cref="EnumerateObject"/> public bool TryGetProperty(string propertyName, out JsonElement value) { if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); return TryGetProperty(propertyName.AsSpan(), out value); } /// <summary> /// Looks for a property named <paramref name="propertyName"/> in the current object, returning /// whether or not such a property existed. When the property exists <paramref name="value"/> /// is assigned to the value of that property. /// </summary> /// <remarks> /// <para> /// Property name matching is performed as an ordinal, case-sensitive, comparison. /// </para> /// /// <para> /// If a property is defined multiple times for the same object, the last such definition is /// what is matched. /// </para> /// </remarks> /// <param name="propertyName">Name of the property to find.</param> /// <param name="value">Receives the value of the located property.</param> /// <returns> /// <see langword="true"/> if the property was found, <see langword="false"/> otherwise. /// </returns> /// <seealso cref="EnumerateObject"/> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Object"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetProperty(ReadOnlySpan<char> propertyName, out JsonElement value) { CheckValidInstance(); return _parent.TryGetNamedPropertyValue(_idx, propertyName, out value); } /// <summary> /// Looks for a property named <paramref name="utf8PropertyName"/> in the current object, returning /// whether or not such a property existed. When the property exists <paramref name="value"/> /// is assigned to the value of that property. /// </summary> /// <remarks> /// <para> /// Property name matching is performed as an ordinal, case-sensitive, comparison. /// </para> /// /// <para> /// If a property is defined multiple times for the same object, the last such definition is /// what is matched. /// </para> /// </remarks> /// <param name="utf8PropertyName"> /// The UTF-8 (with no Byte-Order-Mark (BOM)) representation of the name of the property to return. /// </param> /// <param name="value">Receives the value of the located property.</param> /// <returns> /// <see langword="true"/> if the property was found, <see langword="false"/> otherwise. /// </returns> /// <seealso cref="EnumerateObject"/> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Object"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetProperty(ReadOnlySpan<byte> utf8PropertyName, out JsonElement value) { CheckValidInstance(); return _parent.TryGetNamedPropertyValue(_idx, utf8PropertyName, out value); } /// <summary> /// Gets the value of the element as a <see cref="bool"/>. /// </summary> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <returns>The value of the element as a <see cref="bool"/>.</returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is neither <see cref="JsonValueType.True"/> or /// <see cref="JsonValueType.False"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool GetBoolean() { // CheckValidInstance is redundant. Asking for the type will // return None, which then throws the same exception in the return statement. JsonTokenType type = TokenType; return type == JsonTokenType.True ? true : type == JsonTokenType.False ? false : throw ThrowHelper.GetJsonElementWrongTypeException(nameof(Boolean), type); } /// <summary> /// Gets the value of the element as a <see cref="string"/>. /// </summary> /// <remarks> /// This method does not create a string representation of values other than JSON strings. /// </remarks> /// <returns>The value of the element as a <see cref="bool"/>.</returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.String"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> /// <seealso cref="ToString"/> public string GetString() { CheckValidInstance(); return _parent.GetString(_idx, JsonTokenType.String); } /// <summary> /// Attempts to represent the current JSON number as an <see cref="int"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <returns> /// <see langword="true"/> if the number can be represented as an <see cref="int"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetInt32(out int value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the current JSON number as an <see cref="int"/>. /// </summary> /// <returns>The current JSON number as an <see cref="int"/>.</returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="FormatException"> /// The value cannot be represented as an <see cref="int"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public int GetInt32() { if (TryGetInt32(out int value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON number as a <see cref="uint"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <returns> /// <see langword="true"/> if the number can be represented as a <see cref="uint"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> [CLSCompliant(false)] public bool TryGetUInt32(out uint value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the current JSON number as a <see cref="uint"/>. /// </summary> /// <returns>The current JSON number as a <see cref="uint"/>.</returns> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="FormatException"> /// The value cannot be represented as a <see cref="uint"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> [CLSCompliant(false)] public uint GetUInt32() { if (TryGetUInt32(out uint value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON number as a <see cref="long"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <returns> /// <see langword="true"/> if the number can be represented as a <see cref="long"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetInt64(out long value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the current JSON number as a <see cref="long"/>. /// </summary> /// <returns>The current JSON number as a <see cref="long"/>.</returns> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="FormatException"> /// The value cannot be represented as a <see cref="long"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public long GetInt64() { if (TryGetInt64(out long value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON number as a <see cref="ulong"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <returns> /// <see langword="true"/> if the number can be represented as a <see cref="ulong"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> [CLSCompliant(false)] public bool TryGetUInt64(out ulong value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the current JSON number as a <see cref="ulong"/>. /// </summary> /// <returns>The current JSON number as a <see cref="ulong"/>.</returns> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="FormatException"> /// The value cannot be represented as a <see cref="ulong"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> [CLSCompliant(false)] public ulong GetUInt64() { if (TryGetUInt64(out ulong value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON number as a <see cref="double"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// <para> /// This method does not parse the contents of a JSON string value. /// </para> /// /// <para> /// On .NET Core this method does not return <see langword="false"/> for values larger than /// <see cref="double.MaxValue"/> (or smaller than <see cref="double.MinValue"/>), /// instead <see langword="true"/> is returned and <see cref="double.PositiveInfinity"/> (or /// <see cref="double.NegativeInfinity"/>) is emitted. /// </para> /// </remarks> /// <returns> /// <see langword="true"/> if the number can be represented as a <see cref="double"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetDouble(out double value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the current JSON number as a <see cref="double"/>. /// </summary> /// <returns>The current JSON number as a <see cref="double"/>.</returns> /// <remarks> /// <para> /// This method does not parse the contents of a JSON string value. /// </para> /// /// <para> /// On .NET Core this method returns <see cref="double.PositiveInfinity"/> (or /// <see cref="double.NegativeInfinity"/>) for values larger than /// <see cref="double.MaxValue"/> (or smaller than <see cref="double.MinValue"/>). /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="FormatException"> /// The value cannot be represented as a <see cref="double"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public double GetDouble() { if (TryGetDouble(out double value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON number as a <see cref="float"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// <para> /// This method does not parse the contents of a JSON string value. /// </para> /// /// <para> /// On .NET Core this method does not return <see langword="false"/> for values larger than /// <see cref="float.MaxValue"/> (or smaller than <see cref="float.MinValue"/>), /// instead <see langword="true"/> is returned and <see cref="float.PositiveInfinity"/> (or /// <see cref="float.NegativeInfinity"/>) is emitted. /// </para> /// </remarks> /// <returns> /// <see langword="true"/> if the number can be represented as a <see cref="float"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetSingle(out float value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the current JSON number as a <see cref="float"/>. /// </summary> /// <returns>The current JSON number as a <see cref="float"/>.</returns> /// <remarks> /// <para> /// This method does not parse the contents of a JSON string value. /// </para> /// /// <para> /// On .NET Core this method returns <see cref="float.PositiveInfinity"/> (or /// <see cref="float.NegativeInfinity"/>) for values larger than /// <see cref="float.MaxValue"/> (or smaller than <see cref="float.MinValue"/>). /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="FormatException"> /// The value cannot be represented as a <see cref="float"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public float GetSingle() { if (TryGetSingle(out float value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON number as a <see cref="decimal"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <returns> /// <see langword="true"/> if the number can be represented as a <see cref="decimal"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> /// <seealso cref="GetRawText"/> public bool TryGetDecimal(out decimal value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the current JSON number as a <see cref="decimal"/>. /// </summary> /// <returns>The current JSON number as a <see cref="decimal"/>.</returns> /// <remarks> /// This method does not parse the contents of a JSON string value. /// </remarks> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Number"/>. /// </exception> /// <exception cref="FormatException"> /// The value cannot be represented as a <see cref="decimal"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> /// <seealso cref="GetRawText"/> public decimal GetDecimal() { if (TryGetDecimal(out decimal value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON string as a <see cref="DateTime"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// This method does not create a DateTime representation of values other than JSON strings. /// </remarks> /// <returns> /// <see langword="true"/> if the string can be represented as a <see cref="DateTime"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.String"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetDateTime(out DateTime value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the value of the element as a <see cref="DateTime"/>. /// </summary> /// <remarks> /// This method does not create a DateTime representation of values other than JSON strings. /// </remarks> /// <returns>The value of the element as a <see cref="DateTime"/>.</returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.String"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> /// <seealso cref="ToString"/> public DateTime GetDateTime() { if (TryGetDateTime(out DateTime value)) { return value; } throw new FormatException(); } /// <summary> /// Attempts to represent the current JSON string as a <see cref="DateTimeOffset"/>. /// </summary> /// <param name="value">Receives the value.</param> /// <remarks> /// This method does not create a DateTimeOffset representation of values other than JSON strings. /// </remarks> /// <returns> /// <see langword="true"/> if the string can be represented as a <see cref="DateTimeOffset"/>, /// <see langword="false"/> otherwise. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.String"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public bool TryGetDateTimeOffset(out DateTimeOffset value) { CheckValidInstance(); return _parent.TryGetValue(_idx, out value); } /// <summary> /// Gets the value of the element as a <see cref="DateTimeOffset"/>. /// </summary> /// <remarks> /// This method does not create a DateTimeOffset representation of values other than JSON strings. /// </remarks> /// <returns>The value of the element as a <see cref="DateTimeOffset"/>.</returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.String"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> /// <seealso cref="ToString"/> public DateTimeOffset GetDateTimeOffset() { if (TryGetDateTimeOffset(out DateTimeOffset value)) { return value; } throw new FormatException(); } /// <summary> /// This is an implementation detail and MUST NOT be called by source-package consumers. /// </summary> internal string GetPropertyName() { CheckValidInstance(); return _parent.GetNameOfPropertyValue(_idx); } /// <summary> /// Gets the original input data backing this value, returning it as a <see cref="string"/>. /// </summary> /// <returns> /// The original input data backing this value, returning it as a <see cref="string"/>. /// </returns> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public string GetRawText() { CheckValidInstance(); return _parent.GetRawValueAsString(_idx); } /// <summary> /// This is an implementation detail and MUST NOT be called by source-package consumers. /// </summary> internal string GetPropertyRawText() { CheckValidInstance(); return _parent.GetPropertyRawValueAsString(_idx); } /// <summary> /// Get an enumerator to enumerate the values in the JSON array represented by this JsonElement. /// </summary> /// <returns> /// An enumerator to enumerate the values in the JSON array represented by this JsonElement. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Array"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public ArrayEnumerator EnumerateArray() { CheckValidInstance(); JsonTokenType tokenType = TokenType; if (tokenType != JsonTokenType.StartArray) { throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartArray, tokenType); } return new ArrayEnumerator(this); } /// <summary> /// Get an enumerator to enumerate the properties in the JSON object represented by this JsonElement. /// </summary> /// <returns> /// An enumerator to enumerate the properties in the JSON object represented by this JsonElement. /// </returns> /// <exception cref="InvalidOperationException"> /// This value's <see cref="Type"/> is not <see cref="JsonValueType.Object"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public ObjectEnumerator EnumerateObject() { CheckValidInstance(); JsonTokenType tokenType = TokenType; if (tokenType != JsonTokenType.StartObject) { throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartObject, tokenType); } return new ObjectEnumerator(this); } /// <summary> /// Gets a string representation for the current value appropriate to the value type. /// </summary> /// <remarks> /// <para> /// For <see cref="JsonValueType.Null"/>, <see cref="string.Empty"/> is returned. /// </para> /// /// <para> /// For <see cref="JsonValueType.True"/>, <see cref="bool.TrueString"/> is returned. /// </para> /// /// <para> /// For <see cref="JsonValueType.False"/>, <see cref="bool.FalseString"/> is returned. /// </para> /// /// <para> /// For <see cref="JsonValueType.String"/>, the value of <see cref="GetString"/>() is returned. /// </para> /// /// <para> /// For other types, the value of <see cref="GetRawText"/>() is returned. /// </para> /// </remarks> /// <returns> /// A string representation for the current value appropriate to the value type. /// </returns> /// <exception cref="ObjectDisposedException"> /// The parent <see cref="JsonDocument"/> has been disposed. /// </exception> public override string ToString() { switch (TokenType) { case JsonTokenType.None: case JsonTokenType.Null: return string.Empty; case JsonTokenType.True: return bool.TrueString; case JsonTokenType.False: return bool.FalseString; case JsonTokenType.Number: case JsonTokenType.StartArray: case JsonTokenType.StartObject: { // null parent should have hit the None case Debug.Assert(_parent != null); return _parent.GetRawValueAsString(_idx); } case JsonTokenType.String: return GetString(); case JsonTokenType.Comment: case JsonTokenType.EndArray: case JsonTokenType.EndObject: default: Debug.Fail($"No handler for {nameof(JsonTokenType)}.{TokenType}"); return string.Empty; } } private void CheckValidInstance() { if (_parent == null) { throw new InvalidOperationException(); } } } }
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 Sogeti.Provisioning.WebApi.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; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Plivo.Client; using Plivo.Exception; using Plivo.Http; using Plivo.Utilities; namespace Plivo.Resource.MultiPartyCall { public class MultiPartyCallInterface : ResourceInterface { public MultiPartyCallInterface (HttpClient client) : base (client) { Uri = "Account/" + Client.GetAuthId () + "/MultiPartyCall/"; } public string MakeMpcId(string mpcUuid, string friendlyName) { string mpcId = ""; if (mpcUuid != null) { mpcId = "uuid_" + mpcUuid; } else if (friendlyName != null) { mpcId = "name_" + friendlyName; } else { throw new PlivoValidationException("Provide either mpc_uuid or friendly_name but not both"); } return mpcId; } public ListResponse<MultiPartyCall> List( string subAccount = null, string friendlyName = null, string status = null, uint? terminationCauseCode = null, string endTime_Gt = null, string endTime_Gte = null, string endTime_Lt = null, string endTime_Lte = null, string creationTime_Gt = null, string creationTime_Gte = null, string creationTime_Lt = null, string creationTime_Lte = null, uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; if (subAccount != null) { MpcUtils.ValidSubAccount(subAccount); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } if (status != null) { MpcUtils.ValidParamString("status", status, false); } if (terminationCauseCode != null) { MpcUtils.ValidParamInt("terminationCauseCode", terminationCauseCode, false); } if (endTime_Gt != null) { MpcUtils.ValidDateFormat("endTime_Gt", endTime_Gt, false); } if (endTime_Gte != null) { MpcUtils.ValidDateFormat("endTime_Gte", endTime_Gte, false); } if (endTime_Lt != null) { MpcUtils.ValidDateFormat("endTime_Lt", endTime_Lt, false); } if (endTime_Lte != null) { MpcUtils.ValidDateFormat("endTime_Lte", endTime_Lte, false); } if (creationTime_Gt != null) { MpcUtils.ValidDateFormat("creationTime_Gt", creationTime_Gt, false); } if (creationTime_Gte != null) { MpcUtils.ValidDateFormat("creationTime_Gte", creationTime_Gte, false); } if (creationTime_Lt != null) { MpcUtils.ValidDateFormat("creationTime_Lt", creationTime_Lt, false); } if (creationTime_Lte != null) { MpcUtils.ValidDateFormat("creationTime_Lte", creationTime_Lte, false); } if (limit != null) { MpcUtils.ValidRange("limit", limit, false, 1, 20); } if (offset != null) { MpcUtils.ValidRange("offset", offset, false, 0); } var data = CreateData( mandatoryParams, new { subAccount, friendlyName, status, terminationCauseCode, endTime_Gt, endTime_Gte, endTime_Lt, endTime_Lte, creationTime_Gt, creationTime_Gte, creationTime_Lt, creationTime_Lte, limit, offset, isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var resources = Task.Run (async () => await ListResources<ListResponse<MultiPartyCall>>(data).ConfigureAwait(false)).Result; resources.Objects.ForEach ( (obj) => obj.Interface = this ); return resources; }); } public MultiPartyCall Get(string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } string mpcId = MakeMpcId(mpcUuid, friendlyName); return ExecuteWithExceptionUnwrap(() => { var mpc = Task.Run(async () => await GetResource<MultiPartyCall>(mpcId, new Dictionary<string, object>() {{"is_voice_request", true}}).ConfigureAwait(false)).Result; mpc.Interface = this; return mpc; }); } public MultiPartyCallAddParticipantResponse AddParticipant( string role = null, string friendlyName = null, string mpcUuid = null, string from = null, string to = null, string callUuid = null, string callerName = null, string callStatusCallbackUrl = null, string callStatusCallbackMethod = "POST", string sipHeaders = null, string confirmKey = null, string confirmKeySoundUrl = null, string confirmKeySoundMethod = "GET", string dialMusic = "Real", dynamic ringTimeout = null, dynamic delayDial = null, uint? maxDuration = 14400, uint? maxParticipants = 10, string waitMusicUrl = null, string waitMusicMethod = "GET", string agentHoldMusicUrl = null, string agentHoldMusicMethod = "GET", string customerHoldMusicUrl = null, string customerHoldMusicMethod = "GET", string recordingCallbackUrl = null, string recordingCallbackMethod = "GET", string statusCallbackUrl = null, string statusCallbackMethod = "GET", string onExitActionUrl = null, string onExitActionMethod = "POST", bool record = false, string recordFileFormat = "mp3", string statusCallbackEvents = "mpc-state-changes,participant-state-changes", bool stayAlone = false, bool coachMode = true, bool mute = false, bool hold = false, bool startMpcOnEnter = true, bool endMpcOnExit = false, bool relayDtmfInputs = false, string enterSound = "beep:1", string enterSoundMethod = "GET", string exitSound = "beep:2", string exitSoundMethod = "GET", string startRecordingAudio = null, string startRecordingAudioMethod = "GET", string stopRecordingAudio = null, string stopRecordingAudioMethod = "GET" ) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } if (from != null && to != null && callUuid != null) { throw new PlivoValidationException("cannot specify call_uuid when (from, to) is provided"); } if (from == null && to == null && callUuid == null) { throw new PlivoValidationException("specify either callUuid or (from, to)"); } if ((from == null || to == null) && callUuid == null) { throw new PlivoValidationException("specify (from, to) when not adding an existing callUuid to multi party participant"); } if (role != null) { MpcUtils.ValidParamString("role", role.ToLower(), true, new List<string>() {"agent", "supervisor", "customer"}); } if (from != null) { MpcUtils.ValidParamString("from", from, false); } if (to != null) { MpcUtils.ValidParamString("to", to, false); MpcUtils.ValidMultipleDestinationNos("to", to, role, '<', 20); } if (callUuid != null) { MpcUtils.ValidParamString("callUuid", callUuid, false); } if(callerName!=null) { MpcUtils.ValidParamString("callerName", callerName, false); MpcUtils.ValidRange("callerName Length",(uint)callerName.Length, false , 0, 50); } else { callerName = from; } if (callStatusCallbackUrl != null) { MpcUtils.ValidUrl("callStatusCallbackUrl", callStatusCallbackUrl, false); } if (callStatusCallbackMethod != null) { MpcUtils.ValidParamString("callStatusCallbackMethod", callStatusCallbackMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (sipHeaders != null) { MpcUtils.ValidParamString("sipHeaders", sipHeaders, false); } if (confirmKey != null) { MpcUtils.ValidParamString("confirmKey", confirmKey, false, new List<string>() {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "#", "*"}); } if (confirmKeySoundUrl != null) { MpcUtils.ValidUrl("confirmKeySoundUrl", confirmKeySoundUrl, false); } if (confirmKeySoundMethod != null) { MpcUtils.ValidParamString("confirmKeySoundMethod", confirmKeySoundMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (dialMusic != null) { MpcUtils.IsOneAmongStringUrl("dialMusic", dialMusic, false, new List<string>() {"real", "none"}); } if (ringTimeout != null) { if (ringTimeout.GetType() == typeof(System.String)) { MpcUtils.ValidMultipleDestinationIntegers("ringTimeout", ringTimeout); } else if (ringTimeout.GetType() != typeof(System.Int32)) { throw new PlivoValidationException("RingTimeout must be of type int or String"); } } else { ringTimeout = 45; } if (delayDial != null) { if (delayDial.GetType() == typeof(System.String)) { MpcUtils.ValidMultipleDestinationIntegers("delayDial", delayDial); } else if(delayDial.GetType() != typeof(System.Int32)) { throw new PlivoValidationException("DelayDial must be of type int or String"); } } else { delayDial = 0; } if (maxDuration != null) { MpcUtils.ValidRange("maxDuration", maxDuration, false, 300, 28800); } if (maxParticipants != null) { MpcUtils.ValidRange("maxParticipants", maxParticipants, false, 2, 10); } if (waitMusicUrl != null) { MpcUtils.ValidUrl("waitMusicUrl", waitMusicUrl, false); } if (waitMusicMethod != null) { MpcUtils.ValidParamString("waitMusicMethod", waitMusicMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (agentHoldMusicUrl != null) { MpcUtils.ValidUrl("agentHoldMusicUrl", agentHoldMusicUrl, false); } if (agentHoldMusicMethod != null) { MpcUtils.ValidParamString("agentHoldMusicMethod", agentHoldMusicMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (customerHoldMusicUrl != null) { MpcUtils.ValidUrl("customerHoldMusicUrl", customerHoldMusicUrl, false); } if (customerHoldMusicMethod != null) { MpcUtils.ValidParamString("customerHoldMusicMethod", customerHoldMusicMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (recordingCallbackUrl != null) { MpcUtils.ValidUrl("recordingCallbackUrl", recordingCallbackUrl, false); } if (recordingCallbackMethod != null) { MpcUtils.ValidParamString("recordingCallbackMethod", recordingCallbackMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (statusCallbackUrl != null) { MpcUtils.ValidUrl("statusCallbackUrl", statusCallbackUrl, false); } if (statusCallbackMethod != null) { MpcUtils.ValidParamString("statusCallbackMethod", statusCallbackMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (onExitActionUrl != null) { MpcUtils.ValidUrl("onExitActionUrl", onExitActionUrl, false); } if (onExitActionMethod != null) { MpcUtils.ValidParamString("onExitActionMethod", onExitActionMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (recordFileFormat != null) { MpcUtils.ValidParamString("recordFileFormat", recordFileFormat.ToLower(), false, new List<string>() {"mp3", "wav"}); } if (statusCallbackEvents != null) { MpcUtils.MultiValidParam("statusCallbackEvents", statusCallbackEvents.ToLower(), false, true, new List<string>() { "mpc-state-changes", "participant-state-changes", "participant-speak-events", "participant-digit-input-events", "add-participant-api-events" }, ','); } if (enterSound != null) { MpcUtils.IsOneAmongStringUrl("enterSound", enterSound, false, new List<string>() {"beep:1", "beep:2", "none"}); } if (enterSoundMethod != null) { MpcUtils.ValidParamString("enterSoundMethod", enterSoundMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (exitSound != null) { MpcUtils.IsOneAmongStringUrl("exitSound", exitSound, false, new List<string>() {"beep:1", "beep:2", "none"}); } if (exitSoundMethod != null) { MpcUtils.ValidParamString("exitSoundMethod", exitSoundMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (startRecordingAudio != null) { MpcUtils.ValidUrl("startRecordingAudio", startRecordingAudio, false); } if (startRecordingAudioMethod != null) { MpcUtils.ValidParamString("startRecordingAudioMethod", startRecordingAudioMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } if (stopRecordingAudio != null) { MpcUtils.ValidUrl("stopRecordingAudio", stopRecordingAudio, false); } if (stopRecordingAudioMethod != null) { MpcUtils.ValidParamString("stopRecordingAudioMethod", stopRecordingAudioMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> {"role"}; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { role, from, to, callUuid, callerName, callStatusCallbackUrl, callStatusCallbackMethod, sipHeaders, confirmKey, confirmKeySoundUrl, confirmKeySoundMethod, dialMusic, ringTimeout, delayDial, maxDuration, maxParticipants, waitMusicUrl, waitMusicMethod, agentHoldMusicUrl, agentHoldMusicMethod, customerHoldMusicUrl, customerHoldMusicMethod, recordingCallbackUrl, recordingCallbackMethod, statusCallbackUrl, statusCallbackMethod, onExitActionUrl, onExitActionMethod, record, recordFileFormat, statusCallbackEvents, stayAlone, coachMode, mute, hold, startMpcOnEnter, endMpcOnExit, relayDtmfInputs, enterSound, enterSoundMethod, exitSound, exitSoundMethod, startRecordingAudio, startRecordingAudioMethod, stopRecordingAudio, stopRecordingAudioMethod, isVoiceRequest }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run (async () => await Client.Update<MultiPartyCallAddParticipantResponse> (Uri + mpcId + "/Participant/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; JObject responseJson = JObject.Parse(result.Content); result.Object.ApiId = responseJson["api_id"].ToString(); result.Object.RequestUuid = responseJson["request_uuid"].ToString(); result.Object.Message = responseJson["message"].ToString(); } catch (System.NullReferenceException) { } return result.Object; }); } public UpdateResponse<MultiPartyCall> Start(string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } var status = "active"; string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { status, isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var result = Task.Run (async () => await Client.Update<UpdateResponse<MultiPartyCall>> (Uri + mpcId + "/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; } catch (System.NullReferenceException) { } return result.Object; }); } public DeleteResponse<MultiPartyCall> Stop(string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } string mpcId = MakeMpcId(mpcUuid, friendlyName); return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteResource<DeleteResponse<MultiPartyCall>>(mpcId,new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; }); } public RecordCreateResponse<MultiPartyCall> StartRecording ( string mpcUuid = null, string friendlyName = null, string fileFormat = "mp3", string recordingCallbackUrl = null, string recordingCallbackMethod = "POST" ) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } if (fileFormat != null) { MpcUtils.ValidParamString("fileFormat", fileFormat.ToLower(), false, new List<string>() {"mp3", "wav"}); } if (recordingCallbackUrl != null) { MpcUtils.ValidUrl("recordingCallbackUrl", recordingCallbackUrl, false); } if (recordingCallbackMethod != null) { MpcUtils.ValidParamString("recordingCallbackMethod", recordingCallbackMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { fileFormat, recordingCallbackUrl, recordingCallbackMethod, isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var result = Task.Run (async () => await Client.Update<RecordCreateResponse<MultiPartyCall>> (Uri + mpcId + "/Record/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; JObject responseJson = JObject.Parse(result.Content); result.Object.ApiId = responseJson["api_id"].ToString(); result.Object.RecordingId = responseJson["recording_id"].ToString(); result.Object.RecordingUrl = responseJson["recording_url"].ToString(); result.Object.Message = responseJson["message"].ToString(); } catch (System.NullReferenceException) { } return result.Object; }); } public DeleteResponse<MultiPartyCall> StopRecording (string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var result = Task.Run (async () => await Client.Delete<DeleteResponse<MultiPartyCall>> (Uri + mpcId + "/Record/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; } catch (System.NullReferenceException) { } return result.Object; }); } public UpdateResponse<MultiPartyCall> PauseRecording ( string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var result = Task.Run (async () => await Client.Update<UpdateResponse<MultiPartyCall>> (Uri + mpcId + "/Record/Pause/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; } catch (System.NullReferenceException) { } return result.Object; }); } public UpdateResponse<MultiPartyCall> ResumeRecording ( string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var result = Task.Run (async () => await Client.Update<UpdateResponse<MultiPartyCall>> (Uri + mpcId + "/Record/Resume/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; } catch (System.NullReferenceException) { } return result.Object; }); } public RecordCreateResponse<MultiPartyCallParticipant> StartParticipantRecording ( string participantId = null, string mpcUuid = null, string friendlyName = null, string fileFormat = "mp3", string recordingCallbackUrl = null, string recordingCallbackMethod = "POST" ) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } if (fileFormat != null) { MpcUtils.ValidParamString("fileFormat", fileFormat.ToLower(), false, new List<string>() {"mp3", "wav"}); } if (recordingCallbackUrl != null) { MpcUtils.ValidUrl("recordingCallbackUrl", recordingCallbackUrl, false); } if (recordingCallbackMethod != null) { MpcUtils.ValidParamString("recordingCallbackMethod", recordingCallbackMethod.ToUpper(), false, new List<string>() {"GET", "POST"}); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { fileFormat, recordingCallbackUrl, recordingCallbackMethod, isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { return Task.Run(async () => await UpdateSecondaryResource<RecordCreateResponse<MultiPartyCallParticipant>>(mpcId, data, "Participant", participantId + "/Record").ConfigureAwait(false)).Result; }); } public DeleteResponse<MultiPartyCallParticipant> StopParticipantRecording (string participantId = null, string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { return Task.Run(async () => await DeleteSecondaryResource<DeleteResponse<MultiPartyCallParticipant>>(mpcId, data, "Participant", participantId+"/Record").ConfigureAwait(false)).Result; }); } public UpdateResponse<MultiPartyCallParticipant> PauseParticipantRecording ( string participantId = null, string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { return Task.Run(async () => await UpdateSecondaryResource<UpdateResponse<MultiPartyCallParticipant>>(mpcId, data, "Participant", participantId + "/Record/Pause").ConfigureAwait(false)).Result; }); } public UpdateResponse<MultiPartyCallParticipant> ResumeParticipantRecording ( string participantId = null, string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { return Task.Run(async () => await UpdateSecondaryResource<UpdateResponse<MultiPartyCallParticipant>>(mpcId, data, "Participant", participantId + "/Record/Resume").ConfigureAwait(false)).Result; }); } public ListResponse<MultiPartyCallParticipant> ListParticipants( string mpcUuid = null, string friendlyName = null, string callUuid = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } if (callUuid != null) { MpcUtils.ValidParamString("callUuid", callUuid, false); } string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { callUuid, isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var resources = Task.Run (async () => await ListResources<ListResponse<MultiPartyCallParticipant>>(mpcId + "/Participant" , data).ConfigureAwait(false)).Result; resources.Objects.ForEach ( (obj) => obj.Interface = this ); return resources; }); } public MultiPartyCallParticipantUpdateResponse<MultiPartyCallParticipant> UpdateParticipant(string participantId = null, string mpcUuid = null, string friendlyName = null, bool? coachMode = null, bool? mute = null, bool? hold = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { coachMode, mute, hold, isVoiceRequest }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await UpdateSecondaryResource<MultiPartyCallParticipantUpdateResponse<MultiPartyCallParticipant>>(mpcId, data, "Participant", participantId).ConfigureAwait(false)).Result; return result; }); } public MultiPartyCallParticipant GetParticipant(string participantId = null, string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); return ExecuteWithExceptionUnwrap(() => { var mpcParticipant = Task.Run(async () => await GetSecondaryResource<MultiPartyCallParticipant>(mpcId, new Dictionary<string, object>() {{"is_voice_request", true}}, "Participant", participantId).ConfigureAwait(false)).Result; mpcParticipant.Interface = this; return mpcParticipant; }); } public DeleteResponse<MultiPartyCallParticipant> KickParticipant(string participantId = null, string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteSecondaryResource<DeleteResponse<MultiPartyCallParticipant>>(mpcId, new Dictionary<string, object> () { {"is_voice_request", true} }, "Participant", participantId).ConfigureAwait(false)).Result; }); } public MultiPartyCallParticipantPlayResponse<MultiPartyCallParticipant> StartPlayAudio(string participantId = null, string mpcUuid = null, string friendlyName = null, string url = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidUrl("url", url, true); MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> {"url"}; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { url, isVoiceRequest }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run (async () => await Client.Update<MultiPartyCallParticipantPlayResponse<MultiPartyCallParticipant>> (Uri + mpcId + "/Member/" + participantId + "/Play/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; JObject responseJson = JObject.Parse(result.Content); Console.WriteLine(responseJson); result.Object.ApiId = responseJson["api_id"].ToString(); result.Object.MpcMemberId = responseJson["mpcMemberId"].ToObject<List<string>>(); result.Object.MpcName = responseJson["mpcName"].ToString(); result.Object.Message = responseJson["message"].ToString(); } catch (System.NullReferenceException) { } return result.Object; }); } public DeleteResponse<MultiPartyCallParticipant> StopPlayAudio(string participantId = null, string mpcUuid = null, string friendlyName = null) { if (mpcUuid != null) { MpcUtils.ValidParamString("mpcUuid", mpcUuid, false); } if (friendlyName != null) { MpcUtils.ValidParamString("friendlyName", friendlyName, false); } MpcUtils.ValidParamString("participantId", participantId, true); string mpcId = MakeMpcId(mpcUuid, friendlyName); var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData ( mandatoryParams, new { isVoiceRequest }); return ExecuteWithExceptionUnwrap (() => { var result = Task.Run (async () => await Client.Delete<DeleteResponse<MultiPartyCallParticipant>> (Uri + mpcId + "/Member/" + participantId + "/Play/", data).ConfigureAwait (false)).Result; try { result.Object.StatusCode = result.StatusCode; } catch (System.NullReferenceException) { } return result.Object; }); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using Timer=System.Timers.Timer; using Nini.Config; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Scene presence tests /// </summary> [TestFixture] public class ScenePresenceTests { public Scene scene, scene2, scene3; public UUID agent1, agent2, agent3; public static Random random; public ulong region1,region2,region3; public TestCommunicationsManager cm; public AgentCircuitData acd1; public SceneObjectGroup sog1, sog2, sog3; public TestClient testclient; [TestFixtureSetUp] public void Init() { cm = new TestCommunicationsManager(); scene = SceneSetupHelpers.SetupScene("Neighbour x", UUID.Random(), 1000, 1000, cm); scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000, cm); scene3 = SceneSetupHelpers.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000, cm); ISharedRegionModule interregionComms = new RESTInterregionComms(); interregionComms.Initialise(new IniConfigSource()); interregionComms.PostInitialise(); SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms); SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), interregionComms); SceneSetupHelpers.SetupSceneModules(scene3, new IniConfigSource(), interregionComms); agent1 = UUID.Random(); agent2 = UUID.Random(); agent3 = UUID.Random(); random = new Random(); sog1 = NewSOG(UUID.Random(), scene, agent1); sog2 = NewSOG(UUID.Random(), scene, agent1); sog3 = NewSOG(UUID.Random(), scene, agent1); //ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize)); region1 = scene.RegionInfo.RegionHandle; region2 = scene2.RegionInfo.RegionHandle; region3 = scene3.RegionInfo.RegionHandle; } /// <summary> /// Test adding a root agent to a scene. Doesn't yet actually complete crossing the agent into the scene. /// </summary> [Test] public void T010_TestAddRootAgent() { TestHelper.InMethod(); string firstName = "testfirstname"; AgentCircuitData agent = new AgentCircuitData(); agent.AgentID = agent1; agent.firstname = firstName; agent.lastname = "testlastname"; agent.SessionID = UUID.Zero; agent.SecureSessionID = UUID.Zero; agent.circuitcode = 123; agent.BaseFolder = UUID.Zero; agent.InventoryFolder = UUID.Zero; agent.startpos = Vector3.Zero; agent.CapsPath = GetRandomCapsObjectPath(); agent.ChildrenCapSeeds = new Dictionary<ulong, string>(); agent.child = true; string reason; scene.NewUserConnection(agent, out reason); testclient = new TestClient(agent, scene); scene.AddNewClient(testclient); ScenePresence presence = scene.GetScenePresence(agent1); Assert.That(presence, Is.Not.Null, "presence is null"); Assert.That(presence.Firstname, Is.EqualTo(firstName), "First name not same"); acd1 = agent; } /// <summary> /// Test removing an uncrossed root agent from a scene. /// </summary> [Test] public void T011_TestRemoveRootAgent() { TestHelper.InMethod(); scene.RemoveClient(agent1); ScenePresence presence = scene.GetScenePresence(agent1); Assert.That(presence, Is.Null, "presence is not null"); } [Test] public void T012_TestAddNeighbourRegion() { TestHelper.InMethod(); string reason; if (acd1 == null) fixNullPresence(); scene.NewUserConnection(acd1, out reason); if (testclient == null) testclient = new TestClient(acd1, scene); scene.AddNewClient(testclient); ScenePresence presence = scene.GetScenePresence(agent1); presence.MakeRootAgent(new Vector3(90,90,90),false); string cap = presence.ControllingClient.RequestClientInfo().CapsPath; presence.AddNeighbourRegion(region2, cap); presence.AddNeighbourRegion(region3, cap); List<ulong> neighbours = presence.GetKnownRegionList(); Assert.That(neighbours.Count, Is.EqualTo(2)); } public void fixNullPresence() { string firstName = "testfirstname"; AgentCircuitData agent = new AgentCircuitData(); agent.AgentID = agent1; agent.firstname = firstName; agent.lastname = "testlastname"; agent.SessionID = UUID.Zero; agent.SecureSessionID = UUID.Zero; agent.circuitcode = 123; agent.BaseFolder = UUID.Zero; agent.InventoryFolder = UUID.Zero; agent.startpos = Vector3.Zero; agent.CapsPath = GetRandomCapsObjectPath(); acd1 = agent; } [Test] public void T013_TestRemoveNeighbourRegion() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); presence.RemoveNeighbourRegion(region3); List<ulong> neighbours = presence.GetKnownRegionList(); Assert.That(neighbours.Count,Is.EqualTo(1)); /* presence.MakeChildAgent; presence.MakeRootAgent; CompleteAvatarMovement */ } // I'm commenting this test, because this is not supposed to happen here //[Test] public void T020_TestMakeRootAgent() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); Assert.That(presence.IsChildAgent, Is.False, "Starts out as a root agent"); presence.MakeChildAgent(); Assert.That(presence.IsChildAgent, Is.True, "Did not change to child agent after MakeChildAgent"); // Accepts 0 but rejects Constants.RegionSize Vector3 pos = new Vector3(0,Constants.RegionSize-1,0); presence.MakeRootAgent(pos,true); Assert.That(presence.IsChildAgent, Is.False, "Did not go back to root agent"); Assert.That(presence.AbsolutePosition, Is.EqualTo(pos), "Position is not the same one entered"); } // I'm commenting this test because it does not represent // crossings. The Thread.Sleep's in here are not meaningful mocks, // and they sometimes fail in panda. // We need to talk in order to develop a test // that really tests region crossings. There are 3 async components, // but things are synchronous among them. So there should be // 3 threads in here. //[Test] public void T021_TestCrossToNewRegion() { TestHelper.InMethod(); scene.RegisterRegionWithGrid(); scene2.RegisterRegionWithGrid(); // Adding child agent to region 1001 string reason; scene2.NewUserConnection(acd1, out reason); scene2.AddNewClient(testclient); ScenePresence presence = scene.GetScenePresence(agent1); presence.MakeRootAgent(new Vector3(0,Constants.RegionSize-1,0), true); ScenePresence presence2 = scene2.GetScenePresence(agent1); // Adding neighbour region caps info to presence2 string cap = presence.ControllingClient.RequestClientInfo().CapsPath; presence2.AddNeighbourRegion(region1, cap); Assert.That(presence.IsChildAgent, Is.False, "Did not start root in origin region."); Assert.That(presence2.IsChildAgent, Is.True, "Is not a child on destination region."); // Cross to x+1 presence.AbsolutePosition = new Vector3(Constants.RegionSize+1,3,100); presence.Update(); EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing"); // Mimicking communication between client and server, by waiting OK from client // sent by TestClient.CrossRegion call. Originally, this is network comm. if (!wh.WaitOne(5000,false)) { presence.Update(); if (!wh.WaitOne(8000,false)) throw new ArgumentException("1 - Timeout waiting for signal/variable."); } // This is a TestClient specific method that fires OnCompleteMovementToRegion event, which // would normally be fired after receiving the reply packet from comm. done on the last line. testclient.CompleteMovement(); // Crossings are asynchronous int timer = 10; // Make sure cross hasn't already finished if (!presence.IsInTransit && !presence.IsChildAgent) { // If not and not in transit yet, give it some more time Thread.Sleep(5000); } // Enough time, should at least be in transit by now. while (presence.IsInTransit && timer > 0) { Thread.Sleep(1000); timer-=1; } Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 2->1."); Assert.That(presence.IsChildAgent, Is.True, "Did not complete region cross as expected."); Assert.That(presence2.IsChildAgent, Is.False, "Did not receive root status after receiving agent."); // Cross Back presence2.AbsolutePosition = new Vector3(-10, 3, 100); presence2.Update(); if (!wh.WaitOne(5000,false)) { presence2.Update(); if (!wh.WaitOne(8000,false)) throw new ArgumentException("2 - Timeout waiting for signal/variable."); } testclient.CompleteMovement(); if (!presence2.IsInTransit && !presence2.IsChildAgent) { // If not and not in transit yet, give it some more time Thread.Sleep(5000); } // Enough time, should at least be in transit by now. while (presence2.IsInTransit && timer > 0) { Thread.Sleep(1000); timer-=1; } Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 1->2."); Assert.That(presence2.IsChildAgent, Is.True, "Did not return from region as expected."); Assert.That(presence.IsChildAgent, Is.False, "Presence was not made root in old region again."); } [Test] public void T030_TestAddAttachments() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); presence.AddAttachment(sog1); presence.AddAttachment(sog2); presence.AddAttachment(sog3); Assert.That(presence.HasAttachments(), Is.True); Assert.That(presence.ValidateAttachments(), Is.True); } [Test] public void T031_RemoveAttachments() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); presence.RemoveAttachment(sog1); presence.RemoveAttachment(sog2); presence.RemoveAttachment(sog3); Assert.That(presence.HasAttachments(), Is.False); } // I'm commenting this test because scene setup NEEDS InventoryService to // be non-null //[Test] public void T032_CrossAttachments() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); ScenePresence presence2 = scene2.GetScenePresence(agent1); presence2.AddAttachment(sog1); presence2.AddAttachment(sog2); IRegionModule serialiser = new SerialiserModule(); SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), serialiser); SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), serialiser); Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross"); Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful"); Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted"); Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects"); } [TearDown] public void TearDown() { if (MainServer.Instance != null) MainServer.Instance.Stop(); } public static string GetRandomCapsObjectPath() { TestHelper.InMethod(); UUID caps = UUID.Random(); string capsPath = caps.ToString(); capsPath = capsPath.Remove(capsPath.Length - 4, 4); return capsPath; } private SceneObjectGroup NewSOG(UUID uuid, Scene scene, UUID agent) { SceneObjectPart sop = new SceneObjectPart(); sop.Name = RandomName(); sop.Description = RandomName(); sop.Text = RandomName(); sop.SitName = RandomName(); sop.TouchName = RandomName(); sop.UUID = uuid; sop.Shape = PrimitiveBaseShape.Default; sop.Shape.State = 1; sop.OwnerID = agent; SceneObjectGroup sog = new SceneObjectGroup(); sog.SetScene(scene); sog.SetRootPart(sop); return sog; } private static string RandomName() { StringBuilder name = new StringBuilder(); int size = random.Next(5,12); char ch ; for (int i=0; i<size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ; name.Append(ch); } return name.ToString(); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleCQG.SampleCQGPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleCQG { using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using Ecng.Common; using Ecng.Xaml; using MoreLinq; using StockSharp.Messages; using StockSharp.BusinessEntities; using StockSharp.CQG; using StockSharp.Logging; using StockSharp.Xaml; using StockSharp.Localization; public partial class MainWindow { public static MainWindow Instance { get; private set; } public static readonly DependencyProperty IsConnectedProperty = DependencyProperty.Register("IsConnected", typeof(bool), typeof(MainWindow), new PropertyMetadata(default(bool))); public bool IsConnected { get { return (bool)GetValue(IsConnectedProperty); } set { SetValue(IsConnectedProperty, value); } } public CQGTrader Trader { get; private set; } private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); private readonly LogManager _logManager = new LogManager(); private static string Username { get { return Properties.Settings.Default.Username; } } public MainWindow() { Instance = this; InitializeComponent(); Title = Title.Put("CQG"); Closing += OnClosing; _ordersWindow.MakeHideable(); _securitiesWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); var guiListener = new GuiLogListener(LogControl); //guiListener.Filters.Add(msg => msg.Level > LogLevels.Debug); _logManager.Listeners.Add(guiListener); _logManager.Listeners.Add(new FileLogListener("sterling") { LogDirectory = "Logs" }); Application.Current.MainWindow = this; } private void OnClosing(object sender, CancelEventArgs cancelEventArgs) { Properties.Settings.Default.Save(); _ordersWindow.DeleteHideable(); _securitiesWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _securitiesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); if (Trader != null) Trader.Dispose(); } private void ConnectClick(object sender, RoutedEventArgs e) { var pwd = PwdBox.Password; if (!IsConnected) { if (Username.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3751); return; } if (pwd.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str2975); return; } if (Trader == null) { // create connector Trader = new CQGTrader { LogLevel = LogLevels.Debug }; _logManager.Sources.Add(Trader); // subscribe on connection successfully event Trader.Connected += () => { this.GuiAsync(() => OnConnectionChanged(true)); }; // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false)); // subscribe on error event Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, type, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewPortfolios += portfolios => { // subscribe on portfolio updates portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // subscribe on error of order registration event Trader.OrdersRegisterFailed += OrdersFailed; // subscribe on error of order cancelling event Trader.OrdersCancelFailed += OrdersFailed; // subscribe on error of stop-order registration event Trader.StopOrdersRegisterFailed += OrdersFailed; // subscribe on error of stop-order cancelling event Trader.StopOrdersCancelFailed += OrdersFailed; // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; } Trader.Connect(); } else { Trader.Disconnect(); } } private void OnConnectionChanged(bool isConnected) { IsConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void OrdersFailed(IEnumerable<OrderFail> fails) { this.GuiAsync(() => { foreach (var fail in fails) { var msg = fail.Error.ToString(); MessageBox.Show(this, msg, LocalizedStrings.Str2960); } }); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException(nameof(window)); if (window.Visibility == Visibility.Visible) window.Hide(); else window.Show(); } private void ShowMyTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_myTradesWindow); } private void ShowSecuritiesClick(object sender, RoutedEventArgs e) { ShowOrHide(_securitiesWindow); } private void ShowPortfoliosClick(object sender, RoutedEventArgs e) { ShowOrHide(_portfoliosWindow); } private void ShowOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_ordersWindow); } private void ShowStopOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_stopOrdersWindow); } } }