context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region Namespaces using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Text; using Epi.Data.Services; using Epi.Windows; #endregion namespace Epi.Windows.Controls { /// <summary> /// Settings Panel /// </summary> public partial class SettingsPanel : System.Windows.Forms.UserControl { #region Public Event Handlers /// <summary> /// Occurs when the value of RepresentationOfYes property changes. /// </summary> public event System.EventHandler RepresentationOfYesChanged; /// <summary> /// Occurs when the value of RepresentationOfNo property changes. /// </summary> public event System.EventHandler RepresentationOfNoChanged; /// <summary> /// Occurs when the value of RepresentationOfMissing property changes. /// </summary> public event System.EventHandler RepresentationOfMissingChanged; /// <summary> /// Occurs when the value of ShowSelectCriteria property changes. /// </summary> public event System.EventHandler ShowSelectCriteriaChanged; /// <summary> /// Occurs when the value of ShowGraphics property changes. /// </summary> public event System.EventHandler ShowGraphicsChanged; /// <summary> /// Occurs when the value of ShowHyperlinks property changes. /// </summary> public event System.EventHandler ShowHyperlinksChanged; /// <summary> /// Occurs when the value of ShowPrompy property changes. /// </summary> public event System.EventHandler ShowPromptChanged; /// <summary> /// Occurs when the value of ShowPercents property changes. /// </summary> public event System.EventHandler ShowPercentsChanged; /// <summary> /// Occurs when the value of ShowTablesOutput property changes. /// </summary> public event System.EventHandler ShowTablesOutputChanged; /// <summary> /// Occurs when the value of ShowIncludeMissing property changes. /// </summary> public event System.EventHandler ShowIncludeMissingChanged; /// <summary> /// Occurs when the value of StatisticsLevel property changes. /// </summary> public event System.EventHandler StatisticsLevelChanged; /// <summary> /// Occurs when the value of ProcessRecords property changes. /// </summary> public event System.EventHandler ProcessRecordsChanged; /// <summary> /// Occurs when the value of RepresentationOfYes property changes. /// </summary> public event System.EventHandler RepresentationOfYesTextChanged; /// <summary> /// Occurs when the value of RepresentationOfNo property changes. /// </summary> public event System.EventHandler RepresentationOfNoTextChanged; /// <summary> /// Occurs when the value of RepresentationOfMissing property changes. /// </summary> public event System.EventHandler RepresentationOfMissingTextChanged; #endregion #region Constructor /// <summary> /// Constructor for SettingsPanel /// </summary> public SettingsPanel() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } #endregion //Constructor #region Public Methods /// <summary> /// Loads data of the settings pannel. /// </summary> public void LoadMe() { LoadLists(); ShowSettings(); } /// <summary> /// Loads lists for representations of Yes, No and Missing /// </summary> public void LoadLists() { LoadRepresentionsOfYes(); LoadRepresentionsOfNo(); LoadRepresentionsOfMissing(); } /// <summary> /// Loads the settings from the configuration file. /// </summary> public void ShowSettings(Configuration pConfig = null) { Configuration config = null; if (pConfig == null) { config = Configuration.GetNewInstance(); } else { config = pConfig; } Epi.DataSets.Config.SettingsRow settings = config.Settings; // Representation of boolean values ... cmbYesAs.SelectedItem = settings.RepresentationOfYes; cmbNoAs.SelectedItem = settings.RepresentationOfNo; cmbMissingAs.SelectedItem = settings.RepresentationOfMissing; // HTML output options ... cbxShowPrompt.Checked = settings.ShowCompletePrompt; cbxSelectCriteria.Checked = settings.ShowSelection; cbxPercents.Checked = settings.ShowPercents; cbxGraphics.Checked = settings.ShowGraphics; cbxHyperlinks.Checked = settings.ShowHyperlinks; cbxTablesOutput.Checked = settings.ShowTables; // Statistics Options WinUtil.SetSelectedRadioButton(settings.StatisticsLevel.ToString(), gbxStatistics); numericUpDownPrecision.Value = settings.PrecisionForStatistics; // Record Processing WinUtil.SetSelectedRadioButton(settings.RecordProcessingScope.ToString(), gbxProcessRecords); cbxIncludeMissing.Checked = settings.IncludeMissingValues; } /// <summary> /// Saves the current settings to the configuration file. /// </summary> public void GetSettings(Configuration newConfig) { Epi.DataSets.Config.SettingsRow settings = newConfig.Settings; // Representation of boolean values ... settings.RepresentationOfYes = cmbYesAs.Text; settings.RepresentationOfNo = cmbNoAs.Text; settings.RepresentationOfMissing = cmbMissingAs.Text; // HTML output options ... settings.ShowCompletePrompt = cbxShowPrompt.Checked; settings.ShowSelection = cbxSelectCriteria.Checked; settings.ShowPercents = cbxPercents.Checked; settings.ShowGraphics = cbxGraphics.Checked; settings.ShowTables = cbxTablesOutput.Checked; settings.ShowHyperlinks = cbxHyperlinks.Checked; // Statistics Options settings.StatisticsLevel = int.Parse(WinUtil.GetSelectedRadioButton(gbxStatistics).Tag.ToString()); settings.PrecisionForStatistics = numericUpDownPrecision.Value; // Record Processing settings.RecordProcessingScope = int.Parse(WinUtil.GetSelectedRadioButton(gbxProcessRecords).Tag.ToString()); settings.IncludeMissingValues = cbxIncludeMissing.Checked; } #endregion Public Methods #region Public Properties /// <summary> /// Gets a value indicating how to represent the value of Yes /// </summary> public string RepresentationOfYes { get { return cmbYesAs.Text; } } /// <summary> /// Gets a value indicating how to represent the value of No /// </summary> public string RepresentationOfNo { get { return cmbNoAs.Text; } } /// <summary> /// Gets a value indicating how to represent the value of Missing /// </summary> public string RepresentationOfMissing { get { return cmbMissingAs.Text; } } /// <summary> /// Gets a value indicating whether to display the full prompt for variable name /// </summary> public bool ShowPrompt { get { return cbxShowPrompt.Checked; } } /// <summary> /// Gets a value indicating whether to display frequency graph next to the table /// </summary> public bool ShowGraphics { get { return cbxGraphics.Checked; } } /// <summary> /// Gets a value indicating whether to include hyperlinks in the output /// </summary> public bool ShowHyperlinks { get { return cbxHyperlinks.Checked; } } /// <summary> /// Gets a value indicating whether to display the select criteria /// </summary> public bool ShowSelectCriteria { get { return cbxSelectCriteria.Checked; } } /// <summary> /// Gets a value indicating whether to include percantages in Tables output /// </summary> public bool ShowPercents { get { return cbxPercents.Checked; } } /// <summary> /// Gets a value indicating whether to include tabular data in Frequency and Tables output /// </summary> public bool ShowTablesOutput { get { return cbxTablesOutput.Checked; } } /// <summary> /// Gets a value indicating whether to include missing values in Analysis /// </summary> public bool ShowIncludeMissing { get { return cbxIncludeMissing.Checked; } } /// <summary> /// Gets a value indicating the level of detail desired in statistical procedures /// </summary> public RadioButton StatisticLevel { get { return WinUtil.GetSelectedRadioButton(gbxStatistics); } } /// <summary> /// Gets a value indicating whether to include deleted, undeleted or all records in statistical procedures /// </summary> public RadioButton ProcessRecords { get { return WinUtil.GetSelectedRadioButton(gbxProcessRecords); } } #endregion //Public Properties #region Private Methods /// <summary> /// Loads combobox with values for RepresentationsOfYes from application data file /// </summary> private void LoadRepresentionsOfYes() { string currentRepresentationOfYes = Configuration.GetNewInstance().Settings.RepresentationOfYes; DataView dv = AppData.Instance.RepresentationsOfYesDataTable.DefaultView; cmbYesAs.Items.Clear(); if (!string.IsNullOrEmpty(currentRepresentationOfYes)) { cmbYesAs.Items.Add(currentRepresentationOfYes); } dv.Sort = ColumnNames.POSITION; foreach (DataRowView row in dv) { string name = row[ColumnNames.NAME].ToString(); if (name != currentRepresentationOfYes) { cmbYesAs.Items.Add(row[ColumnNames.NAME]); } } cmbYesAs.SelectedIndex = 0; } /// <summary> /// Loads combobox with values for RepresentationsOfNo from application data file /// </summary> private void LoadRepresentionsOfNo() { string currentRepresentationOfNo = Configuration.GetNewInstance().Settings.RepresentationOfNo; DataView dv = AppData.Instance.RepresentationsOfNoDataTable.DefaultView; cmbNoAs.Items.Clear(); if (!string.IsNullOrEmpty(currentRepresentationOfNo)) { cmbNoAs.Items.Add(currentRepresentationOfNo); } dv.Sort = ColumnNames.POSITION; foreach (DataRowView row in dv) { string name = row[ColumnNames.NAME].ToString(); if (name != currentRepresentationOfNo) { cmbNoAs.Items.Add(name); } } cmbNoAs.SelectedIndex = 0; } /// <summary> /// Loads combobox with values for RepresentationsOfMissing from application data file /// </summary> private void LoadRepresentionsOfMissing() { string currentRepresentationOfMissing = Configuration.GetNewInstance().Settings.RepresentationOfMissing; DataView dv = AppData.Instance.RepresentationsOfMissingDataTable.DefaultView; cmbMissingAs.Items.Clear(); if (!string.IsNullOrEmpty(currentRepresentationOfMissing)) { cmbMissingAs.Items.Add(currentRepresentationOfMissing); } dv.Sort = ColumnNames.POSITION; foreach (DataRowView row in dv) { string name = row[ColumnNames.NAME].ToString(); if (name != currentRepresentationOfMissing) { cmbMissingAs.Items.Add(name); } } cmbMissingAs.SelectedIndex = 0; } #endregion Private Methods #region Event Handlers private void SettingsPanel_Load(object sender, System.EventArgs e) { //rdbNormal.Tag = ((short)RecordProcessingScope.Undeleted).ToString(); whut that heck? //LoadMe(); } /// <summary> /// Occurs when RepresentationOfYes property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbYesAs_SelectedIndexChanged(object sender, System.EventArgs e) { if (this.RepresentationOfYesChanged != null) { this.RepresentationOfYesChanged(sender, e); } } /// <summary> /// Occurs when RepresentationOfYes Text property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbYesAs_TextChanged(object sender, System.EventArgs e) { if (this.RepresentationOfYesTextChanged != null) { this.RepresentationOfYesTextChanged(sender, e); } } /// <summary> ///Occurs when RepresentationOfNoproperty changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbNoAs_SelectedIndexChanged(object sender, System.EventArgs e) { if (this.RepresentationOfNoChanged != null) { this.RepresentationOfNoChanged(sender, e); } } private void cmbNoAs_TextChanged(object sender, EventArgs e) { if (this.RepresentationOfNoTextChanged != null) { this.RepresentationOfNoTextChanged(sender,e); } } /// <summary> /// Occurs when RepresentationOfMissing property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbMissingAs_SelectedIndexChanged(object sender, System.EventArgs e) { if (this.RepresentationOfMissingChanged != null) { this.RepresentationOfMissingChanged(sender, e); } } /// <summary> /// Occurs when RepresentationOfMssing property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbMissingAs_TextChanged(object sender, EventArgs e) { if (this.RepresentationOfMissingTextChanged != null) { this.RepresentationOfMissingTextChanged(sender,e); } } /// <summary> /// Occurs when ShowPrompt property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cbxShowPrompt_CheckedChanged(object sender, System.EventArgs e) { if (this.ShowPromptChanged != null) { this.ShowPromptChanged(sender, e); } } /// <summary> /// Occurs when ShowSelectCriteria property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cbxSelectCriteria_CheckedChanged(object sender, System.EventArgs e) { if (this.ShowSelectCriteriaChanged != null) { this.ShowSelectCriteriaChanged(sender, e); } } /// <summary> /// Occurs when ShowGraphics property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cbxGraphics_CheckedChanged(object sender, System.EventArgs e) { if (this.ShowGraphicsChanged != null) { this.ShowGraphicsChanged(sender, e); } } /// <summary> /// Occurs when ShowPercents property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cbxPercents_CheckedChanged(object sender, System.EventArgs e) { if (this.ShowPercentsChanged != null) { this.ShowPercentsChanged(sender, e); } } /// <summary> /// Occurs when ShowHyperlinks property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cbxHyperlinks_CheckedChanged(object sender, System.EventArgs e) { if (this.ShowHyperlinksChanged != null) { this.ShowHyperlinksChanged(sender, e); } } /// <summary> /// Occurs when ShowTablesOutput property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cbxTablesOutput_CheckedChanged(object sender, System.EventArgs e) { if (this.ShowTablesOutputChanged != null) { this.ShowTablesOutputChanged(sender, e); } } /// <summary> /// Occurs when the value of StatisticsLevel property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void StatisticsRadioButtonClick(object sender, System.EventArgs e) { if (this.StatisticsLevelChanged != null) { this.StatisticsLevelChanged(sender, e); } } /// <summary> ///Occures when the value of ProcessRecords changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void ProcessRecordsRadioButtonClick(object sender, System.EventArgs e) { if (this.ProcessRecordsChanged != null) { this.ProcessRecordsChanged(sender, e); } } /// <summary> /// Occurs when ShowIncludeMissinge property changes. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cbxIncludeMissing_CheckedChanged(object sender, System.EventArgs e) { if (this.ShowIncludeMissingChanged != null) { this.ShowIncludeMissingChanged(sender, e); } } #endregion Event Handlers } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; #if DEBUG using System.Diagnostics; #endif using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Base type of all asynchronous tagger providers (<see cref="ITaggerProvider"/> and <see cref="IViewTaggerProvider"/>). /// </summary> internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> : ForegroundThreadAffinitizedObject where TTag : ITag { private readonly object _uniqueKey = new object(); private readonly IAsynchronousOperationListener _asyncListener; private readonly IForegroundNotificationService _notificationService; /// <summary> /// The behavior the tagger engine will have when text changes happen to the subject buffer /// it is attached to. Most taggers can simply use <see cref="TaggerTextChangeBehavior.None"/>. /// However, advanced taggers that want to perform specialized behavior depending on what has /// actually changed in the file can specify <see cref="TaggerTextChangeBehavior.TrackTextChanges"/>. /// /// If this is specified the tagger engine will track text changes and pass them along as /// <see cref="TaggerContext{TTag}.TextChangeRange"/> when calling /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.None; /// <summary> /// The behavior the tagger will have when changes happen to the caret. /// </summary> protected virtual TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.None; /// <summary> /// The behavior of tags that are created by the async tagger. This will matter for tags /// created for a previous version of a document that are mapped forward by the async /// tagging architecture. This value cannot be <see cref="SpanTrackingMode.Custom"/>. /// </summary> protected virtual SpanTrackingMode SpanTrackingMode => SpanTrackingMode.EdgeExclusive; /// <summary> /// Comparer used to determine if two <see cref="ITag"/>s are the same. This is used by /// the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> to determine if a previous set of /// computed tags and a current set of computed tags should be considered the same or not. /// If they are the same, then the UI will not be updated. If they are different then /// the UI will be updated for sets of tags that have been removed or added. /// </summary> protected virtual IEqualityComparer<TTag> TagComparer => EqualityComparer<TTag>.Default; /// <summary> /// Options controlling this tagger. The tagger infrastructure will check this option /// against the buffer it is associated with to see if it should tag or not. /// /// An empty enumerable, or null, can be returned to indicate that this tagger should /// run unconditionally. /// </summary> protected virtual IEnumerable<Option<bool>> Options => SpecializedCollections.EmptyEnumerable<Option<bool>>(); protected virtual IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.EmptyEnumerable<PerLanguageOption<bool>>(); #if DEBUG public readonly string StackTrace; #endif protected AbstractAsynchronousTaggerProvider( IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService) { _asyncListener = asyncListener; _notificationService = notificationService; #if DEBUG StackTrace = new StackTrace().ToString(); #endif } private TagSource CreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return new TagSource(textViewOpt, subjectBuffer, this, _asyncListener, _notificationService); } internal IAccurateTagger<T> GetOrCreateTagger<T>(ITextView textViewOpt, ITextBuffer subjectBuffer) where T : ITag { if (!subjectBuffer.GetOption(EditorComponentOnOffOptions.Tagger)) { return null; } var tagSource = GetOrCreateTagSource(textViewOpt, subjectBuffer); return tagSource == null ? null : new Tagger(this._asyncListener, this._notificationService, tagSource, subjectBuffer) as IAccurateTagger<T>; } private TagSource GetOrCreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { TagSource tagSource; if (!this.TryRetrieveTagSource(textViewOpt, subjectBuffer, out tagSource)) { tagSource = this.CreateTagSource(textViewOpt, subjectBuffer); if (tagSource == null) { return null; } this.StoreTagSource(textViewOpt, subjectBuffer, tagSource); tagSource.Disposed += (s, e) => this.RemoveTagSource(textViewOpt, subjectBuffer); } return tagSource; } private bool TryRetrieveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, out TagSource tagSource) { return textViewOpt != null ? textViewOpt.TryGetPerSubjectBufferProperty(subjectBuffer, _uniqueKey, out tagSource) : subjectBuffer.Properties.TryGetProperty(_uniqueKey, out tagSource); } private void RemoveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { if (textViewOpt != null) { textViewOpt.RemovePerSubjectBufferProperty<TagSource, ITextView>(subjectBuffer, _uniqueKey); } else { subjectBuffer.Properties.RemoveProperty(_uniqueKey); } } private void StoreTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, TagSource tagSource) { if (textViewOpt != null) { textViewOpt.AddPerSubjectBufferProperty(subjectBuffer, _uniqueKey, tagSource); } else { subjectBuffer.Properties.AddProperty(_uniqueKey, tagSource); } } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to /// determine the caret position. This value will be passed in as the value to /// <see cref="TaggerContext{TTag}.CaretPosition"/> in the call to /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer) { return textViewOpt?.GetCaretPoint(subjectBuffer); } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to determine /// the set of spans that it should asynchronously tag. This will be called in response to /// notifications from the <see cref="ITaggerEventSource"/> that something has changed, and /// will only be called from the UI thread. The tagger infrastructure will then determine /// the <see cref="DocumentSnapshotSpan"/>s associated with these <see cref="SnapshotSpan"/>s /// and will asynchronously call into <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> at some point in /// the future to produce tags for these spans. /// </summary> protected virtual IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer) { // For a standard tagger, the spans to tag is the span of the entire snapshot. return new[] { subjectBuffer.CurrentSnapshot.GetFullSpan() }; } /// <summary> /// Creates the <see cref="ITaggerEventSource"/> that notifies the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> /// that it should recompute tags for the text buffer after an appropriate <see cref="TaggerDelay"/>. /// </summary> protected abstract ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer); internal Task ProduceTagsAsync_ForTestingPurposesOnly(TaggerContext<TTag> context) { return ProduceTagsAsync(context); } /// <summary> /// Produce tags for the given context. /// </summary> protected virtual async Task ProduceTagsAsync(TaggerContext<TTag> context) { foreach (var spanToTag in context.SpansToTag) { context.CancellationToken.ThrowIfCancellationRequested(); await ProduceTagsAsync(context, spanToTag, GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan)).ConfigureAwait(false); } } private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan) { return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot ? caretPosition.Value.Position : (int?)null; } protected virtual Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { return SpecializedTasks.EmptyTask; } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class GeneratorExpression : Expression { protected Expression _expression; protected DeclarationCollection _declarations; protected Expression _iterator; protected StatementModifier _filter; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public GeneratorExpression CloneNode() { return (GeneratorExpression)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public GeneratorExpression CleanClone() { return (GeneratorExpression)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.GeneratorExpression; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnGeneratorExpression(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( GeneratorExpression)node; if (!Node.Matches(_expression, other._expression)) return NoMatch("GeneratorExpression._expression"); if (!Node.AllMatch(_declarations, other._declarations)) return NoMatch("GeneratorExpression._declarations"); if (!Node.Matches(_iterator, other._iterator)) return NoMatch("GeneratorExpression._iterator"); if (!Node.Matches(_filter, other._filter)) return NoMatch("GeneratorExpression._filter"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_expression == existing) { this.Expression = (Expression)newNode; return true; } if (_declarations != null) { Declaration item = existing as Declaration; if (null != item) { Declaration newItem = (Declaration)newNode; if (_declarations.Replace(item, newItem)) { return true; } } } if (_iterator == existing) { this.Iterator = (Expression)newNode; return true; } if (_filter == existing) { this.Filter = (StatementModifier)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { GeneratorExpression clone = new GeneratorExpression(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._expressionType = _expressionType; if (null != _expression) { clone._expression = _expression.Clone() as Expression; clone._expression.InitializeParent(clone); } if (null != _declarations) { clone._declarations = _declarations.Clone() as DeclarationCollection; clone._declarations.InitializeParent(clone); } if (null != _iterator) { clone._iterator = _iterator.Clone() as Expression; clone._iterator.InitializeParent(clone); } if (null != _filter) { clone._filter = _filter.Clone() as StatementModifier; clone._filter.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; _expressionType = null; if (null != _expression) { _expression.ClearTypeSystemBindings(); } if (null != _declarations) { _declarations.ClearTypeSystemBindings(); } if (null != _iterator) { _iterator.ClearTypeSystemBindings(); } if (null != _filter) { _filter.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Expression { get { return _expression; } set { if (_expression != value) { _expression = value; if (null != _expression) { _expression.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Declaration))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public DeclarationCollection Declarations { get { return _declarations ?? (_declarations = new DeclarationCollection(this)); } set { if (_declarations != value) { _declarations = value; if (null != _declarations) { _declarations.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Iterator { get { return _iterator; } set { if (_iterator != value) { _iterator = value; if (null != _iterator) { _iterator.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public StatementModifier Filter { get { return _filter; } set { if (_filter != value) { _filter = value; if (null != _filter) { _filter.InitializeParent(this); } } } } } }
// 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.Diagnostics.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Notes about PersianCalendar // //////////////////////////////////////////////////////////////////////////// // Modern Persian calendar is a solar observation based calendar. Each new year begins on the day when the vernal equinox occurs before noon. // The epoch is the date of the vernal equinox prior to the epoch of the Islamic calendar (March 19, 622 Julian or March 22, 622 Gregorian) // There is no Persian year 0. Ordinary years have 365 days. Leap years have 366 days with the last month (Esfand) gaining the extra day. /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 0622/03/22 9999/12/31 ** Persian 0001/01/01 9378/10/13 */ public class PersianCalendar : Calendar { public static readonly int PersianEra = 1; internal static long PersianEpoch = new DateTime(622, 3, 22).Ticks / GregorianCalendar.TicksPerDay; const int ApproximateHalfYear = 180; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; internal const int MonthsPerYear = 12; internal static int[] DaysToMonth = { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 }; internal const int MaxCalendarYear = 9378; internal const int MaxCalendarMonth = 10; internal const int MaxCalendarDay = 13; // Persian calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 3, day: 22) // This is the minimal Gregorian date that we support in the PersianCalendar. internal static DateTime minDate = new DateTime(622, 3, 22); internal static DateTime maxDate = DateTime.MaxValue; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of PersianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ /* internal static Calendar GetDefaultInstance() { if (m_defaultInstance == null) { m_defaultInstance = new PersianCalendar(); } return (m_defaultInstance); } */ public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } // Return the type of the Persian calendar. // //public override CalendarAlgorithmType AlgorithmType { // get { // return CalendarAlgorithmType.SolarCalendar; // } //} // Construct an instance of Persian calendar. public PersianCalendar() { } internal override CalendarId BaseCalendarID { get { return CalendarId.GREGORIAN; } } internal override CalendarId ID { get { return CalendarId.PERSIAN; } } /*=================================GetAbsoluteDatePersian========================== **Action: Gets the Absolute date for the given Persian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: **Arguments: **Exceptions: ============================================================================*/ long GetAbsoluteDatePersian(int year, int month, int day) { if (year >= 1 && year <= MaxCalendarYear && month >= 1 && month <= 12) { int ordinalDay = DaysInPreviousMonths(month) + day - 1; // day is one based, make 0 based since this will be the number of days we add to beginning of year below int approximateDaysFromEpochForYearStart = (int)(CalendricalCalculationsHelper.MeanTropicalYearInDays * (year - 1)); long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(PersianEpoch + approximateDaysFromEpochForYearStart + ApproximateHalfYear); yearStart += ordinalDay; return yearStart; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } static internal void CheckTicksRange(long ticks) { if (ticks < minDate.Ticks || ticks > maxDate.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, minDate, maxDate)); } } static internal void CheckEraRange(int era) { if (era != CurrentEra && era != PersianEra) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } } static internal void CheckYearRange(int year, int era) { CheckEraRange(era); if (year < 1 || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear)); } } static internal void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { if (month > MaxCalendarMonth) { throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarMonth)); } } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month); } } static int MonthFromOrdinalDay(int ordinalDay) { Contract.Assert(ordinalDay <= 366); int index = 0; while (ordinalDay > DaysToMonth[index]) index++; return index; } static int DaysInPreviousMonths(int month) { Contract.Assert(1 <= month && month <= 12); --month; // months are one based but for calculations use 0 based return DaysToMonth[month]; } /*=================================GetDatePart========================== **Action: Returns a given date part of this <i>DateTime</i>. This method is used ** to compute the year, day-of-year, month, or day part. **Returns: **Arguments: **Exceptions: ArgumentException if part is incorrect. ============================================================================*/ internal int GetDatePart(long ticks, int part) { long NumDays; // The calculation buffer in number of days. CheckTicksRange(ticks); // // Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D. // 1/1/0001 is absolute date 1. // NumDays = ticks / GregorianCalendar.TicksPerDay + 1; // // Calculate the appromixate Persian Year. // long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays); int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1; Contract.Assert(y >= 1); if (part == DatePartYear) { return y; } // // Calculate the Persian Month. // int ordinalDay = (int)(NumDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1))); if (part == DatePartDayOfYear) { return ordinalDay; } int m = MonthFromOrdinalDay(ordinalDay); Contract.Assert(ordinalDay >= 1); Contract.Assert(m >= 1 && m <= 12); if (part == DatePartMonth) { return m; } int d = ordinalDay - DaysInPreviousMonths(m); Contract.Assert(1 <= d); Contract.Assert(d <= 31); // // Calculate the Persian Day. // if (part == DatePartDay) { return (d); } // Incorrect part value. throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); // Get the date in Persian calendar. int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int days = GetDaysInMonth(y, m); if (d > days) { d = days; } long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); if ((month == MaxCalendarMonth) && (year == MaxCalendarYear)) { return MaxCalendarDay; } int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1]; if ((month == MonthsPerYear) && !IsLeapYear(year)) { Contract.Assert(daysInMonth == 30); --daysInMonth; } return daysInMonth; } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { return DaysToMonth[MaxCalendarMonth - 1] + MaxCalendarDay; } // Common years have 365 days. Leap years have 366 days. return (IsLeapYear(year, CurrentEra) ? 366 : 365); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return (PersianEra); } public override int[] Eras { get { return (new int[] { PersianEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { return MaxCalendarMonth; } return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and MaxCalendarYear. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { // The year/month/era value checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, month)); } return (IsLeapYear(year, era) && month == 12 && day == 30); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { CheckYearRange(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { CheckYearRange(year, era); if (year == MaxCalendarYear) { return false; } return (GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1)) == 366; } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { // The year/month/era checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { // BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day); throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Day, daysInMonth, month)); } long lDate = GetAbsoluteDatePersian(year, month, day); if (lDate >= 0) { return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond))); } else { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1410; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( "value", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return (base.ToFourDigitYear(year)); } if (year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxCalendarYear)); } return (year); } } }
using System; using System.Net; using System.Threading.Tasks; using LianZhao.Patterns.Func; using Action = System.Action; using Void = LianZhao.Void; namespace WikiaWP { public class WikiAsyncFunc<TResult> { private readonly IAsyncFunc<ApiClient, TResult> _func; private Action<UnhandledErrorEventArgs<Exception>> _onError; private Action<bool> _onFinally; public WikiAsyncFunc( IAsyncFunc<ApiClient, TResult> func, Action<UnhandledErrorEventArgs<Exception>> onError = null, Action<bool> onFinally = null) { if (func == null) { throw new ArgumentNullException("func"); } _func = func; _onError = onError; _onFinally = onFinally; } public async Task<TResult> InvokeAsync() { var success = false; try { TResult result; using (var api = new ApiClient()) { result = await _func.InvokeAsync(api); } success = true; return result; } catch (Exception ex) { if (_onError == null) { throw; } var e = new UnhandledErrorEventArgs<Exception>(ex); _onError(e); if (e.Handled) { return e.Result; } throw; } finally { if (_onFinally != null) { _onFinally(success); } } } public WikiAsyncFunc<TResult> OnError(Action<UnhandledErrorEventArgs<Exception>> handler) { _onError += handler; return this; } public WikiAsyncFunc<TResult> OnFinally(Action<bool> handler) { _onFinally += handler; return this; } public class UnhandledErrorEventArgs<TError> : EventArgs { public TError Error { get; private set; } public bool Handled { get; private set; } public TResult Result { get; private set; } public UnhandledErrorEventArgs(TError error) { Error = error; } public void SetHandled(TResult result = default (TResult)) { Handled = true; Result = result; } } } public static class WikiAsyncFunc { public static WikiAsyncFunc<TResult> Create<TResult>( IAsyncFunc<ApiClient, TResult> func, Action<WikiAsyncFunc<TResult>.UnhandledErrorEventArgs<Exception>> onError = null, Action<bool> onFinally = null) { return new WikiAsyncFunc<TResult>(func, onError, onFinally); } public static WikiAsyncFunc<TResult> Create<TResult>( Func<ApiClient, Task<TResult>> func, Action<WikiAsyncFunc<TResult>.UnhandledErrorEventArgs<Exception>> onError = null, Action<bool> onFinally = null) { return new WikiAsyncFunc<TResult>(AsyncFunc.FromDelegate(func), onError, onFinally); } public static WikiAsyncFunc<Void> Create( IAsyncFunc<ApiClient, Void> func, Action<WikiAsyncFunc<Void>.UnhandledErrorEventArgs<Exception>> onError = null, Action<bool> onFinally = null) { return new WikiAsyncFunc<Void>(func, onError, onFinally); } public static WikiAsyncFunc<Void> Create( Func<ApiClient, Task> func, Action<WikiAsyncFunc<Void>.UnhandledErrorEventArgs<Exception>> onError = null, Action<bool> onFinally = null) { return new WikiAsyncFunc<Void>(AsyncAction.FromDelegate(func), onError, onFinally); } public static WikiAsyncFunc<TResult> OnHttpError<TResult>( this WikiAsyncFunc<TResult> wikiFunc, Action<WikiAsyncFunc<TResult>.UnhandledErrorEventArgs<HttpStatusCode>> handler) { Action<WikiAsyncFunc<TResult>.UnhandledErrorEventArgs<Exception>> errorHandler = e => { if (e.Handled) { return; } var httpStatusCodeProvider = e.Error as IFunc<Void, HttpStatusCode>; if (httpStatusCodeProvider == null) { return; } var args = new WikiAsyncFunc<TResult>.UnhandledErrorEventArgs<HttpStatusCode>( httpStatusCodeProvider.Invoke()); handler.Invoke(args); if (args.Handled) { e.SetHandled(args.Result); } }; return wikiFunc.OnError(errorHandler); } public static WikiAsyncFunc<TResult> IgnoreHttpError<TResult>( this WikiAsyncFunc<TResult> wikiFunc, HttpStatusCode error, Func<TResult> func) { Action<WikiAsyncFunc<TResult>.UnhandledErrorEventArgs<HttpStatusCode>> errorHandler = e => { if (e.Handled) { return; } if (error == e.Error) { e.SetHandled(func.Invoke()); } }; return wikiFunc.OnHttpError(errorHandler); } public static WikiAsyncFunc<TResult> IgnoreAllError<TResult>( this WikiAsyncFunc<TResult> wikiFunc, Func<TResult> func) { Action<WikiAsyncFunc<TResult>.UnhandledErrorEventArgs<Exception>> errorHandler = e => { if (e.Handled) { return; } e.SetHandled(func.Invoke()); }; return wikiFunc.OnError(errorHandler); } public static WikiAsyncFunc<Void> IgnoreHttpError( this WikiAsyncFunc<Void> wikiFunc, HttpStatusCode error, Action action) { Action<WikiAsyncFunc<Void>.UnhandledErrorEventArgs<HttpStatusCode>> errorHandler = e => { if (e.Handled) { return; } if (error == e.Error) { action.Invoke(); e.SetHandled(); } }; return wikiFunc.OnHttpError(errorHandler); } public static WikiAsyncFunc<Void> IgnoreError( this WikiAsyncFunc<Void> wikiFunc, Action<Exception> action = null) { Action<WikiAsyncFunc<Void>.UnhandledErrorEventArgs<Exception>> errorHandler = e => { if (e.Handled) { return; } if (action != null) { action.Invoke(e.Error); } e.SetHandled(Void.Instance); }; return wikiFunc.OnError(errorHandler); } } }
/* ** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $ ** Some generic functions over Lua objects ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; namespace SharpLua { using TValue = Lua.lua_TValue; using StkId = Lua.lua_TValue; using lu_byte = System.Byte; using lua_Number = System.Double; using l_uacNumber = System.Double; using Instruction = System.UInt32; public partial class Lua { /* tags for values visible from Lua */ public const int LAST_TAG = LUA_TTHREAD; public const int NUM_TAGS = (LAST_TAG + 1); /* ** Extra tags for non-values */ public const int LUA_TPROTO = (LAST_TAG + 1); public const int LUA_TUPVAL = (LAST_TAG + 2); public const int LUA_TDEADKEY = (LAST_TAG + 3); public interface ArrayElement { void set_index(int index); void set_array(object array); } /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ public class CommonHeader { public GCObject next; public lu_byte tt; public lu_byte marked; } /* ** Common header in struct form */ public class GCheader : CommonHeader { }; /* ** Union of all Lua values (in c# we use virtual data members and boxing) */ public class Value { // in the original code Value is a struct, so all assignments in the code // need to be replaced with a call to Copy. as it turns out, there are only // a couple. the vast majority of references to Value are the instance that // appears in the TValue class, so if you make that a virtual data member and // omit the set accessor then you'll get a compiler error if anything tries // to set it. public void Copy(Value copy) { this.p = copy.p; } public GCObject gc { get { return (GCObject)this.p; } set { this.p = value; } } public object p; public lua_Number n { get { return (lua_Number)this.p; } set { this.p = (object)value; } } public int b { get { return (int)this.p; } set { this.p = (object)value; } } }; /* ** Tagged Values */ //#define TValuefields Value value; int tt public class lua_TValue : ArrayElement { private lua_TValue[] values = null; private int index = -1; public void set_index(int index) { this.index = index; } public void set_array(object array) { this.values = (lua_TValue[])array; Debug.Assert(this.values != null); } public lua_TValue this[int offset] { get { return this.values[this.index + offset]; } set { this.values[this.index + offset] = value; } } public lua_TValue this[uint offset] { get { return this.values[this.index + (int)offset]; } set { this.values[this.index + (int)offset] = value; } } public static lua_TValue operator +(lua_TValue value, int offset) { return value.values[value.index + offset]; } public static lua_TValue operator +(int offset, lua_TValue value) { return value.values[value.index + offset]; } public static lua_TValue operator -(lua_TValue value, int offset) { return value.values[value.index - offset]; } public static int operator -(lua_TValue value, lua_TValue[] array) { Debug.Assert(value.values == array); return value.index; } public static int operator -(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index - b.index; } public static bool operator <(lua_TValue a, lua_TValue b) { //Console.WriteLine(a.values.Length + " " + b.values.Length); Debug.Assert(a.values == b.values); return a.index < b.index; } public static bool operator <=(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index <= b.index; } public static bool operator >(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index > b.index; } public static bool operator >=(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index >= b.index; } public static lua_TValue inc(ref lua_TValue value) { value = value[1]; return value[-1]; } public static lua_TValue dec(ref lua_TValue value) { value = value[-1]; return value[1]; } public static implicit operator int(lua_TValue value) { return value.index; } public lua_TValue() { } public lua_TValue(lua_TValue copy) { this.values = copy.values; this.index = copy.index; this.value.Copy(copy.value); this.tt = copy.tt; } public lua_TValue(Value value, int tt) { this.values = null; this.index = 0; this.value.Copy(value); this.tt = tt; } public Value value = new Value(); public int tt; }; /* Macros to test type */ internal static bool ttisnil(TValue o) { return (ttype(o) == LUA_TNIL); } internal static bool ttisnumber(TValue o) { return (ttype(o) == LUA_TNUMBER); } internal static bool ttisstring(TValue o) { return (ttype(o) == LUA_TSTRING); } internal static bool ttistable(TValue o) { return (ttype(o) == LUA_TTABLE); } internal static bool ttisfunction(TValue o) { return (ttype(o) == LUA_TFUNCTION); } internal static bool ttisboolean(TValue o) { return (ttype(o) == LUA_TBOOLEAN); } internal static bool ttisuserdata(TValue o) { return (ttype(o) == LUA_TUSERDATA); } internal static bool ttisthread(TValue o) { return (ttype(o) == LUA_TTHREAD); } internal static bool ttislightuserdata(TValue o) { return (ttype(o) == LUA_TLIGHTUSERDATA); } /* Macros to access values */ #if DEBUG public static int ttype(TValue o) { return o.tt; } public static int ttype(CommonHeader o) { return o.tt; } public static GCObject gcvalue(TValue o) { return (GCObject)check_exp(iscollectable(o), o.value.gc); } public static object pvalue(TValue o) { return (object)check_exp(ttislightuserdata(o), o.value.p); } public static lua_Number nvalue(TValue o) { return (lua_Number)check_exp(ttisnumber(o), o.value.n); } public static TString rawtsvalue(TValue o) { return (TString)check_exp(ttisstring(o), o.value.gc.ts); } public static TString_tsv tsvalue(TValue o) { return rawtsvalue(o).tsv; } public static Udata rawuvalue(TValue o) { return (Udata)check_exp(ttisuserdata(o), o.value.gc.u); } public static Udata_uv uvalue(TValue o) { return rawuvalue(o).uv; } public static Closure clvalue(TValue o) { return (Closure)check_exp(ttisfunction(o), o.value.gc.cl); } public static Table hvalue(TValue o) { return (Table)check_exp(ttistable(o), o.value.gc.h); } public static int bvalue(TValue o) { return (int)check_exp(ttisboolean(o), o.value.b); } public static LuaState thvalue(TValue o) { return (LuaState)check_exp(ttisthread(o), o.value.gc.th); } #else public static int ttype(TValue o) { return o.tt; } public static int ttype(CommonHeader o) { return o.tt; } public static GCObject gcvalue(TValue o) { return o.value.gc; } public static object pvalue(TValue o) { return o.value.p; } public static lua_Number nvalue(TValue o) { return o.value.n; } public static TString rawtsvalue(TValue o) { return o.value.gc.ts; } public static TString_tsv tsvalue(TValue o) { return rawtsvalue(o).tsv; } public static Udata rawuvalue(TValue o) { return o.value.gc.u; } public static Udata_uv uvalue(TValue o) { return rawuvalue(o).uv; } public static Closure clvalue(TValue o) { return o.value.gc.cl; } public static Table hvalue(TValue o) { return o.value.gc.h; } public static int bvalue(TValue o) { return o.value.b; } public static LuaState thvalue(TValue o) { return (LuaState)check_exp(ttisthread(o), o.value.gc.th); } #endif public static int l_isfalse(TValue o) { return ((ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))) ? 1 : 0; } /* ** for internal debug only */ [Conditional("DEBUG")] internal static void checkconsistency(TValue obj) { lua_assert(!iscollectable(obj) || (ttype(obj) == (obj).value.gc.gch.tt)); } [Conditional("DEBUG")] internal static void checkliveness(GlobalState g, TValue obj) { lua_assert(!iscollectable(obj) || ((ttype(obj) == obj.value.gc.gch.tt) && !isdead(g, obj.value.gc))); } /* Macros to set values */ internal static void setnilvalue(TValue obj) { obj.tt = LUA_TNIL; } internal static void setnvalue(TValue obj, lua_Number x) { obj.value.n = x; obj.tt = LUA_TNUMBER; } internal static void setpvalue(TValue obj, object x) { obj.value.p = x; obj.tt = LUA_TLIGHTUSERDATA; } internal static void setbvalue(TValue obj, int x) { obj.value.b = x; obj.tt = LUA_TBOOLEAN; } internal static void setsvalue(LuaState L, TValue obj, GCObject x) { obj.value.gc = x; obj.tt = LUA_TSTRING; checkliveness(G(L), obj); } internal static void setuvalue(LuaState L, TValue obj, GCObject x) { obj.value.gc = x; obj.tt = LUA_TUSERDATA; checkliveness(G(L), obj); } internal static void setthvalue(LuaState L, TValue obj, GCObject x) { obj.value.gc = x; obj.tt = LUA_TTHREAD; checkliveness(G(L), obj); } internal static void setclvalue(LuaState L, TValue obj, Closure x) { obj.value.gc = x; obj.tt = LUA_TFUNCTION; checkliveness(G(L), obj); } internal static void sethvalue(LuaState L, TValue obj, Table x) { obj.value.gc = x; obj.tt = LUA_TTABLE; checkliveness(G(L), obj); } internal static void setptvalue(LuaState L, TValue obj, Proto x) { obj.value.gc = x; obj.tt = LUA_TPROTO; checkliveness(G(L), obj); } internal static void setobj(LuaState L, TValue obj1, TValue obj2) { obj1.value.Copy(obj2.value); obj1.tt = obj2.tt; checkliveness(G(L), obj1); } /* ** different types of sets, according to destination */ /* from stack to (same) stack */ //#define setobjs2s setobj public static void setobjs2s(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); } ///* to stack (not from same stack) */ //#define setobj2s setobj public static void setobj2s(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); } //#define setsvalue2s setsvalue public static void setsvalue2s(LuaState L, TValue obj, TString x) { setsvalue(L, obj, x); } //#define sethvalue2s sethvalue public static void sethvalue2s(LuaState L, TValue obj, Table x) { sethvalue(L, obj, x); } //#define setptvalue2s setptvalue public static void setptvalue2s(LuaState L, TValue obj, Proto x) { setptvalue(L, obj, x); } ///* from table to same table */ //#define setobjt2t setobj public static void setobjt2t(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); } ///* to table */ //#define setobj2t setobj public static void setobj2t(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); } ///* to new object */ //#define setobj2n setobj public static void setobj2n(LuaState L, TValue obj, TValue x) { setobj(L, obj, x); } //#define setsvalue2n setsvalue public static void setsvalue2n(LuaState L, TValue obj, TString x) { setsvalue(L, obj, x); } public static void setttype(TValue obj, int tt) { obj.tt = tt; } public static bool iscollectable(TValue o) { return (ttype(o) >= LUA_TSTRING); } //typedef TValue *StkId; /* index to stack elements */ /* ** String headers for string table */ public class TString_tsv : GCObject { public lu_byte reserved; public uint hash; public uint len; }; public class TString : TString_tsv { //public L_Umaxalign dummy; /* ensures maximum alignment for strings */ public TString_tsv tsv { get { return this; } } public TString() { } public TString(CharPtr str) { this.str = str; } public CharPtr str; public override string ToString() { return str.ToString(); } // for debugging }; public static CharPtr getstr(TString ts) { return ts.str; } public static CharPtr svalue(StkId o) { return getstr(rawtsvalue(o)); } public class Udata_uv : GCObject { public Table metatable; public Table env; public uint len; }; public class Udata : Udata_uv { public Udata() { this.uv = this; } public new Udata_uv uv; //public L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ // in the original C code this was allocated alongside the structure memory. it would probably // be possible to still do that by allocating memory and pinning it down, but we can do the // same thing just as easily by allocating a seperate byte array for it instead. public object user_data; }; /* ** Function Prototypes */ public class Proto : GCObject { public Proto[] protos = null; public int index = 0; public Proto this[int offset] { get { return this.protos[this.index + offset]; } } public TValue[] k; /* constants used by the function */ //public Instruction[] code; public uint[] code; public new Proto[] p; /* functions defined inside the function */ public int[] lineinfo; /* map from opcodes to source lines */ public LocVar[] locvars; /* information about local variables */ public TString[] upvalues; /* upvalue names */ public TString source; public int sizeupvalues; public int sizek; /* size of `k' */ public int sizecode; public int sizelineinfo; public int sizep; /* size of `p' */ public int sizelocvars; public int linedefined; public int lastlinedefined; public GCObject gclist; public lu_byte nups; /* number of upvalues */ public lu_byte numparams; public lu_byte is_vararg; public lu_byte maxstacksize; }; /* masks for new-style vararg */ public const int VARARG_HASARG = 1; public const int VARARG_ISVARARG = 2; public const int VARARG_NEEDSARG = 4; public class LocVar { public TString varname; public int startpc; /* first point where variable is active */ public int endpc; /* first point where variable is dead */ }; /* ** Upvalues */ public class UpVal : GCObject { public TValue v; /* points to stack or to its own value */ public class _u { public TValue value = new TValue(); /* the value (when closed) */ public class _l { /* double linked list (when open) */ public UpVal prev; public UpVal next; }; public _l l = new _l(); } public new _u u = new _u(); }; /* ** Closures */ public class ClosureHeader : GCObject { public lu_byte isC; public lu_byte nupvalues; public GCObject gclist; public Table env; }; public class ClosureType { ClosureHeader header; public static implicit operator ClosureHeader(ClosureType ctype) { return ctype.header; } public ClosureType(ClosureHeader header) { this.header = header; } public lu_byte isC { get { return header.isC; } set { header.isC = value; } } public lu_byte nupvalues { get { return header.nupvalues; } set { header.nupvalues = value; } } public GCObject gclist { get { return header.gclist; } set { header.gclist = value; } } public Table env { get { return header.env; } set { header.env = value; } } } public class CClosure : ClosureType { public CClosure(ClosureHeader header) : base(header) { } public lua_CFunction f; public TValue[] upvalue; }; public class LClosure : ClosureType { public LClosure(ClosureHeader header) : base(header) { } public Proto p; public UpVal[] upvals; }; public class Closure : ClosureHeader { public Closure() { c = new CClosure(this); l = new LClosure(this); } public CClosure c; public LClosure l; }; public static bool iscfunction(TValue o) { return ((ttype(o) == LUA_TFUNCTION) && (clvalue(o).c.isC != 0)); } public static bool isLfunction(TValue o) { return ((ttype(o) == LUA_TFUNCTION) && (clvalue(o).c.isC == 0)); } /* ** Tables */ public class TKey_nk : TValue { public TKey_nk() { } public TKey_nk(Value value, int tt, Node next) : base(value, tt) { this.next = next; } public Node next; /* for chaining */ }; public class TKey { public TKey() { this.nk = new TKey_nk(); } public TKey(TKey copy) { this.nk = new TKey_nk(copy.nk.value, copy.nk.tt, copy.nk.next); } public TKey(Value value, int tt, Node next) { this.nk = new TKey_nk(value, tt, next); } public TKey_nk nk = new TKey_nk(); public TValue tvk { get { return this.nk; } } }; public class Node : ArrayElement { private Node[] values = null; private int index = -1; public void set_index(int index) { this.index = index; } public void set_array(object array) { this.values = (Node[])array; Debug.Assert(this.values != null); } public Node() { this.i_val = new TValue(); this.i_key = new TKey(); } public Node(Node copy) { this.values = copy.values; this.index = copy.index; this.i_val = new TValue(copy.i_val); this.i_key = new TKey(copy.i_key); } public Node(TValue i_val, TKey i_key) { this.values = new Node[] { this }; this.index = 0; this.i_val = i_val; this.i_key = i_key; } public TValue i_val; public TKey i_key; public Node this[uint offset] { get { return this.values[this.index + (int)offset]; } } public Node this[int offset] { get { return this.values[this.index + offset]; } } public static int operator -(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index - n2.index; } public static Node inc(ref Node node) { node = node[1]; return node[-1]; } public static Node dec(ref Node node) { node = node[-1]; return node[1]; } public static bool operator >(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index > n2.index; } public static bool operator >=(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index >= n2.index; } public static bool operator <(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index < n2.index; } public static bool operator <=(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index <= n2.index; } public static bool operator ==(Node n1, Node n2) { object o1 = n1 as Node; object o2 = n2 as Node; if ((o1 == null) && (o2 == null)) return true; if (o1 == null) return false; if (o2 == null) return false; if (n1.values != n2.values) return false; return n1.index == n2.index; } public static bool operator !=(Node n1, Node n2) { return !(n1 == n2); } public override bool Equals(object o) { return this == (Node)o; } public override int GetHashCode() { return 0; } }; public class Table : GCObject { public lu_byte flags; /* 1<<p means tagmethod(p) is not present */ public lu_byte lsizenode; /* log2 of size of `node' array */ public Table metatable; public TValue[] array; /* array part */ public Node[] node; public int lastfree; /* any free position is before this position */ public GCObject gclist; public int sizearray; /* size of `array' array */ }; /* ** `module' operation for hashing (size is always a power of 2) */ //#define lmod(s,size) \ // (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1))))) internal static int twoto(int x) { return 1 << x; } internal static int sizenode(Table t) { return twoto(t.lsizenode); } public static TValue luaO_nilobject_ = new TValue(new Value(), LUA_TNIL); public static TValue luaO_nilobject = luaO_nilobject_; public static int ceillog2(int x) { return luaO_log2((uint)(x - 1)) + 1; } /* ** converts an integer to a "floating point byte", represented as ** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if ** eeeee != 0 and (xxx) otherwise. */ public static int luaO_int2fb(uint x) { int e = 0; /* expoent */ while (x >= 16) { x = (x + 1) >> 1; e++; } if (x < 8) return (int)x; else return ((e + 1) << 3) | (cast_int(x) - 8); } /* converts back */ public static int luaO_fb2int(int x) { int e = (x >> 3) & 31; if (e == 0) return x; else return ((x & 7) + 8) << (e - 1); } private readonly static lu_byte[] log_2 = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 }; public static int luaO_log2(uint x) { int l = -1; while (x >= 256) { l += 8; x >>= 8; } return l + log_2[x]; } public static int luaO_rawequalObj(TValue t1, TValue t2) { if (ttype(t1) != ttype(t2)) return 0; else switch (ttype(t1)) { case LUA_TNIL: return 1; case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)) ? 1 : 0; case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2) ? 1 : 0; /* boolean true must be 1....but not in C# !! */ case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2) ? 1 : 0; default: lua_assert(iscollectable(t1)); return gcvalue(t1) == gcvalue(t2) ? 1 : 0; } } public static int luaO_str2d(CharPtr s, out lua_Number result) { CharPtr endptr; result = lua_str2number(s, out endptr); if (endptr == s) return 0; /* conversion failed */ if (endptr[0] == 'x' || endptr[0] == 'X') /* maybe an hexadecimal constant? */ result = cast_num(strtoul(s, out endptr, 16)); if ((endptr[0] == 'o' || endptr[0] == 'O') && (endptr + 1 != '\0')) result = cast_num(strtoul(endptr + 1, out endptr, 8)); if ((endptr[0] == 'b' || endptr[0] == 'B') && (endptr + 1 != '\0')) result = cast_num(strtoul(endptr + 1, out endptr, 2)); if (endptr[0] == '\0') return 1; /* most common case */ while (isspace(endptr[0])) endptr = endptr.next(); if (endptr[0] != '\0') return 0; /* invalid trailing characters? */ return 1; } private static void pushstr(LuaState L, CharPtr str) { setsvalue2s(L, L.top, luaS_new(L, str)); incr_top(L); } /* this function handles only `%d', `%c', %f, %p, and `%s' formats */ public static CharPtr luaO_pushvfstring(LuaState L, CharPtr fmt, params object[] argp) { int parm_index = 0; int n = 1; pushstr(L, ""); for (; ; ) { CharPtr e = strchr(fmt, '%'); if (e == null) break; setsvalue2s(L, L.top, luaS_newlstr(L, fmt, (uint)(e - fmt))); incr_top(L); switch (e[1]) { case 's': { object o = argp[parm_index++]; CharPtr s = o as CharPtr; if (s == null) s = (string)o; if (s == null) s = "(null)"; pushstr(L, s); break; } case 'c': { CharPtr buff = new char[2]; buff[0] = (char)(int)argp[parm_index++]; buff[1] = '\0'; pushstr(L, buff); break; } case 'd': { setnvalue(L.top, (int)argp[parm_index++]); incr_top(L); break; } case 'f': { setnvalue(L.top, (l_uacNumber)argp[parm_index++]); incr_top(L); break; } case 'p': { //CharPtr buff = new char[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ CharPtr buff = new char[32]; sprintf(buff, "0x%08x", argp[parm_index++].GetHashCode()); pushstr(L, buff); break; } case '%': { pushstr(L, "%"); break; } default: { CharPtr buff = new char[3]; buff[0] = '%'; buff[1] = e[1]; buff[2] = '\0'; pushstr(L, buff); break; } } n += 2; fmt = e + 2; } pushstr(L, fmt); luaV_concat(L, n + 1, cast_int(L.top - L.base_) - 1); L.top -= n; return svalue(L.top - 1); } public static CharPtr luaO_pushfstring(LuaState L, CharPtr fmt, params object[] args) { return luaO_pushvfstring(L, fmt, args); } public static void luaO_chunkid(CharPtr out_, CharPtr source, uint bufflen) { //out_ = ""; if (source[0] == '=') { strncpy(out_, source + 1, (int)bufflen); /* remove first char */ out_[bufflen - 1] = '\0'; /* ensures null termination */ } else { /* out = "source", or "...source" */ if (source[0] == '@') { uint l; source = source.next(); /* skip the `@' */ bufflen -= (uint)(" '...' ".Length + 1); l = (uint)strlen(source); strcpy(out_, ""); if (l > bufflen) { source += (l - bufflen); /* get last part of file name */ strcat(out_, "..."); } strcat(out_, source); } else { /* out = [string "string"] */ uint len = strcspn(source, "\n\r"); /* stop at first newline */ bufflen -= (uint)(" [string \"...\"] ".Length + 1); if (len > bufflen) len = bufflen; strcpy(out_, "[string \""); if (source[len] != '\0') { /* must truncate? */ strncat(out_, source, (int)len); strcat(out_, "..."); } else strcat(out_, source); strcat(out_, "\"]"); } } } } }
// // MRMainUI.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; using UnityEngine.UI; using System; using System.Collections; namespace PortableRealm { public class MRMainUI : MonoBehaviour { #region Callback class for dialog buttons public delegate void OnButtonPressed(int buttonId); private class ButtonClickedAction { public ButtonClickedAction(OnButtonPressed callback, int buttonId) { mCallback = callback; mId = buttonId; } public void OnClicked() { MRGame.ShowingUI = false; Destroy (TheUI.mSelectionDialog); TheUI.mSelectionDialog = null; TheUI.mDialogButtons = null; TheUI.mDialogCallbacks = null; mCallback(mId); } private int mId; private OnButtonPressed mCallback; } #endregion #region Constants public enum eCombatActionButton { None, FlipWeapon, RunAway, CastSpell, ActivateItem, AbandonItems } private const float TIMED_MESSAGE_BOX_DISPLAY_TIME = 2.0f; #endregion #region Properties public GameObject SelectionDialogPrototype; public GameObject MessageDialogPrototype; public GameObject YesNoDialogPrototype; public GameObject TimedMessagePrototype; public GameObject InstructionMessagePrototype; public GameObject AttackManeuverDialogPrototype; public GameObject CombatActionDialogPrototype; public GameObject VictoryPointsSelectionDialogPrototype; public GameObject SaveLoadSelectDialogPrototype; public GameObject GameTypeSelectDialogPrototype; public GameObject InstructionsDialogPrototype; public GameObject CreditsDialogPrototype; public static MRMainUI TheUI { get{ return msTheUI; } } #endregion #region Methods void Awake() { msTheUI = this; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { // check if a timed message has timed out if (mTimedMessageBox != null && Time.time - mTimedMessageBoxStartTime >= TIMED_MESSAGE_BOX_DISPLAY_TIME) { Destroy (mTimedMessageBox); mTimedMessageBox = null; } } /// <summary> /// Displays a dialog getting the player choose an item from multiple options. /// </summary> /// <param name="title">Dialog title.</param> /// <param name="buttons">List of options.</param> /// <param name="callback">Class that will be called when a button is pressed.</param> public void DisplaySelectionDialog(string title, string subtitle, string[] buttons, OnButtonPressed callback) { mSelectionDialog = (GameObject)Instantiate(SelectionDialogPrototype); // set the title foreach (Text text in mSelectionDialog.GetComponentsInChildren<Text>()) { if (text.gameObject.name == "Title") { text.text = title; break; } } // set the subtitle foreach (Text text in mSelectionDialog.GetComponentsInChildren<Text>()) { if (text.gameObject.name == "Subtitle") { if (subtitle != null) text.text = subtitle; else text.enabled = false; break; } } // set up the buttons Button buttonProto = mSelectionDialog.GetComponentInChildren<Button>(); mDialogButtons = new Button[buttons.Length]; mDialogCallbacks = new ButtonClickedAction[buttons.Length]; mDialogButtons[0] = buttonProto; mDialogCallbacks[0] = new ButtonClickedAction(callback, 0); buttonProto.onClick.AddListener(mDialogCallbacks[0].OnClicked); buttonProto.GetComponentInChildren<Text>().text = buttons[0]; RectTransform prevButtonTransform = buttonProto.GetComponentInChildren<RectTransform>(); float buttonHeight = prevButtonTransform.sizeDelta.y; for (int i = 1; i < buttons.Length; ++i) { mDialogButtons[i] = (Button)Instantiate(buttonProto); mDialogCallbacks[i] = new ButtonClickedAction(callback, i); mDialogButtons[i].onClick.AddListener(mDialogCallbacks[i].OnClicked); mDialogButtons[i].transform.SetParent(buttonProto.transform.parent, false); mDialogButtons[i].GetComponentInChildren<Text>().text = buttons[i]; RectTransform buttonTransform = mDialogButtons[i].GetComponentInChildren<RectTransform>(); buttonTransform.anchoredPosition = new Vector2(prevButtonTransform.anchoredPosition.x, prevButtonTransform.anchoredPosition.y - buttonHeight); prevButtonTransform = buttonTransform; } // adjust the dialog size for the number of buttons float minHeight = 197; float bottomOffset = 0; foreach (RectTransform background in mSelectionDialog.GetComponentsInChildren<RectTransform>()) { if (background.gameObject.name == "Main Background") { bottomOffset = minHeight - buttons.Length * buttonHeight; if (bottomOffset < 0) bottomOffset = 0; background.offsetMin = new Vector2(0, bottomOffset); break; } } // center the dialog RectTransform dialogTransform = (RectTransform)mSelectionDialog.transform; dialogTransform.Translate(new Vector3(0, -bottomOffset, 0)); mSelectionDialog.transform.SetParent(transform, false); MRGame.ShowingUI = true; } /// <summary> /// Displays a simple message dialog with no title. /// </summary> /// <param name="message">The message.</param> public void DisplayMessageDialog(string message) { DisplayMessageDialog(message, null); } /// <summary> /// Displays a simple message dialog. /// </summary> /// <param name="message">The message.</param> /// <param name="title">Title of the message dialog.</param> public void DisplayMessageDialog(string message, string title) { DisplayMessageDialog(message, title, null); } /// <summary> /// Displays a simple message dialog. /// </summary> /// <param name="message">The message.</param> /// <param name="title">Title of the message dialog.</param> /// <param name="callback">Class that will be called when ok is pressed.</param> public void DisplayMessageDialog(string message, string title, OnButtonPressed callback) { mMessageDialog = (GameObject)Instantiate(MessageDialogPrototype); // set the title and message if (title == null) title = ""; foreach (Text text in mMessageDialog.GetComponentsInChildren<Text>()) { if (text.gameObject.name == "Title") { text.text = title; } else if (text.gameObject.name == "Message") { text.text = message; } } // set the ok button callback Button ok = mMessageDialog.GetComponentInChildren<Button>(); ok.onClick.AddListener(OnOkClicked); mOkCallback = callback; mMessageDialog.transform.SetParent(transform, false); MRGame.ShowingUI = true; } /// <summary> /// Displays a simple message dialog with an ok/cancel response. /// </summary> /// <param name="message">The message.</param> /// <param name="title">Title of the message dialog.</param> /// <param name="okCallback">Class that will be called when "ok" is pressed.</param> /// <param name="cancelCallback">Class that will be called when "cancel" is pressed.</param> public void DisplayOkCancelDialog(string message, string title, OnButtonPressed okCallback, OnButtonPressed cancelCallback) { DisplayYesNoDialog(message, title, "Ok", "Cancel", okCallback, cancelCallback); } /// <summary> /// Displays a simple message dialog with a yes/no response. /// </summary> /// <param name="message">The message.</param> /// <param name="title">Title of the message dialog.</param> /// <param name="yesCallback">Class that will be called when "yes" is pressed.</param> /// <param name="noCallback">Class that will be called when "yes" is pressed.</param> public void DisplayYesNoDialog(string message, string title, OnButtonPressed yesCallback, OnButtonPressed noCallback) { DisplayYesNoDialog(message, title, "Yes", "No", yesCallback, noCallback); } /// <summary> /// Displays a simple message dialog with a yes/no response. /// </summary> /// <param name="message">The message.</param> /// <param name="title">Title of the message dialog.</param> /// <param name="yesText">Text to display on the "yes" button.</param> /// <param name="noText">Text to display on the "no" button.</param> /// <param name="yesCallback">Class that will be called when "yes" is pressed.</param> /// <param name="noCallback">Class that will be called when "yes" is pressed.</param> public void DisplayYesNoDialog(string message, string title, string yesText, string noText, OnButtonPressed yesCallback, OnButtonPressed noCallback) { mYesNoDialog = (GameObject)Instantiate(YesNoDialogPrototype); // set the title and message if (title == null) title = ""; foreach (Text text in mYesNoDialog.GetComponentsInChildren<Text>()) { if (text.gameObject.name == "Title") { text.text = title; } else if (text.gameObject.name == "Message") { text.text = message; } else if (text.gameObject.name == "YesText") { text.text = yesText; } else if (text.gameObject.name == "NoText") { text.text = noText; } } // set the ok button callback foreach (Button button in mYesNoDialog.GetComponentsInChildren<Button>()) { if (button.name == "yesButton") { button.onClick.AddListener(OnYesClicked); mYesCallback = yesCallback; } else if (button.name == "noButton") { button.onClick.AddListener(OnNoClicked); mNoCallback = noCallback; } } mYesNoDialog.transform.SetParent(transform, false); MRGame.ShowingUI = true; } public void DisplayAttackManeuverDialog(float leftPositionViewport, float topPositionViewport) { if (mAttackManeuverDialog == null) { mAttackManeuverDialog = (GameObject)Instantiate(AttackManeuverDialogPrototype); Vector2 anchor = ((RectTransform)mAttackManeuverDialog.transform).anchorMin; anchor.x = leftPositionViewport; anchor.y = topPositionViewport; ((RectTransform)mAttackManeuverDialog.transform).anchorMin = anchor; ((RectTransform)mAttackManeuverDialog.transform).anchorMax = anchor; //Vector3 position = mAttackManeuverDialog.transform.localPosition; // note world x 0 is left screen, but ui 0 is the center //position.x = leftPosition - (Screen.width / 2.0f) + (((RectTransform)mAttackManeuverDialog.transform).rect.width * scale.x / 2.0f); //mAttackManeuverDialog.transform.localPosition = position; mAttackManeuverDialog.transform.SetParent(transform, false); // set button callbacks Button[] buttons = mAttackManeuverDialog.GetComponentsInChildren<Button>(); foreach (Button button in buttons) { if (button.gameObject.name == "None") button.onClick.AddListener(OnAttackManeuverNoneClicked); else if (button.gameObject.name == "Cancel") button.onClick.AddListener(OnAttackManeuverCancelClicked); } } } public void HideAttackManeuverDialog() { if (mAttackManeuverDialog != null) { DestroyObject(mAttackManeuverDialog); mAttackManeuverDialog = null; } } /// <summary> /// Displays the results of a die pool roll at the bottom of the screen. /// </summary> /// <param name="pool">The die pool to display</param> public void DisplayDieRollResult(MRDiePool pool) { if (mTimedMessageBox != null) DestroyObject(mTimedMessageBox); mTimedMessageBox = (GameObject)Instantiate(TimedMessagePrototype); Text text = mTimedMessageBox.GetComponentInChildren<Text>(); string message; if (pool.DieRolls.Length == 1) message = "Roll " + pool.DieRolls[0]; else message = "Roll " + pool.DieRolls[0] + ", " + pool.DieRolls[1]; message += " = " + pool.Roll; text.text = message; mTimedMessageBox.transform.SetParent(transform, false); mTimedMessageBoxStartTime = Time.time; } /// <summary> /// Displays the results of a die pool roll with a message at the bottom of the screen. /// </summary> /// <param name="message">Message to display with the roll</param> /// <param name="pool">The die pool to display</param> public void DisplayDieRollResult(string message, MRDiePool pool) { if (mTimedMessageBox != null) DestroyObject(mTimedMessageBox); mTimedMessageBox = (GameObject)Instantiate(TimedMessagePrototype); Text text = mTimedMessageBox.GetComponentInChildren<Text>(); if (pool.DieRolls.Length == 1) message += " = " + pool.Roll; else message = " = (" + pool.DieRolls[0] + ", " + pool.DieRolls[1] + ") = " + pool.Roll; text.text = message; mTimedMessageBox.transform.SetParent(transform, false); mTimedMessageBoxStartTime = Time.time; } /// <summary> /// Displays an instructional message at the top of the screen. To stop showing the message, /// call this function with null as the message. /// </summary> /// <param name="message">Message to display.</param> public void DisplayInstructionMessage(string message) { if (mInstructionMessage != null) { // check if we're showing the same message Text text = mInstructionMessage.GetComponentInChildren<Text>(); if (message != null && message.Equals(text.text, StringComparison.Ordinal)) return; DestroyObject(mInstructionMessage); } if (message != null) { mInstructionMessage = (GameObject)Instantiate(InstructionMessagePrototype); Text text = mInstructionMessage.GetComponentInChildren<Text>(); text.text = message; mInstructionMessage.transform.SetParent(transform, false); } } /// <summary> /// Displays the combat action selection dialog. /// </summary> /// <param name="canActivateWeapon">Set to <c>true</c> to allow alert/unalert weapon.</param> /// <param name="canRunAway">Set to <c>true</c> to allow running away.</param> /// <param name="canCastSpell">Set to <c>true</c> to allow casting a spell.</param> public void DisplayCombatActionDialog(bool canActivateWeapon, bool canRunAway, bool canCastSpell, OnButtonPressed callback) { if (mCombatActionDialog == null) { mCombatActionDialog = (GameObject)Instantiate(CombatActionDialogPrototype); mCombatActionDialog.transform.SetParent(transform, false); // set button callbacks Button[] buttons = mCombatActionDialog.GetComponentsInChildren<Button>(); foreach (Button button in buttons) { if (button.gameObject.name == "Weapon") { button.interactable = canActivateWeapon; button.onClick.AddListener(OnCombatActionWeaponClicked); } else if (button.gameObject.name == "Run") { button.interactable = canRunAway; button.onClick.AddListener(OnCombatActionRunClicked); } else if (button.gameObject.name == "Spell") { button.interactable = canCastSpell; button.onClick.AddListener(OnCombatActionSpellClicked); } else if (button.gameObject.name == "None") button.onClick.AddListener(OnCombatActionNoneClicked); } mOkCallback = callback; } } /// <summary> /// Displays the victory points selection dialog. /// </summary> /// <param name="character">Character to choose victory points for.</param> public void DisplayVictoryPointsSelectionDialog(MRCharacter character) { if (mVictoryPointsSelectionDialog == null && character != null) { mVictoryPointsSelectionDialog = (GameObject)Instantiate(VictoryPointsSelectionDialogPrototype); mVictoryPointsSelectionDialog.transform.SetParent(transform, false); MonoBehaviour[] scripts = mVictoryPointsSelectionDialog.GetComponents<MonoBehaviour>(); for (int i = 0; i < scripts.Length; ++i) { if (scripts[i] is MRVictoryPointSelectionDialog) { MRVictoryPointSelectionDialog dialogScript = (MRVictoryPointSelectionDialog)scripts[i]; dialogScript.Character = character; dialogScript.Callback = OnVictoryPointsSelected; MRGame.ShowingUI = true; break; } } } } /// <summary> /// Displays the save/new game select dialog. /// </summary> public void DisplaySaveGameSelectDialog() { if (mLoadSaveGameSelectDialog == null) { mLoadSaveGameSelectDialog = (GameObject)Instantiate(SaveLoadSelectDialogPrototype); mLoadSaveGameSelectDialog.transform.SetParent(transform, false); MonoBehaviour[] scripts = mLoadSaveGameSelectDialog.GetComponents<MonoBehaviour>(); for (int i = 0; i < scripts.Length; ++i) { if (scripts[i] is MRLoadSaveGameSelectDialog) { MRLoadSaveGameSelectDialog dialogScript = (MRLoadSaveGameSelectDialog)scripts[i]; dialogScript.DialogMode = MRLoadSaveGameSelectDialog.Mode.Save; dialogScript.Callback = OnSaveSlotSelected; MRGame.ShowingUI = true; break; } } MRGame.ShowingUI = true; } } /// <summary> /// Displays the load game select dialog. /// </summary> public void DisplayLoadGameSelectDialog() { if (mLoadSaveGameSelectDialog == null) { mLoadSaveGameSelectDialog = (GameObject)Instantiate(SaveLoadSelectDialogPrototype); mLoadSaveGameSelectDialog.transform.SetParent(transform, false); MonoBehaviour[] scripts = mLoadSaveGameSelectDialog.GetComponents<MonoBehaviour>(); for (int i = 0; i < scripts.Length; ++i) { if (scripts[i] is MRLoadSaveGameSelectDialog) { MRLoadSaveGameSelectDialog dialogScript = (MRLoadSaveGameSelectDialog)scripts[i]; dialogScript.DialogMode = MRLoadSaveGameSelectDialog.Mode.Load; dialogScript.Callback = OnLoadSlotSelected; MRGame.ShowingUI = true; break; } } } } /// <summary> /// Displaies the game type selection dialog. /// </summary> public void DisplayGameTypeSelectDialog() { if (mGameTypeSelectDialog == null) { mGameTypeSelectDialog = (GameObject)Instantiate(GameTypeSelectDialogPrototype); mGameTypeSelectDialog.transform.SetParent(transform, false); MonoBehaviour[] scripts = mGameTypeSelectDialog.GetComponents<MonoBehaviour>(); for (int i = 0; i < scripts.Length; ++i) { if (scripts[i] is MRGameTypeSelectionDialog) { MRGameTypeSelectionDialog dialogScript = (MRGameTypeSelectionDialog)scripts[i]; dialogScript.Callback = OnGameTypeSelected; MRGame.ShowingUI = true; break; } } } } /// <summary> /// Displays the instructions dialog. /// </summary> public void DisplayInstructionsDialog() { mInstructionsDialog = (GameObject)Instantiate(InstructionsDialogPrototype); mInstructionsDialog.transform.SetParent(transform, false); // set button callbacks Button[] buttons = mInstructionsDialog.GetComponentsInChildren<Button>(); foreach (Button button in buttons) { if (button.gameObject.name == "Back") { button.onClick.AddListener(OnInstructionsBackClicked); } } MRGame.ShowingUI = true; } /// <summary> /// Displays the credits dialog. /// </summary> public void DisplayCreditsDialog() { mCreditsDialog = (GameObject)Instantiate(CreditsDialogPrototype); mCreditsDialog.transform.SetParent(transform, false); // set button callbacks Button[] buttons = mCreditsDialog.GetComponentsInChildren<Button>(); foreach (Button button in buttons) { if (button.gameObject.name == "Back") { button.onClick.AddListener(OnCreditsBackClicked); } } MRGame.ShowingUI = true; } /// <summary> /// Hides the combat action selection dialog. /// </summary> private void HideCombatActionDialog() { if (mCombatActionDialog != null) { DestroyObject(mCombatActionDialog); mCombatActionDialog = null; } } /// <summary> /// Called when the player clicks the "ok" button of the message dialog. /// </summary> private void OnOkClicked() { MRGame.ShowingUI = false; Destroy (mMessageDialog); mMessageDialog = null; if (mOkCallback != null) mOkCallback(0); } /// <summary> /// Called when the player clicks the "yes" button of the yesno dialog. /// </summary> private void OnYesClicked() { MRGame.ShowingUI = false; Destroy (mYesNoDialog); mYesNoDialog = null; if (mYesCallback != null) mYesCallback(0); } /// <summary> /// Called when the player clicks the "no" button of the yesno dialog. /// </summary> private void OnNoClicked() { MRGame.ShowingUI = false; Destroy (mYesNoDialog); mYesNoDialog = null; if (mNoCallback != null) mNoCallback(1); } /// <summary> /// Called when the player clicks the "none" button of the attack/maneuver dialog. /// </summary> private void OnAttackManeuverNoneClicked() { MRGame.TheGame.OnAttackManeuverSelectedGame(MRCombatManager.eAttackManeuverOption.None); } /// <summary> /// Called when the player clicks the "cancel" button of the attack/maneuver dialog. /// </summary> private void OnAttackManeuverCancelClicked() { MRGame.TheGame.OnAttackManeuverSelectedGame(MRCombatManager.eAttackManeuverOption.Cancel); } private void OnCombatActionWeaponClicked() { HideCombatActionDialog(); if (mOkCallback != null) mOkCallback((int)eCombatActionButton.FlipWeapon); } private void OnCombatActionRunClicked() { HideCombatActionDialog(); if (mOkCallback != null) mOkCallback((int)eCombatActionButton.RunAway); } private void OnCombatActionSpellClicked() { HideCombatActionDialog(); if (mOkCallback != null) mOkCallback((int)eCombatActionButton.CastSpell); } private void OnCombatActionNoneClicked() { HideCombatActionDialog(); if (mOkCallback != null) mOkCallback((int)eCombatActionButton.None); } private void OnVictoryPointsSelected(int buttonId) { MRGame.ShowingUI = false; Destroy(mVictoryPointsSelectionDialog); mVictoryPointsSelectionDialog = null; } /// <summary> /// Called when the player selected the game type for a new game. /// </summary> /// <param name="buttonId">Button identifier, 0 = ok.</param> private void OnGameTypeSelected(int buttonId) { MRGame.eGameType type = MRGame.eGameType.Default; int bolChapter = 1; MonoBehaviour[] scripts = mGameTypeSelectDialog.GetComponents<MonoBehaviour>(); for (int i = 0; i < scripts.Length; ++i) { if (scripts[i] is MRGameTypeSelectionDialog) { MRGameTypeSelectionDialog dialogScript = (MRGameTypeSelectionDialog)scripts[i]; type = dialogScript.GameType; bolChapter = dialogScript.BookOfLearningChapter; break; } } MRGame.ShowingUI = false; Destroy(mGameTypeSelectDialog); mGameTypeSelectDialog = null; switch (type) { case MRGame.eGameType.BookOfLearning: { string bolChapterName = "bol_"; if (bolChapter < 10) bolChapterName += "0"; bolChapterName += bolChapter.ToString(); bolChapterName += "_world"; MRGame.TheGame.Main.StartPregeneratedGame(bolChapterName); break; } case MRGame.eGameType.Default: default: MRGame.TheGame.Main.StartNewGame(); break; } } /// <summary> /// Called when the player selected which game to load. /// </summary> /// <param name="buttonId">Button identifier, 0 = ok.</param> private void OnLoadSlotSelected(int buttonId) { int selected = -1; String selectedName = ""; if (buttonId == 0) { // ok selected MonoBehaviour[] scripts = mLoadSaveGameSelectDialog.GetComponents<MonoBehaviour>(); for (int i = 0; i < scripts.Length; ++i) { if (scripts[i] is MRLoadSaveGameSelectDialog) { MRLoadSaveGameSelectDialog dialogScript = (MRLoadSaveGameSelectDialog)scripts[i]; selected = dialogScript.Selected; selectedName = dialogScript.SelectedGameName; break; } } } MRGame.ShowingUI = false; Destroy(mLoadSaveGameSelectDialog); mLoadSaveGameSelectDialog = null; if (selected >= 0 && !String.IsNullOrEmpty(selectedName)) { MRGame.TheGame.Main.CurrentSaveGameSlot = selected; MRGame.TheGame.Main.CurrentSaveGameName = selectedName; StartCoroutine(MRGame.TheGame.Main.LoadGame()); } } /// <summary> /// Called when the player selected which game to save. /// </summary> /// <param name="buttonId">Button identifier, 0 = ok.</param> private void OnSaveSlotSelected(int buttonId) { int selected = -1; String selectedName = ""; if (buttonId == 0) { // ok selected MonoBehaviour[] scripts = mLoadSaveGameSelectDialog.GetComponents<MonoBehaviour>(); for (int i = 0; i < scripts.Length; ++i) { if (scripts[i] is MRLoadSaveGameSelectDialog) { MRLoadSaveGameSelectDialog dialogScript = (MRLoadSaveGameSelectDialog)scripts[i]; selected = dialogScript.Selected; selectedName = dialogScript.SelectedGameName; break; } } } MRGame.ShowingUI = false; Destroy(mLoadSaveGameSelectDialog); mLoadSaveGameSelectDialog = null; if (selected >= 0 && !String.IsNullOrEmpty(selectedName)) { MRGame.TheGame.Main.CurrentSaveGameSlot = selected; MRGame.TheGame.Main.CurrentSaveGameName = selectedName; MRGame.TheGame.Main.SaveGame(); } } private void OnInstructionsBackClicked() { MRGame.ShowingUI = false; Destroy (mInstructionsDialog); mInstructionsDialog = null; } private void OnCreditsBackClicked() { MRGame.ShowingUI = false; Destroy (mCreditsDialog); mCreditsDialog = null; } #endregion #region Members private static MRMainUI msTheUI; private GameObject mSelectionDialog; private GameObject mMessageDialog; private GameObject mYesNoDialog; private GameObject mTimedMessageBox; private GameObject mInstructionMessage; private GameObject mAttackManeuverDialog; private GameObject mCombatActionDialog; private GameObject mVictoryPointsSelectionDialog; private GameObject mLoadSaveGameSelectDialog; private GameObject mGameTypeSelectDialog; private GameObject mInstructionsDialog; private GameObject mCreditsDialog; private Button[] mDialogButtons; private ButtonClickedAction[] mDialogCallbacks; private OnButtonPressed mOkCallback; private OnButtonPressed mYesCallback; private OnButtonPressed mNoCallback; private float mTimedMessageBoxStartTime; #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using NPOI.OpenXml4Net.Exceptions; using NPOI.OpenXml4Net.OPC; using System.Collections.Generic; using NPOI.OpenXmlFormats.Wordprocessing; using System.IO; using System.Xml.Serialization; using System.Xml; /** * @author Philipp Epp * */ public class XWPFNumbering : POIXMLDocumentPart { protected List<XWPFAbstractNum> abstractNums = new List<XWPFAbstractNum>(); protected List<XWPFNum> nums = new List<XWPFNum>(); private CT_Numbering ctNumbering; bool isNew; /** *create a new styles object with an existing document */ public XWPFNumbering(PackagePart part) : base(part) { isNew = true; } [Obsolete("deprecated in POI 3.14, scheduled for removal in POI 3.16")] public XWPFNumbering(PackagePart part, PackageRelationship rel) : this(part) { } /** * create a new XWPFNumbering object for use in a new document */ public XWPFNumbering() { abstractNums = new List<XWPFAbstractNum>(); nums = new List<XWPFNum>(); isNew = true; } /** * read numbering form an existing package */ internal override void OnDocumentRead() { NumberingDocument numberingDoc = null; Stream is1 = GetPackagePart().GetInputStream(); try { XmlDocument doc = ConvertStreamToXml(is1); numberingDoc = NumberingDocument.Parse(doc, NamespaceManager); ctNumbering = numberingDoc.Numbering; //get any Nums foreach (CT_Num ctNum in ctNumbering.GetNumList()) { nums.Add(new XWPFNum(ctNum, this)); } foreach (CT_AbstractNum ctAbstractNum in ctNumbering.GetAbstractNumList()) { abstractNums.Add(new XWPFAbstractNum(ctAbstractNum, this)); } isNew = false; } catch (Exception e) { throw new POIXMLException(e); } finally { if (is1 != null) is1.Close(); } } /** * save and Commit numbering */ protected internal override void Commit() { /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); xmlOptions.SaveSyntheticDocumentElement=(new QName(CTNumbering.type.Name.NamespaceURI, "numbering")); Dictionary<String,String> map = new Dictionary<String,String>(); map.Put("http://schemas.Openxmlformats.org/markup-compatibility/2006", "ve"); map.Put("urn:schemas-microsoft-com:office:office", "o"); map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r"); map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/math", "m"); map.Put("urn:schemas-microsoft-com:vml", "v"); map.Put("http://schemas.Openxmlformats.org/drawingml/2006/wordProcessingDrawing", "wp"); map.Put("urn:schemas-microsoft-com:office:word", "w10"); map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w"); map.Put("http://schemas.microsoft.com/office/word/2006/wordml", "wne"); xmlOptions.SaveSuggestedPrefixes=(map);*/ PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); NumberingDocument doc = new NumberingDocument(ctNumbering); //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] { // new XmlQualifiedName("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006"), // new XmlQualifiedName("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"), // new XmlQualifiedName("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"), // new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml"), // new XmlQualifiedName("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"), // new XmlQualifiedName("w10", "urn:schemas-microsoft-com:office:word"), // new XmlQualifiedName("wne", "http://schemas.microsoft.com/office/word/2006/wordml"), // new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main") // }); doc.Save(out1); out1.Close(); } /** * Sets the ctNumbering * @param numbering */ public void SetNumbering(CT_Numbering numbering) { ctNumbering = numbering; } /** * Checks whether number with numID exists * @param numID * @return bool true if num exist, false if num not exist */ public bool NumExist(string numID) { foreach (XWPFNum num in nums) { if (num.GetCTNum().numId.Equals(numID)) return true; } return false; } /** * add a new number to the numbering document * @param num */ public string AddNum(XWPFNum num){ ctNumbering.AddNewNum(); int pos = (ctNumbering.GetNumList().Count) - 1; ctNumbering.SetNumArray(pos, num.GetCTNum()); nums.Add(num); return num.GetCTNum().numId; } /** * Add a new num with an abstractNumID * @return return NumId of the Added num */ public string AddNum(string abstractNumID) { CT_Num ctNum = this.ctNumbering.AddNewNum(); ctNum.AddNewAbstractNumId(); ctNum.abstractNumId.val = (abstractNumID); ctNum.numId = (nums.Count + 1).ToString(); XWPFNum num = new XWPFNum(ctNum, this); nums.Add(num); return ctNum.numId; } /** * Add a new num with an abstractNumID and a numID * @param abstractNumID * @param numID */ public void AddNum(string abstractNumID, string numID) { CT_Num ctNum = this.ctNumbering.AddNewNum(); ctNum.AddNewAbstractNumId(); ctNum.abstractNumId.val = (abstractNumID); ctNum.numId = (numID); XWPFNum num = new XWPFNum(ctNum, this); nums.Add(num); } /** * Get Num by NumID * @param numID * @return abstractNum with NumId if no Num exists with that NumID * null will be returned */ public XWPFNum GetNum(string numID){ foreach(XWPFNum num in nums){ if(num.GetCTNum().numId.Equals(numID)) return num; } return null; } /** * Get AbstractNum by abstractNumID * @param abstractNumID * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID * null will be returned */ public XWPFAbstractNum GetAbstractNum(string abstractNumID){ foreach(XWPFAbstractNum abstractNum in abstractNums){ if(abstractNum.GetAbstractNum().abstractNumId.Equals(abstractNumID)){ return abstractNum; } } return null; } /** * Compare AbstractNum with abstractNums of this numbering document. * If the content of abstractNum Equals with an abstractNum of the List in numbering * the Bigint Value of it will be returned. * If no equal abstractNum is existing null will be returned * * @param abstractNum * @return Bigint */ public string GetIdOfAbstractNum(XWPFAbstractNum abstractNum) { CT_AbstractNum copy = (CT_AbstractNum)abstractNum.GetCTAbstractNum().Copy(); XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this); int i; for (i = 0; i < abstractNums.Count; i++) { newAbstractNum.GetCTAbstractNum().abstractNumId = i.ToString(); newAbstractNum.SetNumbering(this); if (newAbstractNum.GetCTAbstractNum().ValueEquals(abstractNums[i].GetCTAbstractNum())) { return newAbstractNum.GetCTAbstractNum().abstractNumId; } } return null; } /** * add a new AbstractNum and return its AbstractNumID * @param abstractNum */ public string AddAbstractNum(XWPFAbstractNum abstractNum) { int pos = abstractNums.Count; if (abstractNum.GetAbstractNum() != null) { var ctAbstractNum = abstractNum.GetAbstractNum(); ctAbstractNum.abstractNumId = pos.ToString(); // Use the current CTAbstractNum if it exists ctNumbering.AddNewAbstractNum().Set(ctAbstractNum); } else { ctNumbering.AddNewAbstractNum(); abstractNum.GetAbstractNum().abstractNumId = pos.ToString(); ctNumbering.SetAbstractNumArray(pos, abstractNum.GetAbstractNum()); } abstractNums.Add(abstractNum); return abstractNum.GetAbstractNum().abstractNumId; } /// <summary> /// Add a new AbstractNum /// </summary> /// <returns></returns> /// @author antony liu public string AddAbstractNum() { CT_AbstractNum ctAbstractNum = ctNumbering.AddNewAbstractNum(); XWPFAbstractNum abstractNum = new XWPFAbstractNum(ctAbstractNum, this); abstractNum.AbstractNumId = abstractNums.Count.ToString(); abstractNum.MultiLevelType = MultiLevelType.HybridMultilevel; abstractNum.InitLvl(); abstractNums.Add(abstractNum); return abstractNum.GetAbstractNum().abstractNumId; } /** * remove an existing abstractNum * @param abstractNumID * @return true if abstractNum with abstractNumID exists in NumberingArray, * false if abstractNum with abstractNumID not exists */ public bool RemoveAbstractNum(string abstractNumID) { if (int.Parse(abstractNumID) < abstractNums.Count) { ctNumbering.RemoveAbstractNum(int.Parse(abstractNumID)); abstractNums.RemoveAt(int.Parse(abstractNumID)); return true; } return false; } /** *return the abstractNumID *If the AbstractNumID not exists *return null * @param numID * @return abstractNumID */ public string GetAbstractNumID(string numID) { XWPFNum num = GetNum(numID); if (num == null) return null; if (num.GetCTNum() == null) return null; if (num.GetCTNum().abstractNumId == null) return null; return num.GetCTNum().abstractNumId.val; } } }
// // 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.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation dsc node configurations. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> internal partial class DscNodeConfigurationOperations : IServiceOperations<AutomationManagementClient>, IDscNodeConfigurationOperations { /// <summary> /// Initializes a new instance of the DscNodeConfigurationOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DscNodeConfigurationOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create the node configuration identified by node configuration /// name. (see http://aka.ms/azureautomationsdk/dscnodeconfigurations /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create or update parameters for configuration. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get Dsc node configuration operation. /// </returns> public async Task<DscNodeConfigurationGetResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, DscNodeConfigurationCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Configuration == null) { throw new ArgumentNullException("parameters.Configuration"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Source == null) { throw new ArgumentNullException("parameters.Source"); } if (parameters.Source.ContentHash != null) { if (parameters.Source.ContentHash.Algorithm == null) { throw new ArgumentNullException("parameters.Source.ContentHash.Algorithm"); } if (parameters.Source.ContentHash.Value == null) { throw new ArgumentNullException("parameters.Source.ContentHash.Value"); } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodeConfigurations/"; url = url + Uri.EscapeDataString(parameters.Name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dscNodeConfigurationCreateOrUpdateParametersValue = new JObject(); requestDoc = dscNodeConfigurationCreateOrUpdateParametersValue; JObject sourceValue = new JObject(); dscNodeConfigurationCreateOrUpdateParametersValue["source"] = sourceValue; if (parameters.Source.ContentHash != null) { JObject hashValue = new JObject(); sourceValue["hash"] = hashValue; hashValue["algorithm"] = parameters.Source.ContentHash.Algorithm; hashValue["value"] = parameters.Source.ContentHash.Value; } if (parameters.Source.ContentType != null) { sourceValue["type"] = parameters.Source.ContentType; } if (parameters.Source.Value != null) { sourceValue["value"] = parameters.Source.Value; } if (parameters.Source.Version != null) { sourceValue["version"] = parameters.Source.Version; } dscNodeConfigurationCreateOrUpdateParametersValue["name"] = parameters.Name; JObject configurationValue = new JObject(); dscNodeConfigurationCreateOrUpdateParametersValue["configuration"] = configurationValue; if (parameters.Configuration.Name != null) { configurationValue["name"] = parameters.Configuration.Name; } dscNodeConfigurationCreateOrUpdateParametersValue["incrementNodeConfigurationBuild"] = parameters.IncrementNodeConfigurationBuild; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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 && statusCode != HttpStatusCode.Created) { 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 DscNodeConfigurationGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeConfigurationGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DscNodeConfiguration nodeConfigurationInstance = new DscNodeConfiguration(); result.NodeConfiguration = nodeConfigurationInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); nodeConfigurationInstance.Name = nameInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); nodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); nodeConfigurationInstance.CreationTime = creationTimeInstance; } JToken configurationValue2 = responseDoc["configuration"]; if (configurationValue2 != null && configurationValue2.Type != JTokenType.Null) { DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty(); nodeConfigurationInstance.Configuration = configurationInstance; JToken nameValue2 = configurationValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); configurationInstance.Name = nameInstance2; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); nodeConfigurationInstance.Id = idInstance; } } } 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> /// Delete the Dsc node configurations by node configuration. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='nodeConfigurationName'> /// Required. The Dsc node configuration name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string nodeConfigurationName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (nodeConfigurationName == null) { throw new ArgumentNullException("nodeConfigurationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("nodeConfigurationName", nodeConfigurationName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodeConfigurations/"; url = url + Uri.EscapeDataString(nodeConfigurationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); 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> /// Retrieve the Dsc node configurations by node configuration. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='nodeConfigurationName'> /// Required. The Dsc node configuration name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get Dsc node configuration operation. /// </returns> public async Task<DscNodeConfigurationGetResponse> GetAsync(string resourceGroupName, string automationAccount, string nodeConfigurationName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (nodeConfigurationName == null) { throw new ArgumentNullException("nodeConfigurationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("nodeConfigurationName", nodeConfigurationName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodeConfigurations/"; url = url + Uri.EscapeDataString(nodeConfigurationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-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 DscNodeConfigurationGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeConfigurationGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DscNodeConfiguration nodeConfigurationInstance = new DscNodeConfiguration(); result.NodeConfiguration = nodeConfigurationInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); nodeConfigurationInstance.Name = nameInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); nodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); nodeConfigurationInstance.CreationTime = creationTimeInstance; } JToken configurationValue = responseDoc["configuration"]; if (configurationValue != null && configurationValue.Type != JTokenType.Null) { DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty(); nodeConfigurationInstance.Configuration = configurationInstance; JToken nameValue2 = configurationValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); configurationInstance.Name = nameInstance2; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); nodeConfigurationInstance.Id = idInstance; } } } 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> /// Retrieve a list of dsc node configurations. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public async Task<DscNodeConfigurationListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeConfigurationListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/nodeConfigurations"; List<string> queryParameters = new List<string>(); List<string> odataFilter = new List<string>(); if (parameters != null && parameters.ConfigurationName != null) { odataFilter.Add("configuration/name eq '" + Uri.EscapeDataString(parameters.ConfigurationName) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-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 DscNodeConfigurationListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeConfigurationListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNodeConfiguration dscNodeConfigurationInstance = new DscNodeConfiguration(); result.DscNodeConfigurations.Add(dscNodeConfigurationInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dscNodeConfigurationInstance.Name = nameInstance; } JToken lastModifiedTimeValue = valueValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); dscNodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken creationTimeValue = valueValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); dscNodeConfigurationInstance.CreationTime = creationTimeInstance; } JToken configurationValue = valueValue["configuration"]; if (configurationValue != null && configurationValue.Type != JTokenType.Null) { DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty(); dscNodeConfigurationInstance.Configuration = configurationInstance; JToken nameValue2 = configurationValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); configurationInstance.Name = nameInstance2; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeConfigurationInstance.Id = idInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } 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> /// Retrieve next list of dsc node configrations. (see /// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public async Task<DscNodeConfigurationListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-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 DscNodeConfigurationListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DscNodeConfigurationListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DscNodeConfiguration dscNodeConfigurationInstance = new DscNodeConfiguration(); result.DscNodeConfigurations.Add(dscNodeConfigurationInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dscNodeConfigurationInstance.Name = nameInstance; } JToken lastModifiedTimeValue = valueValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); dscNodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken creationTimeValue = valueValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); dscNodeConfigurationInstance.CreationTime = creationTimeInstance; } JToken configurationValue = valueValue["configuration"]; if (configurationValue != null && configurationValue.Type != JTokenType.Null) { DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty(); dscNodeConfigurationInstance.Configuration = configurationInstance; JToken nameValue2 = configurationValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); configurationInstance.Name = nameInstance2; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dscNodeConfigurationInstance.Id = idInstance; } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } 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(); } } } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEditor; using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using Object = UnityEngine.Object; namespace Fungus.EditorUtils { public class FlowchartWindow : EventWindow { protected class ClipboardObject { internal SerializedObject serializedObject; internal Type type; internal ClipboardObject(Object obj) { serializedObject = new SerializedObject(obj); type = obj.GetType(); } } protected class BlockCopy { private SerializedObject block = null; private List<ClipboardObject> commands = new List<ClipboardObject>(); private ClipboardObject eventHandler = null; internal BlockCopy(Block block) { this.block = new SerializedObject(block); foreach (var command in block.CommandList) { commands.Add(new ClipboardObject(command)); } if (block._EventHandler != null) { eventHandler = new ClipboardObject(block._EventHandler); } } private void CopyProperties(SerializedObject source, Object dest, params SerializedPropertyType[] excludeTypes) { var newSerializedObject = new SerializedObject(dest); var prop = source.GetIterator(); while (prop.NextVisible(true)) { if (!excludeTypes.Contains(prop.propertyType)) { newSerializedObject.CopyFromSerializedProperty(prop); } } newSerializedObject.ApplyModifiedProperties(); } internal Block PasteBlock(Flowchart flowchart) { var newBlock = FlowchartWindow.CreateBlock(flowchart, Vector2.zero); // Copy all command serialized properties // Copy references to match duplication behavior foreach (var command in commands) { var newCommand = Undo.AddComponent(flowchart.gameObject, command.type) as Command; CopyProperties(command.serializedObject, newCommand); newCommand.ItemId = flowchart.NextItemId(); newBlock.CommandList.Add(newCommand); } // Copy event handler if (eventHandler != null) { var newEventHandler = Undo.AddComponent(flowchart.gameObject, eventHandler.type) as EventHandler; CopyProperties(eventHandler.serializedObject, newEventHandler); newEventHandler.ParentBlock = newBlock; newBlock._EventHandler = newEventHandler; } // Copy block properties, but do not copy references because those were just assigned CopyProperties( block, newBlock, SerializedPropertyType.ObjectReference, SerializedPropertyType.Generic, SerializedPropertyType.ArraySize ); newBlock.BlockName = flowchart.GetUniqueBlockKey(block.FindProperty("blockName").stringValue + " (Copy)"); return newBlock; } } protected struct BlockGraphics { internal Color tint; internal Texture2D onTexture; internal Texture2D offTexture; } protected List<BlockCopy> copyList = new List<BlockCopy>(); public static List<Block> deleteList = new List<Block>(); protected Vector2 startDragPosition; public const float minZoomValue = 0.25f; public const float maxZoomValue = 1f; protected GUIStyle nodeStyle = new GUIStyle(); protected static BlockInspector blockInspector; protected int forceRepaintCount; protected Texture2D addTexture; protected Texture2D connectionPointTexture; protected Rect selectionBox; protected Vector2 startSelectionBoxPosition = -Vector2.one; protected List<Block> mouseDownSelectionState = new List<Block>(); protected Color gridLineColor = Color.black; protected readonly Color connectionColor = new Color(0.65f, 0.65f, 0.65f, 1.0f); // Context Click occurs on MouseDown which interferes with panning // Track right click positions manually to show menus on MouseUp protected Vector2 rightClickDown = -Vector2.one; protected const float rightClickTolerance = 5f; protected const string searchFieldName = "search"; private string searchString = string.Empty; protected Rect searchRect; protected Rect popupRect; protected Block[] filteredBlocks; protected int blockPopupSelection = -1; protected Vector2 popupScroll; protected Flowchart flowchart, prevFlowchart; protected Block[] blocks; protected Block dragBlock; protected static FungusState fungusState; [MenuItem("Tools/Fungus/Flowchart Window")] static void Init() { GetWindow(typeof(FlowchartWindow), false, "Flowchart"); } protected virtual void OnEnable() { // All block nodes use the same GUIStyle, but with a different background nodeStyle.border = new RectOffset(20, 20, 5, 5); nodeStyle.padding = nodeStyle.border; nodeStyle.contentOffset = Vector2.zero; nodeStyle.alignment = TextAnchor.MiddleCenter; nodeStyle.wordWrap = true; addTexture = FungusEditorResources.AddSmall; connectionPointTexture = FungusEditorResources.ConnectionPoint; gridLineColor.a = EditorGUIUtility.isProSkin ? 0.5f : 0.25f; copyList.Clear(); wantsMouseMove = true; // For hover selection in block search popup } protected virtual void OnInspectorUpdate() { // Ensure the Block Inspector is always showing the currently selected block var flowchart = GetFlowchart(); if (flowchart == null) { return; } if (Selection.activeGameObject == null && flowchart.SelectedBlock != null ) { if (blockInspector == null) { ShowBlockInspector(flowchart); } blockInspector.block = (Block)flowchart.SelectedBlock; } forceRepaintCount--; forceRepaintCount = Math.Max(0, forceRepaintCount); Repaint(); } protected virtual void OnBecameVisible() { // Ensure that toolbar looks correct in both docked and undocked windows // The docked value doesn't always report correctly without the delayCall EditorApplication.delayCall += () => { var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; var isDockedMethod = typeof(EditorWindow).GetProperty("docked", flags).GetGetMethod(true); if ((bool) isDockedMethod.Invoke(this, null)) { EditorZoomArea.Offset = new Vector2(2.0f, 19.0f); } else { EditorZoomArea.Offset = new Vector2(0.0f, 22.0f); } }; } public static Flowchart GetFlowchart() { // Using a temp hidden object to track the active Flowchart across // serialization / deserialization when playing the game in the editor. if (fungusState == null) { fungusState = GameObject.FindObjectOfType<FungusState>(); if (fungusState == null) { GameObject go = new GameObject("_FungusState"); go.hideFlags = HideFlags.HideInHierarchy; fungusState = go.AddComponent<FungusState>(); } } if (Selection.activeGameObject != null) { var fs = Selection.activeGameObject.GetComponent<Flowchart>(); if (fs != null) { fungusState.SelectedFlowchart = fs; } } return fungusState.SelectedFlowchart; } protected void UpdateFilteredBlocks() { filteredBlocks = blocks.Where(block => block.BlockName.ToLower().Contains(searchString.ToLower())).ToArray(); blockPopupSelection = Mathf.Clamp(blockPopupSelection, 0, filteredBlocks.Length - 1); } protected virtual void HandleEarlyEvents(Event e) { switch (e.type) { case EventType.MouseDown: // Clear search filter focus if (!searchRect.Contains(e.mousePosition) && !popupRect.Contains(e.mousePosition)) { CloseBlockPopup(); } if (e.button == 0 && searchRect.Contains(e.mousePosition)) { blockPopupSelection = 0; popupScroll = Vector2.zero; } rightClickDown = -Vector2.one; break; case EventType.KeyDown: if (GUI.GetNameOfFocusedControl() == searchFieldName) { var centerBlock = false; var selectBlock = false; var closePopup = false; var useEvent = false; switch (e.keyCode) { case KeyCode.DownArrow: ++blockPopupSelection; centerBlock = true; useEvent = true; break; case KeyCode.UpArrow: --blockPopupSelection; centerBlock = true; useEvent = true; break; case KeyCode.Return: centerBlock = true; selectBlock = true; closePopup = true; useEvent = true; break; case KeyCode.Escape: closePopup = true; useEvent = true; break; } blockPopupSelection = Mathf.Clamp(blockPopupSelection, 0, filteredBlocks.Length - 1); if (centerBlock && filteredBlocks.Length > 0) { var block = filteredBlocks[blockPopupSelection]; CenterBlock(block); if (selectBlock) { SelectBlock(block); } } if (closePopup) { CloseBlockPopup(); } if (useEvent) { e.Use(); } } else if (e.keyCode == KeyCode.Escape && flowchart.SelectedBlocks.Count > 0) { DeselectAll(); e.Use(); } break; } } protected virtual void OnGUI() { // TODO: avoid calling some of these methods in OnGUI because it should be possible // to only call them when the window is initialized or a new flowchart is selected, etc. flowchart = GetFlowchart(); if (flowchart == null) { GUILayout.Label("No Flowchart scene object selected"); return; } //target has changed, so clear the blockinspector if (flowchart != prevFlowchart) { blockInspector = null; prevFlowchart = flowchart; return; } DeleteBlocks(); blocks = flowchart.GetComponents<Block>(); UpdateFilteredBlocks(); BringSelectedBlockToFront(); HandleEarlyEvents(Event.current); // Draw background color / drop shadow if (Event.current.type == EventType.Repaint) { UnityEditor.Graphs.Styles.graphBackground.Draw( new Rect(0, 17, position.width, position.height - 17), false, false, false, false ); } // Draw blocks and connections DrawFlowchartView(Event.current); // Draw selection box if (Event.current.type == EventType.Repaint) { if (startSelectionBoxPosition.x >= 0 && startSelectionBoxPosition.y >= 0) { GUI.Box(selectionBox, "", GUI.skin.FindStyle("SelectionRect")); } } // Draw toolbar, search popup, and variables window // need try catch here as we are now invalidating the drawer if the target flowchart // has changed which makes unity GUILayouts upset and this function appears to // actually get called partially outside our control try { DrawOverlay(Event.current); } catch (Exception) { //Debug.Log("Failed to draw overlay in some way"); } // Handle events for custom GUI base.HandleEvents(Event.current); if (forceRepaintCount > 0) { // Redraw on next frame to get crisp refresh rate Repaint(); } } protected virtual void DrawOverlay(Event e) { // Main toolbar group GUILayout.BeginHorizontal(EditorStyles.toolbar); { GUILayout.Space(2); // Draw add block button if (GUILayout.Button(new GUIContent(addTexture, "Add a new block"), EditorStyles.toolbarButton)) { DeselectAll(); Vector2 newNodePosition = new Vector2( 50 / flowchart.Zoom - flowchart.ScrollPos.x, 50 / flowchart.Zoom - flowchart.ScrollPos.y ); CreateBlock(flowchart, newNodePosition); } GUILayout.Label("", EditorStyles.toolbarButton, GUILayout.Width(8)); // Separator // Draw scale bar and labels GUILayout.Label("Scale", EditorStyles.miniLabel); var newZoom = GUILayout.HorizontalSlider( flowchart.Zoom, minZoomValue, maxZoomValue, GUILayout.MinWidth(40), GUILayout.MaxWidth(100) ); GUILayout.Label(flowchart.Zoom.ToString("0.0#x"), EditorStyles.miniLabel, GUILayout.Width(30)); if (newZoom != flowchart.Zoom) { DoZoom(newZoom - flowchart.Zoom, Vector2.one * 0.5f); } // Draw center button if (GUILayout.Button("Center", EditorStyles.toolbarButton)) { CenterFlowchart(); } GUILayout.FlexibleSpace(); // Draw search bar GUI.SetNextControlName(searchFieldName); var newString = EditorGUILayout.TextField(searchString, GUI.skin.FindStyle("ToolbarSeachTextField"), GUILayout.Width(150)); if (newString != searchString) { searchString = newString; } if (e.type == EventType.Repaint) { searchRect = GUILayoutUtility.GetLastRect(); popupRect = searchRect; popupRect.width += 12; popupRect.y += popupRect.height; popupRect.height = Mathf.Min(filteredBlocks.Length * 16, position.height - 22); } if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSeachCancelButton"))) { CloseBlockPopup(); } // Eat all click events on toolbar if (e.type == EventType.MouseDown) { if (e.mousePosition.y < searchRect.height) { e.Use(); } } } GUILayout.EndHorizontal(); // Name and description group GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); { GUILayout.Label(flowchart.name, EditorStyles.whiteBoldLabel); GUILayout.Space(2); if (flowchart.Description.Length > 0) { GUILayout.Label(flowchart.Description, EditorStyles.helpBox); } } GUILayout.EndVertical(); } GUILayout.EndHorizontal(); // Variables group GUILayout.BeginHorizontal(); { GUILayout.BeginVertical(GUILayout.Width(440)); { GUILayout.FlexibleSpace(); flowchart.VariablesScrollPos = GUILayout.BeginScrollView(flowchart.VariablesScrollPos); { GUILayout.Space(8); FlowchartEditor flowchartEditor = Editor.CreateEditor (flowchart) as FlowchartEditor; flowchartEditor.DrawVariablesGUI(); DestroyImmediate(flowchartEditor); Rect variableWindowRect = GUILayoutUtility.GetLastRect(); if (flowchart.VariablesExpanded && flowchart.Variables.Count > 0) { variableWindowRect.y -= 20; variableWindowRect.height += 20; } // Eat mouse events if (e.type == EventType.MouseDown) { if (e.mousePosition.x <= variableWindowRect.width && e.mousePosition.y <= variableWindowRect.height) { e.Use(); } } } GUILayout.EndScrollView(); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); // Draw block search popup on top of other controls if (GUI.GetNameOfFocusedControl() == searchFieldName && filteredBlocks.Length > 0) { DrawBlockPopup(e); } } protected virtual void DrawBlockPopup(Event e) { blockPopupSelection = Mathf.Clamp(blockPopupSelection, 0, filteredBlocks.Length - 1); GUI.Box(popupRect, "", GUI.skin.FindStyle("sv_iconselector_back")); if (e.type == EventType.MouseMove) { if (popupRect.Contains(e.mousePosition)) { var relativeY = e.mousePosition.y - popupRect.yMin + popupScroll.y; blockPopupSelection = (int) (relativeY / 16); } e.Use(); } GUILayout.BeginArea(popupRect); { popupScroll = EditorGUILayout.BeginScrollView(popupScroll, GUIStyle.none, GUI.skin.verticalScrollbar); { var normalStyle = new GUIStyle(GUI.skin.FindStyle("MenuItem")); normalStyle.padding = new RectOffset(8, 0, 0, 0); normalStyle.imagePosition = ImagePosition.ImageLeft; var selectedStyle = new GUIStyle(normalStyle); selectedStyle.normal = selectedStyle.hover; normalStyle.hover = normalStyle.normal; for (int i = 0; i < filteredBlocks.Length; ++i) { EditorGUILayout.BeginHorizontal(GUILayout.Height(16)); var block = filteredBlocks[i]; var style = i == blockPopupSelection ? selectedStyle : normalStyle; GUI.contentColor = GetBlockGraphics(block).tint; var buttonPressed = false; if (GUILayout.Button(FungusEditorResources.BulletPoint, style, GUILayout.Width(16))) { buttonPressed = true; } GUI.contentColor = Color.white; if (GUILayout.Button(block.BlockName, style)) { buttonPressed = true; } if (buttonPressed) { CenterBlock(block); SelectBlock(block); CloseBlockPopup(); } EditorGUILayout.EndHorizontal(); } } EditorGUILayout.EndScrollView(); } GUILayout.EndArea(); } protected Block GetBlockAtPoint(Vector2 point) { for (int i = blocks.Length - 1; i > -1; --i) { var block = blocks[i]; var rect = block._NodeRect; rect.position += flowchart.ScrollPos; if (rect.Contains(point / flowchart.Zoom)) { return block; } } return null; } protected void BringSelectedBlockToFront() { var block = flowchart.SelectedBlock; if (block != null) { var index = Array.IndexOf(blocks, block); for (int i = index; i < blocks.Length - 1; ++i) { blocks[i] = blocks[i + 1]; } blocks[blocks.Length - 1] = block; } } protected override void OnMouseDown(Event e) { var hitBlock = GetBlockAtPoint(e.mousePosition); // Convert Ctrl+Left click to a right click on mac if (Application.platform == RuntimePlatform.OSXEditor) { if (e.button == MouseButton.Left && e.control) { e.button = MouseButton.Right; } } switch(e.button) { case MouseButton.Left: if (!e.alt) { if (hitBlock != null) { startDragPosition = e.mousePosition / flowchart.Zoom - flowchart.ScrollPos; Undo.RecordObject(flowchart, "Select"); if (GetAppendModifierDown()) { if (flowchart.SelectedBlocks.Contains(hitBlock)) { flowchart.SelectedBlocks.Remove(hitBlock); } else { flowchart.AddSelectedBlock(hitBlock); } } else { if (flowchart.SelectedBlocks.Contains(hitBlock)) { SetBlockForInspector(flowchart, hitBlock); } else { SelectBlock(hitBlock); } dragBlock = hitBlock; } e.Use(); GUIUtility.keyboardControl = 0; // Fix for textarea not refeshing (change focus) } else if (!(UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Zoom)) { if (!GetAppendModifierDown()) { DeselectAll(); } startSelectionBoxPosition = e.mousePosition; mouseDownSelectionState = new List<Block>(flowchart.SelectedBlocks); e.Use(); } } break; case MouseButton.Right: rightClickDown = e.mousePosition; e.Use(); break; } } protected override void OnMouseDrag(Event e) { var drag = false; switch (e.button) { case MouseButton.Left: // Block dragging if (dragBlock != null) { for (int i = 0; i < flowchart.SelectedBlocks.Count; ++i) { var block = flowchart.SelectedBlocks[i]; var tempRect = block._NodeRect; tempRect.position += e.delta / flowchart.Zoom; block._NodeRect = tempRect; } e.Use(); } // Pan tool or alt + left click else if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Pan || e.alt) { drag = true; } else if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Zoom) { DoZoom(-e.delta.y * 0.01f, Vector2.one * 0.5f); e.Use(); } // Selection box else if (startSelectionBoxPosition.x >= 0 && startSelectionBoxPosition.y >= 0) { var topLeft = Vector2.Min(startSelectionBoxPosition, e.mousePosition); var bottomRight = Vector2.Max(startSelectionBoxPosition, e.mousePosition); selectionBox = Rect.MinMaxRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y); Rect zoomSelectionBox = selectionBox; zoomSelectionBox.position -= flowchart.ScrollPos * flowchart.Zoom; zoomSelectionBox.position /= flowchart.Zoom; zoomSelectionBox.size /= flowchart.Zoom; for (int i = 0; i < blocks.Length; ++i) { var block = blocks[i]; if (zoomSelectionBox.Overlaps(block._NodeRect)) { if (mouseDownSelectionState.Contains(block)) { flowchart.SelectedBlocks.Remove(block); } else { flowchart.AddSelectedBlock(block); } } else if (mouseDownSelectionState.Contains(block)) { flowchart.AddSelectedBlock(block); } else { flowchart.SelectedBlocks.Remove(block); } } e.Use(); } break; case MouseButton.Right: if (Vector2.Distance(rightClickDown, e.mousePosition) > rightClickTolerance) { rightClickDown = -Vector2.one; } drag = true; break; case MouseButton.Middle: drag = true; break; } if (drag) { flowchart.ScrollPos += e.delta / flowchart.Zoom; e.Use(); } } protected override void OnRawMouseUp(Event e) { var hitBlock = GetBlockAtPoint(e.mousePosition); // Convert Ctrl+Left click to a right click on mac if (Application.platform == RuntimePlatform.OSXEditor) { if (e.button == MouseButton.Left && e.control) { e.button = MouseButton.Right; } } switch (e.button) { case MouseButton.Left: if (dragBlock != null) { for (int i = 0; i < flowchart.SelectedBlocks.Count; ++i) { var block = flowchart.SelectedBlocks[i]; var tempRect = block._NodeRect; var distance = e.mousePosition / flowchart.Zoom - flowchart.ScrollPos - startDragPosition; tempRect.position -= distance; block._NodeRect = tempRect; Undo.RecordObject(block, "Block Position"); tempRect.position += distance; block._NodeRect = tempRect; } dragBlock = null; } // Check to see if selection actually changed? if (selectionBox.size.x > 0 && selectionBox.size.y > 0) { var tempList = new List<Block>(flowchart.SelectedBlocks); flowchart.SelectedBlocks = mouseDownSelectionState; Undo.RecordObject(flowchart, "Select"); flowchart.SelectedBlocks = tempList; if (flowchart.SelectedBlock != null) { SetBlockForInspector(flowchart, flowchart.SelectedBlock); } } break; case MouseButton.Right: if (rightClickDown != -Vector2.one) { var menu = new GenericMenu(); var mousePosition = rightClickDown; // Clicked on a block if (hitBlock != null) { flowchart.AddSelectedBlock(hitBlock); // Use a copy because flowchart.SelectedBlocks gets modified var blockList = new List<Block>(flowchart.SelectedBlocks); menu.AddItem(new GUIContent ("Copy"), false, () => Copy()); menu.AddItem(new GUIContent ("Cut"), false, () => Cut()); menu.AddItem(new GUIContent ("Duplicate"), false, () => Duplicate()); menu.AddItem(new GUIContent ("Delete"), false, () => AddToDeleteList(blockList)); } else { DeselectAll(); menu.AddItem(new GUIContent("Add Block"), false, () => CreateBlock(flowchart, mousePosition / flowchart.Zoom - flowchart.ScrollPos)); if (copyList.Count > 0) { menu.AddItem(new GUIContent("Paste"), false, () => Paste(mousePosition)); } else { menu.AddDisabledItem(new GUIContent("Paste")); } } var menuRect = new Rect(); menuRect.position = new Vector2(mousePosition.x, mousePosition.y - 12f); menu.DropDown(menuRect); e.Use(); } break; } // Selection box selectionBox.size = Vector2.zero; selectionBox.position = -Vector2.one; startSelectionBoxPosition = selectionBox.position; } protected override void OnScrollWheel(Event e) { if (selectionBox.size == Vector2.zero) { Vector2 zoomCenter; zoomCenter.x = e.mousePosition.x / flowchart.Zoom / position.width; zoomCenter.y = e.mousePosition.y / flowchart.Zoom / position.height; zoomCenter *= flowchart.Zoom; DoZoom(-e.delta.y * 0.01f, zoomCenter); e.Use(); } } protected virtual void DrawFlowchartView(Event e) { // Calc rect for script view Rect scriptViewRect = new Rect(0, 0, this.position.width / flowchart.Zoom, this.position.height / flowchart.Zoom); EditorZoomArea.Begin(flowchart.Zoom, scriptViewRect); if (e.type == EventType.Repaint) { DrawGrid(); // Draw connections foreach (var block in blocks) { DrawConnections(block, false); } foreach (var block in blocks) { DrawConnections(block, true); } } for (int i = 0; i < blocks.Length; ++i) { var block = blocks[i]; float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.BlockName)).x + 10; float nodeWidthB = 0f; if (block._EventHandler != null) { nodeWidthB = nodeStyle.CalcSize(new GUIContent(block._EventHandler.GetSummary())).x + 10; } Rect tempRect = block._NodeRect; tempRect.width = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120); tempRect.height = 40; block._NodeRect = tempRect; Rect windowRect = new Rect(block._NodeRect); windowRect.position += flowchart.ScrollPos; // Draw blocks bool selected = flowchart.SelectedBlocks.Contains(block); GUIStyle nodeStyleCopy = new GUIStyle(nodeStyle); var graphics = GetBlockGraphics(block); // Make sure node is wide enough to fit the node name text float width = nodeStyleCopy.CalcSize(new GUIContent(block.BlockName)).x; tempRect = block._NodeRect; tempRect.width = Mathf.Max(block._NodeRect.width, width); block._NodeRect = tempRect; // Draw untinted highlight if (selected) { GUI.backgroundColor = Color.white; nodeStyleCopy.normal.background = graphics.onTexture; GUI.Box(windowRect, "", nodeStyleCopy); } // Draw tinted block; ensure text is readable var brightness = graphics.tint.r * 0.3 + graphics.tint.g * 0.59 + graphics.tint.b * 0.11; nodeStyleCopy.normal.textColor = brightness >= 0.5 ? Color.black : Color.white; if (GUI.GetNameOfFocusedControl() == searchFieldName && !filteredBlocks.Contains(block)) { graphics.tint.a *= 0.2f; } nodeStyleCopy.normal.background = graphics.offTexture; GUI.backgroundColor = graphics.tint; GUI.Box(windowRect, block.BlockName, nodeStyleCopy); GUI.backgroundColor = Color.white; if (block.Description.Length > 0) { GUIStyle descriptionStyle = new GUIStyle(EditorStyles.helpBox); descriptionStyle.wordWrap = true; var content = new GUIContent(block.Description); windowRect.y += windowRect.height; windowRect.height = descriptionStyle.CalcHeight(content, windowRect.width); GUI.Label(windowRect, content, descriptionStyle); } GUI.backgroundColor = Color.white; // Draw Event Handler labels if (block._EventHandler != null) { string handlerLabel = ""; EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block._EventHandler.GetType()); if (info != null) { handlerLabel = "<" + info.EventHandlerName + "> "; } GUIStyle handlerStyle = new GUIStyle(EditorStyles.whiteLabel); handlerStyle.wordWrap = true; handlerStyle.margin.top = 0; handlerStyle.margin.bottom = 0; handlerStyle.alignment = TextAnchor.MiddleCenter; Rect rect = new Rect(block._NodeRect); rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block._NodeRect.width); rect.x += flowchart.ScrollPos.x; rect.y += flowchart.ScrollPos.y - rect.height; GUI.Label(rect, handlerLabel, handlerStyle); } } // Draw play icons beside all executing blocks if (Application.isPlaying) { for (int i = 0; i < blocks.Length; ++i) { var b = blocks[i]; if (b.IsExecuting()) { b.ExecutingIconTimer = Time.realtimeSinceStartup + FungusConstants.ExecutingIconFadeTime; b.ActiveCommand.ExecutingIconTimer = Time.realtimeSinceStartup + FungusConstants.ExecutingIconFadeTime; forceRepaintCount = 1; } if (b.ExecutingIconTimer > Time.realtimeSinceStartup) { Rect rect = new Rect(b._NodeRect); rect.x += flowchart.ScrollPos.x - 37; rect.y += flowchart.ScrollPos.y + 3; rect.width = 34; rect.height = 34; if (!b.IsExecuting()) { float alpha = (b.ExecutingIconTimer - Time.realtimeSinceStartup) / FungusConstants.ExecutingIconFadeTime; alpha = Mathf.Clamp01(alpha); GUI.color = new Color(1f, 1f, 1f, alpha); } if (GUI.Button(rect, FungusEditorResources.PlayBig, new GUIStyle())) { SelectBlock(b); } GUI.color = Color.white; } } } EditorZoomArea.End(); } public virtual Vector2 GetBlockCenter(Block[] blocks) { if (blocks.Length == 0) { return Vector2.zero; } Vector2 min = blocks[0]._NodeRect.min; Vector2 max = blocks[0]._NodeRect.max; for (int i = 0; i < blocks.Length; ++i) { var block = blocks[i]; min.x = Mathf.Min(min.x, block._NodeRect.center.x); min.y = Mathf.Min(min.y, block._NodeRect.center.y); max.x = Mathf.Max(max.x, block._NodeRect.center.x); max.y = Mathf.Max(max.y, block._NodeRect.center.y); } return (min + max) * 0.5f; } protected virtual void CenterFlowchart() { if (blocks.Length > 0) { var center = -GetBlockCenter(blocks); center.x += position.width * 0.5f / flowchart.Zoom; center.y += position.height * 0.5f / flowchart.Zoom; flowchart.CenterPosition = center; flowchart.ScrollPos = flowchart.CenterPosition; } } protected virtual void DoZoom(float delta, Vector2 center) { var prevZoom = flowchart.Zoom; flowchart.Zoom += delta; flowchart.Zoom = Mathf.Clamp(flowchart.Zoom, minZoomValue, maxZoomValue); var deltaSize = position.size / prevZoom - position.size / flowchart.Zoom; var offset = -Vector2.Scale(deltaSize, center); flowchart.ScrollPos += offset; forceRepaintCount = 1; } protected virtual void DrawGrid() { float width = this.position.width / flowchart.Zoom; float height = this.position.height / flowchart.Zoom; Handles.color = gridLineColor; float gridSize = 128f; float x = flowchart.ScrollPos.x % gridSize; while (x < width) { Handles.DrawLine(new Vector2(x, 0), new Vector2(x, height)); x += gridSize; } float y = (flowchart.ScrollPos.y % gridSize); while (y < height) { if (y >= 0) { Handles.DrawLine(new Vector2(0, y), new Vector2(width, y)); } y += gridSize; } Handles.color = Color.white; } protected virtual void SelectBlock(Block block) { // Select the block and also select currently executing command flowchart.SelectedBlock = block; SetBlockForInspector(flowchart, block); } protected virtual void DeselectAll() { Undo.RecordObject(flowchart, "Deselect"); flowchart.ClearSelectedCommands(); flowchart.ClearSelectedBlocks(); Selection.activeGameObject = flowchart.gameObject; } public static Block CreateBlock(Flowchart flowchart, Vector2 position) { Block newBlock = flowchart.CreateBlock(position); Undo.RegisterCreatedObjectUndo(newBlock, "New Block"); // Use AddSelected instead of Select for when multiple blocks are duplicated flowchart.AddSelectedBlock(newBlock); SetBlockForInspector(flowchart, newBlock); return newBlock; } protected virtual void DrawConnections(Block block, bool highlightedOnly) { if (block == null) { return; } var connectedBlocks = new List<Block>(); bool blockIsSelected = flowchart.SelectedBlock == block; var commandList = block.CommandList; foreach (var command in commandList) { if (command == null) { continue; } bool commandIsSelected = false; var selectedCommands = flowchart.SelectedCommands; foreach (var selectedCommand in selectedCommands) { if (selectedCommand == command) { commandIsSelected = true; break; } } bool highlight = command.IsExecuting || (blockIsSelected && commandIsSelected); if (highlightedOnly && !highlight || !highlightedOnly && highlight) { continue; } connectedBlocks.Clear(); command.GetConnectedBlocks(ref connectedBlocks); foreach (var blockB in connectedBlocks) { if (blockB == null || block == blockB || !blockB.GetFlowchart().Equals(flowchart)) { continue; } Rect startRect = new Rect(block._NodeRect); startRect.x += flowchart.ScrollPos.x; startRect.y += flowchart.ScrollPos.y; Rect endRect = new Rect(blockB._NodeRect); endRect.x += flowchart.ScrollPos.x; endRect.y += flowchart.ScrollPos.y; DrawRectConnection(startRect, endRect, highlight); } } } protected virtual void DrawRectConnection(Rect rectA, Rect rectB, bool highlight) { Vector2[] pointsA = new Vector2[] { new Vector2(rectA.xMin, rectA.center.y), new Vector2(rectA.xMin + rectA.width / 2, rectA.yMin), new Vector2(rectA.xMin + rectA.width / 2, rectA.yMax), new Vector2(rectA.xMax, rectA.center.y) }; Vector2[] pointsB = new Vector2[] { new Vector2(rectB.xMin, rectB.center.y), new Vector2(rectB.xMin + rectB.width / 2, rectB.yMin), new Vector2(rectB.xMin + rectB.width / 2, rectB.yMax), new Vector2(rectB.xMax, rectB.center.y) }; Vector2 pointA = Vector2.zero; Vector2 pointB = Vector2.zero; float minDist = float.MaxValue; foreach (var a in pointsA) { foreach (var b in pointsB) { float d = Vector2.Distance(a, b); if (d < minDist) { pointA = a; pointB = b; minDist = d; } } } Color color = connectionColor; if (highlight) { color = Color.green; } Handles.color = color; // Place control based on distance between points // Weight the min component more so things don't get overly curvy var diff = pointA - pointB; diff.x = Mathf.Abs(diff.x); diff.y = Mathf.Abs(diff.y); var min = Mathf.Min(diff.x, diff.y); var max = Mathf.Max(diff.x, diff.y); var mod = min * 0.75f + max * 0.25f; // Draw bezier curve connecting blocks var directionA = (rectA.center - pointA).normalized; var directionB = (rectB.center - pointB).normalized; var controlA = pointA - directionA * mod * 0.67f; var controlB = pointB - directionB * mod * 0.67f; Handles.DrawBezier(pointA, pointB, controlA, controlB, color, null, 3f); // Draw arrow on curve var point = GetPointOnCurve(pointA, controlA, pointB, controlB, 0.7f); var direction = (GetPointOnCurve(pointA, controlA, pointB, controlB, 0.6f) - point).normalized; var perp = new Vector2(direction.y, -direction.x); Handles.DrawAAConvexPolygon( point, point + direction * 10 + perp * 5, point + direction * 10 - perp * 5 ); var connectionPointA = pointA + directionA * 4f; var connectionRectA = new Rect(connectionPointA.x - 4f, connectionPointA.y - 4f, 8f, 8f); var connectionPointB = pointB + directionB * 4f; var connectionRectB = new Rect(connectionPointB.x - 4f, connectionPointB.y - 4f, 8f, 8f); GUI.DrawTexture(connectionRectA, connectionPointTexture, ScaleMode.ScaleToFit); GUI.DrawTexture(connectionRectB, connectionPointTexture, ScaleMode.ScaleToFit); Handles.color = Color.white; } private static Vector2 GetPointOnCurve(Vector2 s, Vector2 st, Vector2 e, Vector2 et, float t) { float rt = 1 - t; float rtt = rt * t; return rt * rt * rt * s + 3 * rt * rtt * st + 3 * rtt * t * et + t * t * t * e; } protected void AddToDeleteList(List<Block> blocks) { for (int i = 0; i < blocks.Count; ++i) { FlowchartWindow.deleteList.Add(blocks[i]); } } public void DeleteBlocks() { // Delete any scheduled objects for (int i = 0; i < deleteList.Count; ++i) { var deleteBlock = deleteList[i]; bool isSelected = (flowchart.SelectedBlocks.Contains(deleteBlock)); var commandList = deleteBlock.CommandList; for (int j = 0; j < commandList.Count; ++j) { Undo.DestroyObjectImmediate(commandList[j]); } if (deleteBlock._EventHandler != null) { Undo.DestroyObjectImmediate(deleteBlock._EventHandler); } Undo.DestroyObjectImmediate(deleteBlock); flowchart.ClearSelectedCommands(); if (isSelected) { // Deselect flowchart.SelectedBlocks.Remove(deleteBlock); // Revert to showing properties for the Flowchart Selection.activeGameObject = flowchart.gameObject; } } deleteList.Clear(); } protected static void ShowBlockInspector(Flowchart flowchart) { if (blockInspector == null) { // Create a Scriptable Object with a custom editor which we can use to inspect the selected block. // Editors for Scriptable Objects display using the full height of the inspector window. blockInspector = ScriptableObject.CreateInstance<BlockInspector>() as BlockInspector; blockInspector.hideFlags = HideFlags.DontSave; } Selection.activeObject = blockInspector; EditorUtility.SetDirty(blockInspector); } protected static void SetBlockForInspector(Flowchart flowchart, Block block) { ShowBlockInspector(flowchart); flowchart.ClearSelectedCommands(); if (block.ActiveCommand != null) { flowchart.AddSelectedCommand(block.ActiveCommand); } } /// <summary> /// Displays a temporary text alert in the center of the Flowchart window. /// </summary> public static void ShowNotification(string notificationText) { EditorWindow window = EditorWindow.GetWindow(typeof(FlowchartWindow), false, "Flowchart"); if (window != null) { window.ShowNotification(new GUIContent(notificationText)); } } protected virtual bool GetAppendModifierDown() { return Event.current.shift || EditorGUI.actionKey; } protected virtual void Copy() { copyList.Clear(); foreach (var block in flowchart.SelectedBlocks) { copyList.Add(new BlockCopy(block)); } } protected virtual void Cut() { Copy(); Undo.RecordObject(flowchart, "Cut"); AddToDeleteList(flowchart.SelectedBlocks); } // Center is position in unscaled window space protected virtual void Paste(Vector2 center, bool relative = false) { Undo.RecordObject(flowchart, "Deselect"); DeselectAll(); var pasteList = new List<Block>(); foreach (var copy in copyList) { pasteList.Add(copy.PasteBlock(flowchart)); } var copiedCenter = GetBlockCenter(pasteList.ToArray()) + flowchart.ScrollPos; var delta = relative ? center : (center / flowchart.Zoom - copiedCenter); foreach (var block in pasteList) { var tempRect = block._NodeRect; tempRect.position += delta; block._NodeRect = tempRect; } } protected virtual void Duplicate() { var tempCopyList = new List<BlockCopy>(copyList); Copy(); Paste(new Vector2(20, 0), true); copyList = tempCopyList; } protected override void OnValidateCommand(Event e) { if (e.type == EventType.ValidateCommand) { var c = e.commandName; if (c == "Copy" || c == "Cut" || c == "Delete" || c == "Duplicate") { if (flowchart.SelectedBlocks.Count > 0) { e.Use(); } } else if (c == "Paste") { if (copyList.Count > 0) { e.Use(); } } else if (c == "SelectAll" || c == "Find") { e.Use(); } } } protected override void OnExecuteCommand(Event e) { switch (e.commandName) { case "Copy": Copy(); e.Use(); break; case "Cut": Cut(); e.Use(); break; case "Paste": Paste(position.center - position.position); e.Use(); break; case "Delete": AddToDeleteList(flowchart.SelectedBlocks); e.Use(); break; case "Duplicate": Duplicate(); e.Use(); break; case "SelectAll": Undo.RecordObject(flowchart, "Selection"); flowchart.ClearSelectedBlocks(); for (int i = 0; i < blocks.Length; ++i) { flowchart.AddSelectedBlock(blocks[i]); } e.Use(); break; case "Find": blockPopupSelection = 0; popupScroll = Vector2.zero; EditorGUI.FocusTextInControl(searchFieldName); e.Use(); break; } } protected virtual void CenterBlock(Block block) { if (flowchart.Zoom < 1) { DoZoom(1 - flowchart.Zoom, Vector2.one * 0.5f); } flowchart.ScrollPos = -block._NodeRect.center + position.size * 0.5f / flowchart.Zoom; } protected virtual void CloseBlockPopup() { GUIUtility.keyboardControl = 0; searchString = string.Empty; } protected virtual BlockGraphics GetBlockGraphics(Block block) { var graphics = new BlockGraphics(); Color defaultTint; if (block._EventHandler != null) { graphics.offTexture = FungusEditorResources.EventNodeOff; graphics.onTexture = FungusEditorResources.EventNodeOn; defaultTint = FungusConstants.DefaultEventBlockTint; } else { // Count the number of unique connections (excluding self references) var uniqueList = new List<Block>(); var connectedBlocks = block.GetConnectedBlocks(); foreach (var connectedBlock in connectedBlocks) { if (connectedBlock == block || uniqueList.Contains(connectedBlock)) { continue; } uniqueList.Add(connectedBlock); } if (uniqueList.Count > 1) { graphics.offTexture = FungusEditorResources.ChoiceNodeOff; graphics.onTexture = FungusEditorResources.ChoiceNodeOn; defaultTint = FungusConstants.DefaultChoiceBlockTint; } else { graphics.offTexture = FungusEditorResources.ProcessNodeOff; graphics.onTexture = FungusEditorResources.ProcessNodeOn; defaultTint = FungusConstants.DefaultProcessBlockTint; } } graphics.tint = block.UseCustomTint ? block.Tint : defaultTint; return graphics; } } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using System; using System.Reflection; using System.Globalization; using System.Collections; using System.Runtime.InteropServices; [Serializable] internal sealed class JSBinder : Binder{ internal static readonly JSBinder ob = new JSBinder(); // both args and namedParameters cannot be null and args length must be bigger or equal to namedParameters.Length internal static Object[] ArrangeNamedArguments(MethodBase method, Object[] args, string[] namedParameters){ ParameterInfo[] pars = method.GetParameters(); int formalLength = pars.Length; if (formalLength == 0) throw new JScriptException(JSError.MissingNameParameter); Object[] newArgs = new Object[formalLength]; int argsLength = args.Length; int namesLength = namedParameters.Length; int numPositional = argsLength - namesLength; ArrayObject.Copy(args, namesLength, newArgs, 0, numPositional); for (int i = 0; i < namesLength; i++){ string name = namedParameters[i]; if (name == null || name.Equals("")) throw new JScriptException(JSError.MustProvideNameForNamedParameter); int j; for (j = numPositional; j < formalLength; j++){ if (name.Equals(pars[j].Name)) if (newArgs[j] is Empty) throw new JScriptException(JSError.DuplicateNamedParameter); else{ newArgs[j] = args[i]; break; } } if (j == formalLength) throw new JScriptException(JSError.MissingNameParameter); } // go through the array and replace null/missing entries with the default value of the corresponding param (if any) if (method is JSMethod) return newArgs; //JSMethods get special treatment elsewhere for (int i = 0; i < formalLength; i++) if (newArgs[i] == null || newArgs[i] == Missing.Value){ Object dv = TypeReferences.GetDefaultParameterValue(pars[i]); if (dv == System.Convert.DBNull) //No default value was specified throw new ArgumentException(pars[i].Name); newArgs[i] = dv; } return newArgs; } public override FieldInfo BindToField(BindingFlags bindAttr, FieldInfo[] match, Object value, CultureInfo locale){ if (value == null) value = DBNull.Value; int minval = Int32.MaxValue; int dupCount = 0; FieldInfo bestField = null; Type vtype = value.GetType(); for (int i = 0, j = match.Length; i < j; i++){ FieldInfo field = match[i]; int distance = TypeDistance(Runtime.TypeRefs, field.FieldType, vtype); if (distance < minval){ minval = distance; bestField = field; dupCount = 0; }else if (distance == minval) dupCount += 1; } if (dupCount > 0) throw new AmbiguousMatchException(); return bestField; } public override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref Object[] args, ParameterModifier[] modifiers, CultureInfo locale, String[] namedParameters, out Object state){ state = null; return JSBinder.SelectMethodBase(Runtime.TypeRefs, match, ref args, modifiers, namedParameters); } public override Object ChangeType(Object value, Type target_type, CultureInfo locale){ return Convert.CoerceT(value, target_type); } internal static MemberInfo[] GetDefaultMembers(IReflect ir){ return JSBinder.GetDefaultMembers(Globals.TypeRefs, ir); } internal static MemberInfo[] GetDefaultMembers(TypeReferences typeRefs, IReflect ir){ while (ir is ClassScope){ ClassScope csc = (ClassScope)ir; csc.owner.IsExpando(); //Force the class to expose its expando property if it has not already done so if (csc.itemProp != null) return new MemberInfo[]{csc.itemProp}; ir = csc.GetParent(); if (ir is WithObject) ir = (IReflect)((WithObject)ir).contained_object; } if (ir is Type) return JSBinder.GetDefaultMembers((Type)ir); if (ir is JSObject) return typeRefs.ScriptObject.GetDefaultMembers(); return null; } internal static MemberInfo[] GetDefaultMembers(Type t){ while (t != typeof(Object) && t != null){ MemberInfo[] defaultMembers = t.GetDefaultMembers(); if (defaultMembers != null && defaultMembers.Length > 0) return defaultMembers; t = t.BaseType; } return null; } internal static MethodInfo GetDefaultPropertyForArrayIndex(Type t, int index, Type elementType, bool getSetter){ try{ MemberInfo[] defaultMembers = JSBinder.GetDefaultMembers(Runtime.TypeRefs, t); int n = 0; if (defaultMembers == null || (n = defaultMembers.Length) == 0) return null; for (int i = 0; i < n; i++){ MemberInfo mem = defaultMembers[i]; MemberTypes mt = mem.MemberType; MethodInfo meth = null; switch (mt){ case MemberTypes.Property: meth = ((PropertyInfo)mem).GetGetMethod(); break; case MemberTypes.Method: meth = (MethodInfo)mem; break; default: continue; } if (meth != null){ ParameterInfo[] pars = meth.GetParameters(); if (pars == null || pars.Length == 0){ //See if meth is a default method/property-getter that returns an Array or List Type rt = meth.ReturnType; if (typeof(Array).IsAssignableFrom(rt) || typeof(IList).IsAssignableFrom(rt)) return meth; }else if (pars.Length == 1 && mt == MemberTypes.Property){ //See if meth is the getter of a suitable default indexed property PropertyInfo prop = (PropertyInfo)mem; if (elementType == null || prop.PropertyType.IsAssignableFrom(elementType)) try{ Convert.CoerceT(index, pars[0].ParameterType); if (getSetter) return prop.GetSetMethod(); else return meth; }catch(JScriptException){} } } } }catch(InvalidOperationException){} return null; } internal static MemberInfo[] GetInterfaceMembers(String name, Type t){ BindingFlags flags = BindingFlags.Public|BindingFlags.Instance|BindingFlags.Static|BindingFlags.DeclaredOnly; MemberInfo[] members = t.GetMember(name, flags); Type[] baseInts = t.GetInterfaces(); if (baseInts == null || baseInts.Length == 0) return members; ArrayList baseInterfaces = new ArrayList(baseInts); MemberInfoList result = new MemberInfoList(); result.AddRange(members); for (int i = 0; i < baseInterfaces.Count; i++){ Type bi = (Type)baseInterfaces[i]; members = bi.GetMember(name, flags); if (members != null) result.AddRange(members); foreach (Type bbi in bi.GetInterfaces()){ if (baseInterfaces.IndexOf(bbi) == -1) baseInterfaces.Add(bbi); } } return result.ToArray(); } private static bool FormalParamTypeIsObject(ParameterInfo par){ ParameterDeclaration pd = par as ParameterDeclaration; if (pd != null) return pd.ParameterIReflect == Typeob.Object; return par.ParameterType == Typeob.Object; } public override void ReorderArgumentArray(ref Object[] args, Object state){ } internal static MemberInfo Select(TypeReferences typeRefs, MemberInfo[] match, int matches, IReflect[] argIRs, MemberTypes memberType){ Debug.Assert(matches > 1); int candidates = 0; ParameterInfo[][] fparams = new ParameterInfo[matches][]; bool lookForPropertyGetters = memberType == MemberTypes.Method; for (int i = 0; i < matches; i++){ MemberInfo mem = match[i]; if (mem is PropertyInfo && lookForPropertyGetters) mem = ((PropertyInfo)mem).GetGetMethod(true); if (mem == null) continue; if (mem.MemberType == memberType){ if (mem is PropertyInfo) fparams[i] = ((PropertyInfo)mem).GetIndexParameters(); else fparams[i] = ((MethodBase)mem).GetParameters(); candidates++; } } int j = JSBinder.SelectBest(typeRefs, match, matches, argIRs, fparams, null, candidates, argIRs.Length); if (j < 0) return null; return match[j]; } internal static MemberInfo Select(TypeReferences typeRefs, MemberInfo[] match, int matches, ref Object[] args, String[] namedParameters, MemberTypes memberType){ Debug.Assert(matches > 1); bool hasNamedParams = false; if (namedParameters != null && namedParameters.Length > 0) if (args.Length >= namedParameters.Length) hasNamedParams = true; else throw new JScriptException(JSError.MoreNamedParametersThanArguments); int candidates = 0; ParameterInfo[][] fparams = new ParameterInfo[matches][]; Object[][] aparams = new Object[matches][]; bool lookForPropertyGetters = memberType == MemberTypes.Method; for (int i = 0; i < matches; i++){ MemberInfo mem = match[i]; if (lookForPropertyGetters && mem.MemberType == MemberTypes.Property) mem = ((PropertyInfo)mem).GetGetMethod(true); if (mem.MemberType == memberType){ if (memberType == MemberTypes.Property) fparams[i] = ((PropertyInfo)mem).GetIndexParameters(); else fparams[i] = ((MethodBase)mem).GetParameters(); if (hasNamedParams) aparams[i] = JSBinder.ArrangeNamedArguments((MethodBase)mem, args, namedParameters); else aparams[i] = args; candidates++; } } int j = JSBinder.SelectBest(typeRefs, match, matches, null, fparams, aparams, candidates, args.Length); if (j < 0) return null; args = aparams[j]; MemberInfo result = match[j]; if (lookForPropertyGetters && result.MemberType == MemberTypes.Property) result = ((PropertyInfo)result).GetGetMethod(true); return result; } private static int SelectBest(TypeReferences typeRefs, MemberInfo[] match, int matches, IReflect[] argIRs, ParameterInfo[][] fparams, Object[][] aparams, int candidates, int parameters){ Debug.Assert(matches > 1); if (candidates == 0) return -1; if (candidates == 1) for (int i = 0; i < matches; i++) if (fparams[i] != null) return i; bool[] eliminated = new bool[matches]; //Set up penalties to discourage selection of methods that have more formal parameters than there are actual parameters int[] penalty = new int[matches]; for (int i = 0; i < matches; i++){ ParameterInfo[] fpars = fparams[i]; if (fpars != null){ int m = fpars.Length; int actuals = (argIRs == null ? aparams[i].Length : argIRs.Length); if (actuals > m && (m == 0 || !CustomAttribute.IsDefined(fpars[m-1], typeof(ParamArrayAttribute), false))){ fparams[i] = null; candidates--; Debug.Assert(candidates >= 0); continue; } for (int j = parameters; j < m; j++){ ParameterInfo fpar = fpars[j]; if (j == m-1 && CustomAttribute.IsDefined(fpar, typeof(ParamArrayAttribute), false)) break; Object dv = TypeReferences.GetDefaultParameterValue(fpar); if (dv is System.DBNull){ //No default value, set up a penalty penalty[i] = 50; } } } } for (int p = 0; candidates > 1; p++){ int candidatesWithFormalParametersStillToBeConsidered = 0; //Eliminate any candidate that is worse match than any other candidate for this (possibly missing) actual parameter int minval = Int32.MaxValue; bool objectCanWin = false; for (int i = 0; i < matches; i++){ int penaltyForUsingDefaultValue = 0; ParameterInfo[] fpars = fparams[i]; if (fpars != null){ //match[i] is a candidate IReflect aIR = typeRefs.Missing; if (argIRs == null){ if (aparams[i].Length > p){ Object apar = aparams[i][p]; if (apar == null) apar = DBNull.Value; aIR = typeRefs.ToReferenceContext(apar.GetType()); } }else if (p < parameters) aIR = argIRs[p]; int m = fpars.Length; if (m-1 > p) candidatesWithFormalParametersStillToBeConsidered++; IReflect fIR = typeRefs.Missing; if (m > 0 && p >= m-1 && CustomAttribute.IsDefined(fpars[m-1], typeof(ParamArrayAttribute), false) && !(aIR is TypedArray || aIR == typeRefs.ArrayObject || (aIR is Type && ((Type)aIR).IsArray))){ ParameterInfo fpar = fpars[m-1]; if (fpar is ParameterDeclaration){ fIR = ((ParameterDeclaration)fpar).ParameterIReflect; fIR = ((TypedArray)fIR).elementType; }else fIR = fpar.ParameterType.GetElementType(); if (p == m-1) penalty[i]++; }else if (p < m){ ParameterInfo fpar = fpars[p]; fIR = fpar is ParameterDeclaration ? ((ParameterDeclaration)fpar).ParameterIReflect : fpar.ParameterType; if (aIR == typeRefs.Missing){ //No actual parameter was supplied, if the formal parameter has default value, make the match perfect Object dv = TypeReferences.GetDefaultParameterValue(fpar); if (!(dv is System.DBNull)) { aIR = fIR; penaltyForUsingDefaultValue = 1; } } } int distance = TypeDistance(typeRefs, fIR, aIR) + penalty[i] + penaltyForUsingDefaultValue; if (distance == minval){ if (p == m-1 && eliminated[i]){ candidates--; fparams[i] = null; } objectCanWin = objectCanWin && eliminated[i]; continue; } if (distance > minval){ if (objectCanWin && p < m && JSBinder.FormalParamTypeIsObject(fparams[i][p])){ minval = distance; //Make sure that a future, better match than Object can win. continue; } if (p > m-1 && aIR == typeRefs.Missing && CustomAttribute.IsDefined(fpars[m-1], typeof(ParamArrayAttribute), false)) continue; eliminated[i] = true; continue; } //If we get here, we have a match that is strictly better than all previous matches. //If there are no other remaining candidates, we're done. if (candidates == 1 && !eliminated[i]) return i; //Eliminate those other candidates from consideration. objectCanWin = eliminated[i]; for (int j = 0; j < i; j++) if (fparams[j] != null && !eliminated[j]){ bool noFormalForCurrParam = fparams[j].Length <= p; if (noFormalForCurrParam && parameters <= p) //Do not eliminate an overload if it does not have a formal for the current position //and the call does not have an actual parameter for the current position either. continue; if (noFormalForCurrParam || !objectCanWin || !JSBinder.FormalParamTypeIsObject(fparams[j][p])) eliminated[j] = true; } minval = distance; } } if (p >= parameters-1 && candidatesWithFormalParametersStillToBeConsidered < 1) //Looked at all actual parameters as well as all formal parameters, no further progress can be made break; } int best = -1; for (int j = 0; j < matches && candidates > 0; j++){ ParameterInfo[] fpars = fparams[j]; if (fpars != null){ if (eliminated[j]){ candidates--; fparams[j] = null; continue; } int pc = fpars.Length; if (best == -1){ //Choose the first remaining candidate as "best" best = j; continue; } if (Class.ParametersMatch(fpars, fparams[best])){ MemberInfo bstm = match[best]; JSWrappedMethod jswm = match[best] as JSWrappedMethod; if (jswm != null) bstm = jswm.method; if (bstm is JSFieldMethod || bstm is JSConstructor || bstm is JSProperty){ //The first match is always the most derived, go with it candidates--; fparams[j] = null; continue; } Type bestMemT = match[best].DeclaringType; Type memT = match[j].DeclaringType; if (bestMemT != memT){ if (memT.IsAssignableFrom(bestMemT)){ candidates--; fparams[j] = null; continue; }else if (bestMemT.IsAssignableFrom(memT)){ fparams[best] = null; best = j; candidates--; continue; } } } } } if (candidates != 1) throw new AmbiguousMatchException(); return best; } internal static ConstructorInfo SelectConstructor(MemberInfo[] match, ref Object[] args, String[] namedParameters){ return JSBinder.SelectConstructor(Globals.TypeRefs, match, ref args, namedParameters); } internal static ConstructorInfo SelectConstructor(TypeReferences typeRefs, MemberInfo[] match, ref Object[] args, String[] namedParameters){ if (match == null) return null; int n = match.Length; if (n == 0) return null; if (n == 1){ Type t = match[0] as Type; if (t != null) { match = t.GetConstructors(); n = match.Length; } } if (n == 1) return match[0] as ConstructorInfo; return (ConstructorInfo)JSBinder.Select(typeRefs, match, n, ref args, namedParameters, MemberTypes.Constructor); } internal static ConstructorInfo SelectConstructor(MemberInfo[] match, IReflect[] argIRs){ return JSBinder.SelectConstructor(Globals.TypeRefs, match, argIRs); } internal static ConstructorInfo SelectConstructor(TypeReferences typeRefs, MemberInfo[] match, IReflect[] argIRs){ if (match == null) return null; int n = match.Length; if (n == 1){ Object val = match[0]; if (val is JSGlobalField) val = ((JSGlobalField)val).GetValue(null); Type t = val as Type; if (t != null){ match = t.GetConstructors(); } n = match.Length; } if (n == 0) return null; if (n == 1) return match[0] as ConstructorInfo; return (ConstructorInfo)JSBinder.Select(typeRefs, match, n, argIRs, MemberTypes.Constructor); } internal static MemberInfo SelectCallableMember(MemberInfo[] match, IReflect[] argIRs) { if (match == null) return null; int n = match.Length; if (n == 0) return null; MemberInfo result = n == 1 ? match[0] : JSBinder.Select(Globals.TypeRefs, match, n, argIRs, MemberTypes.Method); return result as MemberInfo; } internal static MethodInfo SelectMethod(MemberInfo[] match, ref Object[] args, String[] namedParameters){ return JSBinder.SelectMethod(Globals.TypeRefs, match, ref args, namedParameters); } internal static MethodInfo SelectMethod(TypeReferences typeRefs, MemberInfo[] match, ref Object[] args, String[] namedParameters){ if (match == null) return null; int n = match.Length; if (n == 0) return null; MemberInfo result = n == 1 ? match[0] : JSBinder.Select(typeRefs, match, n, ref args, namedParameters, MemberTypes.Method); if (result != null && result.MemberType == MemberTypes.Property) result = ((PropertyInfo)result).GetGetMethod(true); return result as MethodInfo; } internal static MethodInfo SelectMethod(MemberInfo[] match, IReflect[] argIRs){ return JSBinder.SelectMethod(Globals.TypeRefs, match, argIRs); } internal static MethodInfo SelectMethod(TypeReferences typeRefs, MemberInfo[] match, IReflect[] argIRs){ if (match == null) return null; int n = match.Length; if (n == 0) return null; MemberInfo result = n == 1 ? match[0] : JSBinder.Select(typeRefs, match, n, argIRs, MemberTypes.Method); if (result != null && result.MemberType == MemberTypes.Property) return ((PropertyInfo)result).GetGetMethod(true); return result as MethodInfo; } public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers){ if (match == null) return null; int n = match.Length; if (n == 0) return null; if (n == 1) return match[0]; if (match[0].MemberType == MemberTypes.Constructor) return (ConstructorInfo)JSBinder.Select(Runtime.TypeRefs, match, n, types, MemberTypes.Constructor); else return (MethodInfo)JSBinder.Select(Runtime.TypeRefs, match, n, types, MemberTypes.Method); } private static MethodBase SelectMethodBase(TypeReferences typeRefs, MethodBase[] match, ref Object[] args, ParameterModifier[] modifiers, String[] namedParameters){ if (match == null) return null; int n = match.Length; if (n == 0) return null; if (n == 1) return match[0]; MethodBase result = (MethodBase)JSBinder.Select(typeRefs, match, n, ref args, namedParameters, MemberTypes.Method); if (result == null) result = (MethodBase)JSBinder.Select(typeRefs, match, n, ref args, namedParameters, MemberTypes.Constructor); return result; } internal static MethodInfo SelectOperator(MethodInfo op1, MethodInfo op2, Type t1, Type t2){ ParameterInfo[] params1 = null; if (op1 == null || (op1.Attributes & MethodAttributes.SpecialName) == 0 || (params1 = op1.GetParameters()).Length != 2) op1 = null; ParameterInfo[] params2 = null; if (op2 == null || (op2.Attributes & MethodAttributes.SpecialName) == 0 || (params2 = op2.GetParameters()).Length != 2) op2 = null; if (op1 == null) return op2; if (op2 == null) return op1; int op1cost = TypeDistance(Globals.TypeRefs, params1[0].ParameterType, t1) + TypeDistance(Globals.TypeRefs, params1[1].ParameterType, t2); int op2cost = TypeDistance(Globals.TypeRefs, params2[0].ParameterType, t1) + TypeDistance(Globals.TypeRefs, params2[1].ParameterType, t2); if (op1cost <= op2cost) return op1; return op2; } internal static PropertyInfo SelectProperty(MemberInfo[] match, Object[] args){ return JSBinder.SelectProperty(Globals.TypeRefs, match, args); } internal static PropertyInfo SelectProperty(TypeReferences typeRefs, MemberInfo[] match, Object[] args){ if (match == null) return null; int matches = match.Length; if (matches == 0) return null; if (matches == 1) return match[0] as PropertyInfo; int candidates = 0; PropertyInfo result = null; ParameterInfo[][] fparams = new ParameterInfo[matches][]; Object[][] aparams = new Object[matches][]; for (int i = 0; i < matches; i++){ MemberInfo mem = match[i]; if (mem.MemberType == MemberTypes.Property){ MethodInfo getter = (result = (PropertyInfo)mem).GetGetMethod(true); if (getter == null) fparams[i] = result.GetIndexParameters(); else fparams[i] = getter.GetParameters(); aparams[i] = args; candidates++; } } if (candidates <= 1) return result; int j = JSBinder.SelectBest(typeRefs, match, matches, null, fparams, aparams, candidates, args.Length); if (j < 0) return null; return (PropertyInfo)match[j]; } public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type rtype, Type[] types, ParameterModifier[] modifiers){ if (match == null) return null; int matches = match.Length; if (matches == 0) return null; if (matches == 1) return match[0]; int candidates = 0; PropertyInfo result = null; int minval = Int32.MaxValue; ParameterInfo[][] fparams = new ParameterInfo[matches][]; for (int i = 0; i < matches; i++){ result = match[i]; if (rtype != null){ int distance = TypeDistance(Globals.TypeRefs, result.PropertyType, rtype); if (distance > minval) continue; if (distance < minval) //This property is strictly a better than all previous one w.r.t. rtype. Remove all of those from consideration for (int j = 0; j < i; j++) if (fparams[j] != null){ fparams[j] = null; candidates--; } } fparams[i] = result.GetIndexParameters(); candidates++; } if (candidates <= 1) return result; int k = JSBinder.SelectBest(Globals.TypeRefs, match, matches, types, fparams, null, candidates, types.Length); if (k < 0) return null; return match[k]; } internal static PropertyInfo SelectProperty(MemberInfo[] match, IReflect[] argIRs){ return JSBinder.SelectProperty(Globals.TypeRefs, match, argIRs); } internal static PropertyInfo SelectProperty(TypeReferences typeRefs, MemberInfo[] match, IReflect[] argIRs){ if (match == null) return null; int n = match.Length; if (n == 0) return null; if (n == 1) return match[0] as PropertyInfo; return (PropertyInfo)JSBinder.Select(typeRefs, match, n, argIRs, MemberTypes.Property); } //Returns a value that quantifies the cost/badness of converting a value of type actual to type formal. //Used to select the overload that is the closest match to the actual parameter. private static int TypeDistance(TypeReferences typeRefs, IReflect formal, IReflect actual){ if (formal is TypedArray){ if (actual is TypedArray){ TypedArray f = (TypedArray)formal; TypedArray a = (TypedArray)actual; if (f.rank == a.rank) return TypeDistance(typeRefs, f.elementType, a.elementType) == 0 ? 0 : 100; }else if (actual is Type){ TypedArray f = (TypedArray)formal; Type a = (Type)actual; if (a.IsArray && f.rank == a.GetArrayRank()) return TypeDistance(typeRefs, f.elementType, a.GetElementType()) == 0 ? 0 : 100; else if (a == typeRefs.Array || a == typeRefs.ArrayObject) return 30; } return 100; } if (actual is TypedArray){ if (formal is Type){ Type f = (Type)formal; TypedArray a = (TypedArray)actual; if (f.IsArray && f.GetArrayRank() == a.rank) return TypeDistance(typeRefs, f.GetElementType(), a.elementType) == 0 ? 0 : 100; else if (f == typeRefs.Array) return 30; else if (f == typeRefs.Object) return 50; } return 100; } if (formal is ClassScope){ if (actual is ClassScope) return ((ClassScope)actual).IsSameOrDerivedFrom((ClassScope)formal) ? 0 : 100; else return 100; } if (actual is ClassScope){ if (formal is Type) return ((ClassScope)actual).IsPromotableTo((Type)formal) ? 0 : 100; else return 100; } return TypeDistance(typeRefs, Convert.ToType(typeRefs, formal), Convert.ToType(typeRefs, actual)); } private static int TypeDistance(TypeReferences typeRefs, Type formal, Type actual){ TypeCode atc = Type.GetTypeCode(actual); TypeCode ftc = Type.GetTypeCode(formal); if (actual.IsEnum) atc = TypeCode.Object; if (formal.IsEnum) ftc = TypeCode.Object; switch(atc){ case TypeCode.DBNull: switch(ftc){ default: return formal == typeRefs.Object ? 0 : 1; } case TypeCode.Boolean: switch(ftc){ case TypeCode.Boolean: return 0; case TypeCode.Byte: return 1; case TypeCode.UInt16: return 2; case TypeCode.UInt32: return 3; case TypeCode.UInt64: return 4; case TypeCode.SByte: return 5; case TypeCode.Int16: return 6; case TypeCode.Int32: return 7; case TypeCode.Int64: return 8; case TypeCode.Single: return 9; case TypeCode.Double: return 10; case TypeCode.Decimal: return 11; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 12); case TypeCode.String: return 13; default: return 100; } case TypeCode.Char: switch(ftc){ case TypeCode.Char: return 0; case TypeCode.UInt16: return 1; case TypeCode.UInt32: return 2; case TypeCode.Int32: return 3; case TypeCode.UInt64: return 4; case TypeCode.Int64: return 5; case TypeCode.Single: return 6; case TypeCode.Double: return 7; case TypeCode.Decimal: return 8; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 9); case TypeCode.String: return 10; case TypeCode.Int16: return 11; case TypeCode.Byte: return 12; case TypeCode.SByte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.SByte: switch(ftc){ case TypeCode.SByte: return 0; case TypeCode.Int16: return 1; case TypeCode.Int32: return 2; case TypeCode.Int64: return 3; case TypeCode.Single: return 4; case TypeCode.Double: return 5; case TypeCode.Decimal: return 6; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 7); case TypeCode.String: return 8; case TypeCode.Byte: return 9; case TypeCode.UInt16: return 10; case TypeCode.UInt32: return 12; case TypeCode.UInt64: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.Byte: switch(ftc){ case TypeCode.Byte: return 0; case TypeCode.UInt16: return 1; case TypeCode.Int16: return 3; case TypeCode.UInt32: return 4; case TypeCode.Int32: return 5; case TypeCode.UInt64: return 6; case TypeCode.Int64: return 7; case TypeCode.Single: return 8; case TypeCode.Double: return 9; case TypeCode.Decimal: return 10; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 11); case TypeCode.String: return 12; case TypeCode.SByte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.Int16: switch(ftc){ case TypeCode.Int16: return 0; case TypeCode.Int32: return 1; case TypeCode.Int64: return 2; case TypeCode.Single: return 3; case TypeCode.Double: return 4; case TypeCode.Decimal: return 5; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 6); case TypeCode.String: return 7; case TypeCode.UInt16: return 8; case TypeCode.UInt32: return 10; case TypeCode.UInt64: return 11; case TypeCode.SByte: return 12; case TypeCode.Byte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.UInt16: switch(ftc){ case TypeCode.UInt16: return 0; case TypeCode.UInt32: return 1; case TypeCode.UInt64: return 2; case TypeCode.Int32: return 4; case TypeCode.Int64: return 5; case TypeCode.Single: return 6; case TypeCode.Double: return 7; case TypeCode.Decimal: return 8; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 9); case TypeCode.String: return 10; case TypeCode.Int16: return 11; case TypeCode.Byte: return 12; case TypeCode.SByte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.Int32: switch(ftc){ case TypeCode.Int32: return 0; case TypeCode.Int64: return 1; case TypeCode.Double: return 2; case TypeCode.Decimal: return 3; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 4); case TypeCode.String: return 5; case TypeCode.UInt64: return 6; case TypeCode.UInt32: return 7; case TypeCode.Single: return 8; case TypeCode.Int16: return 9; case TypeCode.UInt16: return 10; case TypeCode.SByte: return 12; case TypeCode.Byte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.UInt32: switch(ftc){ case TypeCode.UInt32: return 0; case TypeCode.UInt64: return 1; case TypeCode.Int64: return 2; case TypeCode.Double: return 3; case TypeCode.Decimal: return 4; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 5); case TypeCode.String: return 6; case TypeCode.Int32: return 7; case TypeCode.Single: return 8; case TypeCode.UInt16: return 9; case TypeCode.Int16: return 11; case TypeCode.Byte: return 12; case TypeCode.SByte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.Int64: switch(ftc){ case TypeCode.Int64: return 0; case TypeCode.Decimal: return 1; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 2); case TypeCode.String: return 3; case TypeCode.Double: return 4; case TypeCode.Single: return 5; case TypeCode.Int32: return 6; case TypeCode.Int16: return 7; case TypeCode.SByte: return 8; case TypeCode.UInt64: return 9; case TypeCode.UInt32: return 10; case TypeCode.UInt16: return 11; case TypeCode.Byte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.UInt64: switch(ftc){ case TypeCode.UInt64: return 0; case TypeCode.Decimal: return 1; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 2); case TypeCode.String: return 3; case TypeCode.Int64: return 4; case TypeCode.Double: return 5; case TypeCode.Single: return 6; case TypeCode.UInt32: return 7; case TypeCode.UInt16: return 8; case TypeCode.Byte: return 10; case TypeCode.Int32: return 11; case TypeCode.Int16: return 12; case TypeCode.SByte: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.Single: switch(ftc){ case TypeCode.Single: return 0; case TypeCode.Double: return 1; case TypeCode.Decimal: return 2; case TypeCode.Int64: return 3; case TypeCode.UInt64: return 4; case TypeCode.Int32: return 5; case TypeCode.UInt32: return 6; case TypeCode.Int16: return 7; case TypeCode.UInt16: return 8; case TypeCode.SByte: return 10; case TypeCode.Byte: return 11; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 12); case TypeCode.String: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.Double: switch(ftc){ case TypeCode.Double: return 0; case TypeCode.Decimal: return 1; case TypeCode.Single: return 2; case TypeCode.Int64: return 3; case TypeCode.UInt64: return 4; case TypeCode.Int32: return 5; case TypeCode.UInt32: return 6; case TypeCode.Int16: return 7; case TypeCode.UInt16: return 8; case TypeCode.SByte: return 10; case TypeCode.Byte: return 11; case TypeCode.Object: return TypeDistance(typeRefs, formal, actual, 12); case TypeCode.String: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.Decimal: switch(ftc){ case TypeCode.Decimal: return 0; case TypeCode.Double: return 1; case TypeCode.Single: return 2; case TypeCode.Int64: return 3; case TypeCode.UInt64: return 4; case TypeCode.Int32: return 5; case TypeCode.UInt32: return 6; case TypeCode.Int16: return 7; case TypeCode.UInt16: return 8; case TypeCode.SByte: return 10; case TypeCode.Byte: return 11; case TypeCode.Object: return formal == typeRefs.Object ? 12 : 100; case TypeCode.String: return 13; case TypeCode.Boolean: return 14; default: return 100; } case TypeCode.DateTime: switch(ftc){ case TypeCode.DateTime: return 0; case TypeCode.Object: return formal == typeRefs.Object ? 1 : 100; case TypeCode.String: return 3; case TypeCode.Double: return 4; case TypeCode.Decimal: return 5; case TypeCode.UInt64: return 6; case TypeCode.Int64: return 7; case TypeCode.UInt32: return 8; case TypeCode.Int32: return 9; default: return 100; } case TypeCode.String: switch(ftc){ case TypeCode.String: return 0; case TypeCode.Object: return formal == typeRefs.Object ? 1 : 100; case TypeCode.Char: return 2; default: return 100; } case TypeCode.Object: if (formal == actual) return 0; if (formal == typeRefs.Missing) return 200; if (!(formal.IsAssignableFrom(actual))){ if (typeRefs.Array.IsAssignableFrom(formal) && (actual == typeRefs.Array || typeRefs.ArrayObject.IsAssignableFrom(actual))) return 10; else if (ftc == TypeCode.String) return 20; else if (actual == typeRefs.ScriptFunction && typeRefs.Delegate.IsAssignableFrom(formal)) return 19; else return 100; } Type[] interfaces = actual.GetInterfaces(); int i; int n = interfaces.Length; for (i = 0; i < n; i++) if (formal == interfaces[i]) return i+1; for (i = 0; actual != typeRefs.Object && actual != null; i++){ if (formal == actual) return i+n+1; actual = actual.BaseType; } return i+n+1; } return 0; //should never get here } private static int TypeDistance(TypeReferences typeRefs, Type formal, Type actual, int distFromObject){ if (formal == typeRefs.Object) return distFromObject; if (formal.IsEnum) return TypeDistance(typeRefs, Enum.GetUnderlyingType(formal), actual)+10; return 100; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Samples.WebApi.PolicyService.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils { using System; using System.Globalization; using DiscUtils.Partitions; /// <summary> /// Enumeration of possible types of physical volume. /// </summary> public enum PhysicalVolumeType { /// <summary> /// Unknown type. /// </summary> None, /// <summary> /// Physical volume encompasses the entire disk. /// </summary> EntireDisk, /// <summary> /// Physical volume is defined by a BIOS-style partition table. /// </summary> BiosPartition, /// <summary> /// Physical volume is defined by a GUID partition table. /// </summary> GptPartition, /// <summary> /// Physical volume is defined by an Apple partition map. /// </summary> ApplePartition } /// <summary> /// Information about a physical disk volume, which may be a partition or an entire disk. /// </summary> public sealed class PhysicalVolumeInfo : VolumeInfo { private string _diskId; private VirtualDisk _disk; private SparseStreamOpenDelegate _streamOpener; private PhysicalVolumeType _type; private PartitionInfo _partitionInfo; /// <summary> /// Initializes a new instance of the PhysicalVolumeInfo class. /// </summary> /// <param name="diskId">The containing disk's identity.</param> /// <param name="disk">The disk containing the partition.</param> /// <param name="partitionInfo">Information about the partition.</param> /// <remarks>Use this constructor to represent a (BIOS or GPT) partition.</remarks> internal PhysicalVolumeInfo( string diskId, VirtualDisk disk, PartitionInfo partitionInfo) { _diskId = diskId; _disk = disk; _streamOpener = partitionInfo.Open; _type = partitionInfo.VolumeType; _partitionInfo = partitionInfo; } /// <summary> /// Initializes a new instance of the PhysicalVolumeInfo class. /// </summary> /// <param name="diskId">The identity of the disk.</param> /// <param name="disk">The disk itself.</param> /// <remarks>Use this constructor to represent an entire disk as a single volume.</remarks> internal PhysicalVolumeInfo( string diskId, VirtualDisk disk) { _diskId = diskId; _disk = disk; _streamOpener = delegate { return new SubStream(disk.Content, Ownership.None, 0, disk.Capacity); }; _type = PhysicalVolumeType.EntireDisk; } /// <summary> /// Gets the type of the volume. /// </summary> public PhysicalVolumeType VolumeType { get { return _type; } } /// <summary> /// Gets the signature of the disk containing the volume (only valid for partition-type volumes). /// </summary> public int DiskSignature { get { return (_type != PhysicalVolumeType.EntireDisk) ? _disk.Signature : 0; } } /// <summary> /// Gets the unique identity of the disk containing the volume, if known. /// </summary> public Guid DiskIdentity { get { return (_type != PhysicalVolumeType.EntireDisk) ? _disk.Partitions.DiskGuid : Guid.Empty; } } /// <summary> /// Gets the one-byte BIOS type for this volume, which indicates the content. /// </summary> public override byte BiosType { get { return (_partitionInfo == null) ? (byte)0 : _partitionInfo.BiosType; } } /// <summary> /// Gets the size of the volume, in bytes. /// </summary> public override long Length { get { return (_partitionInfo == null) ? _disk.Capacity : _partitionInfo.SectorCount * _disk.SectorSize; } } /// <summary> /// Gets the stable identity for this physical volume. /// </summary> /// <remarks>The stability of the identity depends the disk structure. /// In some cases the identity may include a simple index, when no other information /// is available. Best practice is to add disks to the Volume Manager in a stable /// order, if the stability of this identity is paramount.</remarks> public override string Identity { get { if (_type == PhysicalVolumeType.GptPartition) { return "VPG" + PartitionIdentity.ToString("B"); } else { string partId; switch (_type) { case PhysicalVolumeType.EntireDisk: partId = "PD"; break; case PhysicalVolumeType.BiosPartition: case PhysicalVolumeType.ApplePartition: partId = "PO" + (_partitionInfo.FirstSector * _disk.SectorSize).ToString("X", CultureInfo.InvariantCulture); break; default: partId = "P*"; break; } return "VPD:" + _diskId + ":" + partId; } } } /// <summary> /// Gets the disk geometry of the underlying storage medium, if any (may be null). /// </summary> public override Geometry PhysicalGeometry { get { return _disk.Geometry; } } /// <summary> /// Gets the disk geometry of the underlying storage medium (as used in BIOS calls), may be null. /// </summary> public override Geometry BiosGeometry { get { return _disk.BiosGeometry; } } /// <summary> /// Gets the offset of this volume in the underlying storage medium, if any (may be Zero). /// </summary> public override long PhysicalStartSector { get { return _type == PhysicalVolumeType.EntireDisk ? 0 : _partitionInfo.FirstSector; } } /// <summary> /// Gets the unique identity of the physical partition, if known. /// </summary> public Guid PartitionIdentity { get { GuidPartitionInfo gpi = _partitionInfo as GuidPartitionInfo; if (gpi != null) { return gpi.Identity; } return Guid.Empty; } } /// <summary> /// Gets the underlying partition (if any). /// </summary> internal PartitionInfo Partition { get { return _partitionInfo; } } /// <summary> /// Opens the volume, providing access to its contents. /// </summary> /// <returns>A stream that can be used to access the volume.</returns> public override SparseStream Open() { return _streamOpener(); } } }
using J2N.Threading; using YAF.Lucene.Net.Support; using System; using System.Threading; namespace YAF.Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using TrackingIndexWriter = YAF.Lucene.Net.Index.TrackingIndexWriter; /// <summary> /// Utility class that runs a thread to manage periodic /// reopens of a <see cref="ReferenceManager{T}"/>, with methods to wait for a specific /// index changes to become visible. To use this class you /// must first wrap your <see cref="Index.IndexWriter"/> with a /// <see cref="TrackingIndexWriter"/> and always use it to make changes /// to the index, saving the returned generation. Then, /// when a given search request needs to see a specific /// index change, call the <see cref="WaitForGeneration(long)"/> to wait for /// that change to be visible. Note that this will only /// scale well if most searches do not need to wait for a /// specific index generation. /// <para/> /// @lucene.experimental /// </summary> public class ControlledRealTimeReopenThread<T> : ThreadJob, IDisposable where T : class { private readonly ReferenceManager<T> manager; private readonly long targetMaxStaleNS; private readonly long targetMinStaleNS; private readonly TrackingIndexWriter writer; private volatile bool finish; private long waitingGen; private long searchingGen; private long refreshStartGen; private EventWaitHandle reopenCond = new AutoResetEvent(false); private EventWaitHandle available = new AutoResetEvent(false); /// <summary> /// Create <see cref="ControlledRealTimeReopenThread{T}"/>, to periodically /// reopen the a <see cref="ReferenceManager{T}"/>. /// </summary> /// <param name="targetMaxStaleSec"> Maximum time until a new /// reader must be opened; this sets the upper bound /// on how slowly reopens may occur, when no /// caller is waiting for a specific generation to /// become visible. /// </param> /// <param name="targetMinStaleSec"> Mininum time until a new /// reader can be opened; this sets the lower bound /// on how quickly reopens may occur, when a caller /// is waiting for a specific generation to /// become visible. </param> public ControlledRealTimeReopenThread(TrackingIndexWriter writer, ReferenceManager<T> manager, double targetMaxStaleSec, double targetMinStaleSec) { if (targetMaxStaleSec < targetMinStaleSec) { throw new System.ArgumentException("targetMaxScaleSec (= " + targetMaxStaleSec.ToString("0.0") + ") < targetMinStaleSec (=" + targetMinStaleSec.ToString("0.0") + ")"); } this.writer = writer; this.manager = manager; this.targetMaxStaleNS = (long)(1000000000 * targetMaxStaleSec); this.targetMinStaleNS = (long)(1000000000 * targetMinStaleSec); manager.AddListener(new HandleRefresh(this)); } private class HandleRefresh : ReferenceManager.IRefreshListener { private readonly ControlledRealTimeReopenThread<T> outerInstance; public HandleRefresh(ControlledRealTimeReopenThread<T> outerInstance) { this.outerInstance = outerInstance; } public virtual void BeforeRefresh() { } public virtual void AfterRefresh(bool didRefresh) { outerInstance.RefreshDone(); } } private void RefreshDone() { lock (this) { // if we're finishing, , make it out so that all waiting search threads will return searchingGen = finish ? long.MaxValue : refreshStartGen; available.Set(); } reopenCond.Reset(); } public void Dispose() { finish = true; reopenCond.Set(); //#if !NETSTANDARD1_6 // try // { //#endif Join(); //#if !NETSTANDARD1_6 // LUCENENET NOTE: Senseless to catch and rethrow the same exception type // } // catch (ThreadInterruptedException ie) // { // throw new ThreadInterruptedException(ie.ToString(), ie); // } //#endif // LUCENENET specific: dispose reset event reopenCond.Dispose(); available.Dispose(); } /// <summary> /// Waits for the target generation to become visible in /// the searcher. /// If the current searcher is older than the /// target generation, this method will block /// until the searcher is reopened, by another via /// <see cref="ReferenceManager{T}.MaybeRefresh()"/> or until the <see cref="ReferenceManager{T}"/> is closed. /// </summary> /// <param name="targetGen"> The generation to wait for </param> public virtual void WaitForGeneration(long targetGen) { WaitForGeneration(targetGen, -1); } /// <summary> /// Waits for the target generation to become visible in /// the searcher, up to a maximum specified milli-seconds. /// If the current searcher is older than the target /// generation, this method will block until the /// searcher has been reopened by another thread via /// <see cref="ReferenceManager{T}.MaybeRefresh()"/>, the given waiting time has elapsed, or until /// the <see cref="ReferenceManager{T}"/> is closed. /// <para/> /// NOTE: if the waiting time elapses before the requested target generation is /// available the current <see cref="SearcherManager"/> is returned instead. /// </summary> /// <param name="targetGen"> /// The generation to wait for </param> /// <param name="maxMS"> /// Maximum milliseconds to wait, or -1 to wait indefinitely </param> /// <returns> <c>true</c> if the <paramref name="targetGen"/> is now available, /// or false if <paramref name="maxMS"/> wait time was exceeded </returns> public virtual bool WaitForGeneration(long targetGen, int maxMS) { long curGen = writer.Generation; if (targetGen > curGen) { throw new System.ArgumentException("targetGen=" + targetGen + " was never returned by the ReferenceManager instance (current gen=" + curGen + ")"); } lock (this) if (targetGen <= searchingGen) return true; else { waitingGen = Math.Max(waitingGen, targetGen); reopenCond.Set(); available.Reset(); } long startMS = Time.NanoTime() / 1000000; // LUCENENET specific - reading searchingGen not thread safe, so use Interlocked.Read() while (targetGen > Interlocked.Read(ref searchingGen)) { if (maxMS < 0) { available.WaitOne(); } else { long msLeft = (startMS + maxMS) - (Time.NanoTime()) / 1000000; if (msLeft <= 0) { return false; } else { available.WaitOne(TimeSpan.FromMilliseconds(msLeft)); } } } return true; } public override void Run() { // TODO: maybe use private thread ticktock timer, in // case clock shift messes up nanoTime? long lastReopenStartNS = DateTime.UtcNow.Ticks * 100; //System.out.println("reopen: start"); while (!finish) { bool hasWaiting; lock (this) hasWaiting = waitingGen > searchingGen; long nextReopenStartNS = lastReopenStartNS + (hasWaiting ? targetMinStaleNS : targetMaxStaleNS); long sleepNS = nextReopenStartNS - Time.NanoTime(); if (sleepNS > 0) #if !NETSTANDARD1_6 try { #endif reopenCond.WaitOne(TimeSpan.FromMilliseconds(sleepNS / Time.MILLISECONDS_PER_NANOSECOND));//Convert NS to Ticks #if !NETSTANDARD1_6 } #pragma warning disable 168 catch (ThreadInterruptedException ie) #pragma warning restore 168 { Thread.CurrentThread.Interrupt(); return; } #endif if (finish) { break; } lastReopenStartNS = Time.NanoTime(); // Save the gen as of when we started the reopen; the // listener (HandleRefresh above) copies this to // searchingGen once the reopen completes: refreshStartGen = writer.GetAndIncrementGeneration(); try { manager.MaybeRefreshBlocking(); } catch (System.IO.IOException ioe) { throw new Exception(ioe.ToString(), ioe); } } // this will set the searchingGen so that all waiting threads will exit RefreshDone(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Text; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; namespace OpenLiveWriter.PostEditor.Video.VideoService { public class VideoPagingControl : UserControl, IRtlAware { private Label labelQueryStatus; private OpenLiveWriter.Controls.XPBitmapButton buttonPreviousPage; private OpenLiveWriter.Controls.XPBitmapButton buttonNextPage; private readonly Bitmap _previousDisabledImage; private readonly Bitmap _previousEnabledImage; private readonly Bitmap _nextDisabledImage; private readonly Bitmap _nextEnabledImage; private int _currentPage = 1; public VideoPagingControl() { InitializeComponent(); _previousDisabledImage = new Bitmap(GetType(), "Images.PreviousVideosDisabled.png"); _previousEnabledImage = new Bitmap(GetType(), "Images.PreviousVideosEnabled.png"); _nextDisabledImage = new Bitmap(GetType(), "Images.NextVideosDisabled.png"); _nextEnabledImage = new Bitmap(GetType(), "Images.NextVideosEnabled.png"); buttonNextPage.Initialize(_nextEnabledImage, _nextDisabledImage); buttonPreviousPage.Initialize(_previousEnabledImage, _previousDisabledImage); buttonPreviousPage.Click += buttonPreviousPage_Click; buttonNextPage.Click += buttonNextPage_Click; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // We do this just to reverse the anchor directions of the children BidiHelper.RtlLayoutFixup(this, true, true, Controls); UpdateQueryStatus(); } public int NumberOfVideosPerPage { get { return NUMBEROFVIDEOSPERPAGE; } } private const int NUMBEROFVIDEOSPERPAGE = 10; public int NumberOfVideos { get { return _numberOfVideos; } set { _numberOfVideos = value; UpdateQueryStatus(); } } public void Reset() { NumberOfVideos = 0; _currentPage = 1; } private int _numberOfVideos = -1; public int Pages { get { return _pages; } set { _pages = value; } } private int _pages; public int CurrentPage { get { return _currentPage; } } public event EventHandler RefreshRequested; protected virtual void OnRefreshVideos() { if (RefreshRequested != null) RefreshRequested(this, EventArgs.Empty); } private void buttonPreviousPage_Click(object sender, EventArgs e) { if (_currentPage > 1) { _currentPage--; OnRefreshVideos(); } else { Trace.Fail("Invalid state: previous button enabled for first page"); } } private void buttonNextPage_Click(object sender, EventArgs e) { _currentPage++; OnRefreshVideos(); } protected override void Dispose(bool disposing) { if (disposing) { _nextDisabledImage.Dispose(); _nextEnabledImage.Dispose(); _previousDisabledImage.Dispose(); _previousEnabledImage.Dispose(); } base.Dispose(disposing); } private void RefreshLayout() { //DisplayHelper.AutoFitSystemLabel(labelQueryStatus, int.MinValue, int.MaxValue); //Width = buttonPreviousPage.Width + buttonNextPage.Width + labelQueryStatus.Width + 3*PADDING_X; buttonNextPage.Top = 0; buttonPreviousPage.Top = 0; if (BidiHelper.IsRightToLeft) { DisplayHelper.AutoFitSystemLabel(labelQueryStatus, int.MinValue, int.MaxValue); buttonNextPage.Left = 0; buttonPreviousPage.Left = buttonNextPage.Right + PADDING_X; labelQueryStatus.Left = buttonPreviousPage.Right + PADDING_X; } else { buttonNextPage.Left = Width - buttonNextPage.Width; buttonPreviousPage.Left = buttonNextPage.Left - buttonPreviousPage.Width - PADDING_X; labelQueryStatus.Left = buttonPreviousPage.Left - labelQueryStatus.Width - PADDING_X; labelQueryStatus.TextAlign = ContentAlignment.MiddleRight; } } private static readonly int PADDING_X = 2; private void UpdateQueryStatus() { // we got no videos if (_numberOfVideos < 1) { labelQueryStatus.Text = ""; buttonPreviousPage.Enabled = false; buttonNextPage.Enabled = false; } // we got all of the vidoes else if (_numberOfVideos < NUMBEROFVIDEOSPERPAGE) { labelQueryStatus.Text = FormatVideoString(1, _numberOfVideos) + " " + string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.Plugin_Video_Soapbox_Total_Videos), _numberOfVideos); buttonPreviousPage.Enabled = false; buttonNextPage.Enabled = false; } // we didn't get all of the videos else { // calculate indexes and status text int beginIndex = ((_currentPage - 1) * NUMBEROFVIDEOSPERPAGE) + 1; int endIndex = Math.Min((beginIndex + NUMBEROFVIDEOSPERPAGE) - 1, _numberOfVideos); string statusText = FormatVideoString(beginIndex, endIndex) + " " + String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.Plugin_Video_Soapbox_Total_Videos), _numberOfVideos); ; // set status text labelQueryStatus.Visible = true; labelQueryStatus.Text = statusText; // determine enabled/disabled state of next/prev buttons buttonPreviousPage.Visible = true; buttonPreviousPage.Enabled = _currentPage > 1; buttonNextPage.Enabled = _numberOfVideos > endIndex; } RefreshLayout(); } private static string FormatVideoString(int beginIndex, int endIndex) { if (beginIndex != endIndex) return String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.Plugin_Video_Soapbox_Result_Range), beginIndex, endIndex); else return String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.Plugin_Video_Soapbox_Result_Single), beginIndex); } private void InitializeComponent() { this.labelQueryStatus = new System.Windows.Forms.Label(); this.buttonPreviousPage = new OpenLiveWriter.Controls.XPBitmapButton(); this.buttonNextPage = new OpenLiveWriter.Controls.XPBitmapButton(); this.SuspendLayout(); // // labelQueryStatus // this.labelQueryStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.labelQueryStatus.BackColor = System.Drawing.SystemColors.Control; this.labelQueryStatus.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelQueryStatus.Location = new System.Drawing.Point(3, 1); this.labelQueryStatus.Name = "labelQueryStatus"; this.labelQueryStatus.Size = new System.Drawing.Size(192, 18); this.labelQueryStatus.TabIndex = 9; this.labelQueryStatus.Text = "11 to 20 (of 121)"; // // buttonPreviousPage // this.buttonPreviousPage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonPreviousPage.ForeColor = System.Drawing.SystemColors.ControlText; this.buttonPreviousPage.Location = new System.Drawing.Point(201, -1); this.buttonPreviousPage.Name = "buttonPreviousPage"; this.buttonPreviousPage.Size = new System.Drawing.Size(23, 21); this.buttonPreviousPage.TabIndex = 10; // // buttonNextPage // this.buttonNextPage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonNextPage.ForeColor = System.Drawing.SystemColors.ControlText; this.buttonNextPage.Location = new System.Drawing.Point(224, -1); this.buttonNextPage.Name = "buttonNextPage"; this.buttonNextPage.Size = new System.Drawing.Size(23, 21); this.buttonNextPage.TabIndex = 11; // // VideoPagingControl // this.Controls.Add(this.labelQueryStatus); this.Controls.Add(this.buttonPreviousPage); this.Controls.Add(this.buttonNextPage); this.Name = "VideoPagingControl"; this.Size = new System.Drawing.Size(250, 20); this.ResumeLayout(false); } void IRtlAware.Layout() { } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole // // 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.Collections; using NUnit.Framework.Constraints; using System; namespace NUnit.Framework { public partial class Assert { #region True /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void True(bool? condition, string message, params object[] args) { Assert.That(condition, Is.True ,message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void True(bool condition, string message, params object[] args) { Assert.That(condition, Is.True, message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void True(bool? condition) { Assert.That(condition, Is.True ,null, null); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void True(bool condition) { Assert.That(condition, Is.True ,null, null); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsTrue(bool? condition, string message, params object[] args) { Assert.That(condition, Is.True ,message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsTrue(bool condition, string message, params object[] args) { Assert.That(condition, Is.True ,message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void IsTrue(bool? condition) { Assert.That(condition, Is.True ,null, null); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void IsTrue(bool condition) { Assert.That(condition, Is.True ,null, null); } #endregion #region False /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void False(bool? condition, string message, params object[] args) { Assert.That(condition, Is.False ,message, args); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void False(bool condition, string message, params object[] args) { Assert.That(condition, Is.False ,message, args); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void False(bool? condition) { Assert.That(condition, Is.False ,null, null); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void False(bool condition) { Assert.That(condition, Is.False ,null, null); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsFalse(bool? condition, string message, params object[] args) { Assert.That(condition, Is.False ,message, args); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsFalse(bool condition, string message, params object[] args) { Assert.That(condition, Is.False ,message, args); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void IsFalse(bool? condition) { Assert.That(condition, Is.False ,null, null); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void IsFalse(bool condition) { Assert.That(condition, Is.False ,null, null); } #endregion #region NotNull /// <summary> /// Verifies that the object that is passed in is not equal to <code>null</code> /// If the object is <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void NotNull(object anObject, string message, params object[] args) { Assert.That(anObject, Is.Not.Null ,message, args); } /// <summary> /// Verifies that the object that is passed in is not equal to <code>null</code> /// If the object is <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> public static void NotNull(object anObject) { Assert.That(anObject, Is.Not.Null ,null, null); } /// <summary> /// Verifies that the object that is passed in is not equal to <code>null</code> /// If the object is <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsNotNull(object anObject, string message, params object[] args) { Assert.That(anObject, Is.Not.Null ,message, args); } /// <summary> /// Verifies that the object that is passed in is not equal to <code>null</code> /// If the object is <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> public static void IsNotNull(object anObject) { Assert.That(anObject, Is.Not.Null ,null, null); } #endregion #region Null /// <summary> /// Verifies that the object that is passed in is equal to <code>null</code> /// If the object is not <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Null(object anObject, string message, params object[] args) { Assert.That(anObject, Is.Null ,message, args); } /// <summary> /// Verifies that the object that is passed in is equal to <code>null</code> /// If the object is not <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> public static void Null(object anObject) { Assert.That(anObject, Is.Null ,null, null); } /// <summary> /// Verifies that the object that is passed in is equal to <code>null</code> /// If the object is not <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsNull(object anObject, string message, params object[] args) { Assert.That(anObject, Is.Null ,message, args); } /// <summary> /// Verifies that the object that is passed in is equal to <code>null</code> /// If the object is not <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> public static void IsNull(object anObject) { Assert.That(anObject, Is.Null ,null, null); } #endregion #region IsNaN /// <summary> /// Verifies that the double that is passed in is an <code>NaN</code> value. /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="aDouble">The value that is to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsNaN(double aDouble, string message, params object[] args) { Assert.That(aDouble, Is.NaN ,message, args); } /// <summary> /// Verifies that the double that is passed in is an <code>NaN</code> value. /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="aDouble">The value that is to be tested</param> public static void IsNaN(double aDouble) { Assert.That(aDouble, Is.NaN ,null, null); } /// <summary> /// Verifies that the double that is passed in is an <code>NaN</code> value. /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="aDouble">The value that is to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsNaN(double? aDouble, string message, params object[] args) { Assert.That(aDouble, Is.NaN ,message, args); } /// <summary> /// Verifies that the double that is passed in is an <code>NaN</code> value. /// If the object is not <code>NaN</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="aDouble">The value that is to be tested</param> public static void IsNaN(double? aDouble) { Assert.That(aDouble, Is.NaN ,null, null); } #endregion #region IsEmpty #region String /// <summary> /// Assert that a string is empty - that is equal to string.Empty /// </summary> /// <param name="aString">The string to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsEmpty(string aString, string message, params object[] args) { Assert.That(aString, new EmptyStringConstraint() ,message, args); } /// <summary> /// Assert that a string is empty - that is equal to string.Empty /// </summary> /// <param name="aString">The string to be tested</param> public static void IsEmpty(string aString) { Assert.That(aString, new EmptyStringConstraint() ,null, null); } #endregion #region Collection /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing ICollection</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new EmptyCollectionConstraint() ,message, args); } /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing ICollection</param> public static void IsEmpty(IEnumerable collection) { Assert.That(collection, new EmptyCollectionConstraint() ,null, null); } #endregion #endregion #region IsNotEmpty #region String /// <summary> /// Assert that a string is not empty - that is not equal to string.Empty /// </summary> /// <param name="aString">The string to be tested</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsNotEmpty(string aString, string message, params object[] args) { Assert.That(aString, Is.Not.Empty ,message, args); } /// <summary> /// Assert that a string is not empty - that is not equal to string.Empty /// </summary> /// <param name="aString">The string to be tested</param> public static void IsNotEmpty(string aString) { Assert.That(aString, Is.Not.Empty ,null, null); } #endregion #region Collection /// <summary> /// Assert that an array, list or other collection is not empty /// </summary> /// <param name="collection">An array, list or other collection implementing ICollection</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void IsNotEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.Not.Empty ,message, args); } /// <summary> /// Assert that an array, list or other collection is not empty /// </summary> /// <param name="collection">An array, list or other collection implementing ICollection</param> public static void IsNotEmpty(IEnumerable collection) { Assert.That(collection, Is.Not.Empty ,null, null); } #endregion #endregion #region Zero #region Ints /// <summary> /// Asserts that an int is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void Zero(int actual) { Assert.That(actual, Is.Zero); } /// <summary> /// Asserts that an int is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Zero(int actual, string message, params object[] args) { Assert.That(actual, Is.Zero, message, args); } #endregion #region UnsignedInts /// <summary> /// Asserts that an unsigned int is zero. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void Zero(uint actual) { Assert.That(actual, Is.Zero); } /// <summary> /// Asserts that an unsigned int is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void Zero(uint actual, string message, params object[] args) { Assert.That(actual, Is.Zero, message, args); } #endregion #region Longs /// <summary> /// Asserts that a Long is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void Zero(long actual) { Assert.That(actual, Is.Zero); } /// <summary> /// Asserts that a Long is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Zero(long actual, string message, params object[] args) { Assert.That(actual, Is.Zero, message, args); } #endregion #region UnsignedLongs /// <summary> /// Asserts that an unsigned Long is zero. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void Zero(ulong actual) { Assert.That(actual, Is.Zero); } /// <summary> /// Asserts that an unsigned Long is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void Zero(ulong actual, string message, params object[] args) { Assert.That(actual, Is.Zero, message, args); } #endregion #region Decimals /// <summary> /// Asserts that a decimal is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void Zero(decimal actual) { Assert.That(actual, Is.Zero); } /// <summary> /// Asserts that a decimal is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Zero(decimal actual, string message, params object[] args) { Assert.That(actual, Is.Zero, message, args); } #endregion #region Doubles /// <summary> /// Asserts that a double is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void Zero(double actual) { Assert.That(actual, Is.Zero); } /// <summary> /// Asserts that a double is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Zero(double actual, string message, params object[] args) { Assert.That(actual, Is.Zero, message, args); } #endregion #region Floats /// <summary> /// Asserts that a float is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void Zero(float actual) { Assert.That(actual, Is.Zero); } /// <summary> /// Asserts that a float is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Zero(float actual, string message, params object[] args) { Assert.That(actual, Is.Zero, message, args); } #endregion #endregion #region NotZero #region Ints /// <summary> /// Asserts that an int is not zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void NotZero(int actual) { Assert.That(actual, Is.Not.Zero); } /// <summary> /// Asserts that an int is not zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void NotZero(int actual, string message, params object[] args) { Assert.That(actual, Is.Not.Zero, message, args); } #endregion #region UnsignedInts /// <summary> /// Asserts that an unsigned int is not zero. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void NotZero(uint actual) { Assert.That(actual, Is.Not.Zero); } /// <summary> /// Asserts that an unsigned int is not zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void NotZero(uint actual, string message, params object[] args) { Assert.That(actual, Is.Not.Zero, message, args); } #endregion #region Longs /// <summary> /// Asserts that a Long is not zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void NotZero(long actual) { Assert.That(actual, Is.Not.Zero); } /// <summary> /// Asserts that a Long is not zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void NotZero(long actual, string message, params object[] args) { Assert.That(actual, Is.Not.Zero, message, args); } #endregion #region UnsignedLongs /// <summary> /// Asserts that an unsigned Long is not zero. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void NotZero(ulong actual) { Assert.That(actual, Is.Not.Zero); } /// <summary> /// Asserts that an unsigned Long is not zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void NotZero(ulong actual, string message, params object[] args) { Assert.That(actual, Is.Not.Zero, message, args); } #endregion #region Decimals /// <summary> /// Asserts that a decimal is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void NotZero(decimal actual) { Assert.That(actual, Is.Not.Zero); } /// <summary> /// Asserts that a decimal is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void NotZero(decimal actual, string message, params object[] args) { Assert.That(actual, Is.Not.Zero, message, args); } #endregion #region Doubles /// <summary> /// Asserts that a double is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void NotZero(double actual) { Assert.That(actual, Is.Not.Zero); } /// <summary> /// Asserts that a double is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void NotZero(double actual, string message, params object[] args) { Assert.That(actual, Is.Not.Zero, message, args); } #endregion #region Floats /// <summary> /// Asserts that a float is zero. /// </summary> /// <param name="actual">The number to be examined</param> public static void NotZero(float actual) { Assert.That(actual, Is.Not.Zero); } /// <summary> /// Asserts that a float is zero. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void NotZero(float actual, string message, params object[] args) { Assert.That(actual, Is.Not.Zero, message, args); } #endregion #endregion #region Positive #region Ints /// <summary> /// Asserts that an int is positive. /// </summary> /// <param name="actual">The number to be examined</param> public static void Positive(int actual) { Assert.That(actual, Is.Positive); } /// <summary> /// Asserts that an int is positive. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Positive(int actual, string message, params object[] args) { Assert.That(actual, Is.Positive, message, args); } #endregion #region UnsignedInts /// <summary> /// Asserts that an unsigned int is positive. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void Positive(uint actual) { Assert.That(actual, Is.Positive); } /// <summary> /// Asserts that an unsigned int is positive. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void Positive(uint actual, string message, params object[] args) { Assert.That(actual, Is.Positive, message, args); } #endregion #region Longs /// <summary> /// Asserts that a Long is positive. /// </summary> /// <param name="actual">The number to be examined</param> public static void Positive(long actual) { Assert.That(actual, Is.Positive); } /// <summary> /// Asserts that a Long is positive. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Positive(long actual, string message, params object[] args) { Assert.That(actual, Is.Positive, message, args); } #endregion #region UnsignedLongs /// <summary> /// Asserts that an unsigned Long is positive. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void Positive(ulong actual) { Assert.That(actual, Is.Positive); } /// <summary> /// Asserts that an unsigned Long is positive. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void Positive(ulong actual, string message, params object[] args) { Assert.That(actual, Is.Positive, message, args); } #endregion #region Decimals /// <summary> /// Asserts that a decimal is positive. /// </summary> /// <param name="actual">The number to be examined</param> public static void Positive(decimal actual) { Assert.That(actual, Is.Positive); } /// <summary> /// Asserts that a decimal is positive. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Positive(decimal actual, string message, params object[] args) { Assert.That(actual, Is.Positive, message, args); } #endregion #region Doubles /// <summary> /// Asserts that a double is positive. /// </summary> /// <param name="actual">The number to be examined</param> public static void Positive(double actual) { Assert.That(actual, Is.Positive); } /// <summary> /// Asserts that a double is positive. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Positive(double actual, string message, params object[] args) { Assert.That(actual, Is.Positive, message, args); } #endregion #region Floats /// <summary> /// Asserts that a float is positive. /// </summary> /// <param name="actual">The number to be examined</param> public static void Positive(float actual) { Assert.That(actual, Is.Positive); } /// <summary> /// Asserts that a float is positive. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Positive(float actual, string message, params object[] args) { Assert.That(actual, Is.Positive, message, args); } #endregion #endregion #region Negative #region Ints /// <summary> /// Asserts that an int is negative. /// </summary> /// <param name="actual">The number to be examined</param> public static void Negative(int actual) { Assert.That(actual, Is.Negative); } /// <summary> /// Asserts that an int is negative. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Negative(int actual, string message, params object[] args) { Assert.That(actual, Is.Negative, message, args); } #endregion #region UnsignedInts /// <summary> /// Asserts that an unsigned int is negative. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void Negative(uint actual) { Assert.That(actual, Is.Negative); } /// <summary> /// Asserts that an unsigned int is negative. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void Negative(uint actual, string message, params object[] args) { Assert.That(actual, Is.Negative, message, args); } #endregion #region Longs /// <summary> /// Asserts that a Long is negative. /// </summary> /// <param name="actual">The number to be examined</param> public static void Negative(long actual) { Assert.That(actual, Is.Negative); } /// <summary> /// Asserts that a Long is negative. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Negative(long actual, string message, params object[] args) { Assert.That(actual, Is.Negative, message, args); } #endregion #region UnsignedLongs /// <summary> /// Asserts that an unsigned Long is negative. /// </summary> /// <param name="actual">The number to be examined</param> [CLSCompliant(false)] public static void Negative(ulong actual) { Assert.That(actual, Is.Negative); } /// <summary> /// Asserts that an unsigned Long is negative. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> [CLSCompliant(false)] public static void Negative(ulong actual, string message, params object[] args) { Assert.That(actual, Is.Negative, message, args); } #endregion #region Decimals /// <summary> /// Asserts that a decimal is negative. /// </summary> /// <param name="actual">The number to be examined</param> public static void Negative(decimal actual) { Assert.That(actual, Is.Negative); } /// <summary> /// Asserts that a decimal is negative. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Negative(decimal actual, string message, params object[] args) { Assert.That(actual, Is.Negative, message, args); } #endregion #region Doubles /// <summary> /// Asserts that a double is negative. /// </summary> /// <param name="actual">The number to be examined</param> public static void Negative(double actual) { Assert.That(actual, Is.Negative); } /// <summary> /// Asserts that a double is negative. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Negative(double actual, string message, params object[] args) { Assert.That(actual, Is.Negative, message, args); } #endregion #region Floats /// <summary> /// Asserts that a float is negative. /// </summary> /// <param name="actual">The number to be examined</param> public static void Negative(float actual) { Assert.That(actual, Is.Negative); } /// <summary> /// Asserts that a float is negative. /// </summary> /// <param name="actual">The number to be examined</param> /// <param name="message">The message to display in case of failure</param> /// <param name="args">Array of objects to be used in formatting the message</param> public static void Negative(float actual, string message, params object[] args) { Assert.That(actual, Is.Negative, message, args); } #endregion #endregion } }
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 ServerSideFinalProject.Areas.HelpPage.ModelDescriptions; using ServerSideFinalProject.Areas.HelpPage.Models; namespace ServerSideFinalProject.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.Generic; using System.Diagnostics; using System.DirectoryServices; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using PoshSec.Framework.Interface; using PoshSec.Framework.Strings; namespace PoshSec.Framework { internal class NetworkBrowser { private readonly Network _network; private static string _arp; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); //public bool CancelScan { get; set; } public event EventHandler<NetworkScanCompleteEventArgs> NetworkScanComplete; public event EventHandler<EventArgs> NetworkScanCancelled; public event EventHandler<ScanStatusEventArgs> ScanStatusUpdate; public NetworkBrowser(Network network) { _network = network; } private async Task ScanActiveDirectoryAsync() { var hostPc = new DirectoryEntry { Path = "LDAP://" + _network.Name }; SearchResultCollection searchResults = null; void SearchDirectory() { using (var directorySearcher = new DirectorySearcher(hostPc)) { directorySearcher.Filter = "(&(objectClass=computer))"; directorySearcher.SearchScope = SearchScope.Subtree; directorySearcher.PropertiesToLoad.Add("description"); try { searchResults = directorySearcher.FindAll(); } catch (Exception e) { MessageBox.Show(e.Message); } } } void HandleResults(Task t) { if (searchResults != null && searchResults.Count > 0) { var hostcnt = 0; foreach (SearchResult result in searchResults) { hostcnt++; var directoryEntry = result.GetDirectoryEntry(); var scnmsg = "Scanning " + directoryEntry.Name.Replace("CN=", "") + ", please wait..."; OnStatusUpdate(new ScanStatusEventArgs(scnmsg, hostcnt, searchResults.Count)); Application.DoEvents(); if (directoryEntry.Name.Replace("CN=", "") != "Schema" && directoryEntry.SchemaClassName == "computer") { Ping(directoryEntry.Name.Replace("CN=", ""), 1, 100); _network.Nodes.AddRange(GetSystems(directoryEntry)); } } } } var task = Task.Factory .StartNew(SearchDirectory, TaskCreationOptions.LongRunning) .ContinueWith(HandleResults); await task; BuildArpTable(); OnNetworkScanComplete(new NetworkScanCompleteEventArgs(_network)); } private IEnumerable<NetworkNode> GetSystems(DirectoryEntry directoryEntry) { var nodes = new List<NetworkNode>(); var ipAddresses = GetIPAddresses(directoryEntry.Name.Replace("CN=", "")); foreach (var ip in ipAddresses) { OnStatusUpdate(new ScanStatusEventArgs("Adding " + directoryEntry.Name.Replace("CN=", "") + ", please wait...", 0, 255)); var macaddr = GetMac(ip); var isup = macaddr != StringValue.BlankMAC; var node = new NetworkNode { Name = directoryEntry.Name.Replace("CN=", ""), IpAddress = ip, MacAddress = macaddr, Description = (string)directoryEntry.Properties["description"].Value ?? "", Status = isup ? StringValue.Up : StringValue.Down, ClientInstalled = StringValue.NotInstalled, Alerts = 0, LastScanned = DateTime.Now }; nodes.Add(node); } return nodes; } private async Task ScanLocalNetworkAsync() { var localIPs = GetIPAddresses(Dns.GetHostName()).ToArray(); var localIP = localIPs.First(); if (localIPs.Length > 1) localIP = PromptUserToSelectIP(localIPs); if (localIP == null) { OnScanCancelled(new EventArgs()); return; } OnStatusUpdate(new ScanStatusEventArgs("", 0, 255)); _arp = BuildArpTable(); var tasks = new List<Task>(); var maxThread = new SemaphoreSlim(20); var localIpBytes = localIP.GetAddressBytes(); for (byte b = 1; b < 255; b++) { maxThread.Wait(_cancellationTokenSource.Token); var scanIp = new IPAddress(new[] { localIpBytes[0], localIpBytes[1], localIpBytes[2], b }); var b2 = b; var task = Task.Factory.StartNew(() => { OnStatusUpdate(new ScanStatusEventArgs("Scanning " + scanIp + ", please wait...", b2, 255)); var networkNode = Scan(scanIp); if (networkNode.Status == StringValue.Up) _network.Nodes.Add(networkNode); }, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default) .ContinueWith(t => maxThread.Release()); tasks.Add(task); Application.DoEvents(); if (_cancellationTokenSource.IsCancellationRequested) break; } OnStatusUpdate(new ScanStatusEventArgs(StringValue.WaitingForHostResp, 255, 255)); await Task.WhenAll(tasks).ContinueWith(t => { OnStatusUpdate(new ScanStatusEventArgs(StringValue.Ready, 0, 255)); OnNetworkScanComplete(new NetworkScanCompleteEventArgs(_network)); }); } private static IPAddress PromptUserToSelectIP(IEnumerable<IPAddress> ipAddresses) { using (var frm = new frmScan { IPs = ipAddresses.Select(ip => ip.ToString()).ToArray(), StartPosition = FormStartPosition.CenterScreen }) { return frm.ShowDialog() == DialogResult.OK ? IPAddress.Parse(frm.SelectedIP) : null; } } public async Task ScanAsync() { if (_network == null) return; _network.Nodes.Clear(); ClearArpTable(); switch (_network) { case LocalNetwork _: await ScanLocalNetworkAsync(); break; case DomainNetwork _: await ScanActiveDirectoryAsync(); break; } } private static NetworkNode Scan(IPAddress ipAddress) { var host = StringValue.NAHost; var isup = false; var ipaddr = ipAddress.ToString(); if (ipaddr != "") { if (Ping(ipaddr, 1, 100)) { isup = true; host = GetHostname(ipAddress); } } var networkNode = new NetworkNode { IpAddress = ipAddress, Name = host, MacAddress = GetMac(ipAddress), Status = isup ? StringValue.Up : StringValue.Down, LastScanned = DateTime.Now }; return networkNode; } public static bool Ping(string host, int attempts, int timeout) { var response = false; try { var ping = new Ping(); for (var attempt = 0; attempt < attempts; attempt++) try { var pingReply = ping.Send(host, timeout); if (pingReply?.Status == IPStatus.Success) response = true; } catch (Exception ex) { response = false; } } catch (Exception e) { MessageBox.Show(e.Message); } return response; } public static IEnumerable<IPAddress> GetIPAddresses(string host) { var addressList = new List<IPAddress>(); try { var ipentry = Dns.GetHostEntry(host.Replace("CN=", "")); var addrs = ipentry.AddressList; addressList.AddRange(addrs.Where(addr => addr.AddressFamily == AddressFamily.InterNetwork)); } catch (Exception ex) { addressList.Add(IPAddress.Any); } return addressList; } public static string GetMac(IPAddress ipAddress) { var rtn = ""; if (!string.IsNullOrEmpty(_arp)) { string ip = ipAddress.ToString(); var ipidx = _arp.IndexOf(ip + " ", 0); if (ipidx > -1) { var mac = _arp.Substring(ipidx, 39).Replace(ip, "").Trim(); if (mac.Contains("---")) mac = GetMyMac(ipAddress); rtn += mac + ","; } else { rtn += GetMyMac(ipAddress); } if (rtn.EndsWith(",")) rtn = rtn.Substring(0, rtn.Length - 1); } if (rtn == "") rtn = StringValue.BlankMAC; return rtn; } public static string GetMyMac(IPAddress ipAddress) { var mac = StringValue.BlankMAC; try { var psi = new ProcessStartInfo("ipconfig") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, Arguments = "/all" }; var prc = new Process { StartInfo = psi }; prc.Start(); var ipconfig = prc.StandardOutput.ReadToEnd(); prc.WaitForExit(); if (!string.IsNullOrEmpty(ipconfig)) { var ipaddr = ipAddress.ToString(); var ipidx = ipconfig.IndexOf(ipaddr, 0, StringComparison.Ordinal); if (ipidx > -1) { var paidx = ipconfig.ToLower().LastIndexOf("physical address", ipidx, StringComparison.Ordinal); if (paidx > -1) mac = ipconfig.Substring(paidx, 53).Replace("Physical Address. . . . . . . . . : ", ""); } } } catch (Exception) { mac = StringValue.BlankMAC; } return mac; } private static string GetHostname(IPAddress ipAddress) { try { var ipentry = Dns.GetHostEntry(ipAddress); return ipentry.HostName; } catch { return StringValue.NAHost; } } private static void ClearArpTable() { try { var psi = new ProcessStartInfo("arp") { UseShellExecute = false, CreateNoWindow = true, Arguments = "-d" }; var prc = new Process { StartInfo = psi }; prc.Start(); prc.WaitForExit(); } catch (Exception) { //do nothing } } private static string BuildArpTable() { try { var psi = new ProcessStartInfo("arp") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, Arguments = "-a" }; var prc = new Process { StartInfo = psi }; prc.Start(); var arp = prc.StandardOutput.ReadToEnd(); prc.WaitForExit(); return arp; } catch (Exception) { //do nothing } return null; } private void OnStatusUpdate(ScanStatusEventArgs e) { Trace.TraceInformation(e.Status); var handler = ScanStatusUpdate; handler?.Invoke(this, e); } private void OnNetworkScanComplete(NetworkScanCompleteEventArgs e) { Trace.TraceInformation($"Scan of {e.Network.Name} complete."); var handler = NetworkScanComplete; handler?.Invoke(this, e); } private void OnScanCancelled(EventArgs e) { var handler = NetworkScanCancelled; handler?.Invoke(this, e); } public void CancelScan() { _cancellationTokenSource.Cancel(); } } }
//----------------------------------------------------------------------- // <copyright file="InterpreterSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Text.RegularExpressions; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using Akka.Streams.Supervision; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; using OnNext = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.OnNext; using Cancel = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.Cancel; using OnError = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.OnError; using OnComplete = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.OnComplete; using RequestOne = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.RequestOne; namespace Akka.Streams.Tests.Implementation.Fusing { public class InterpreterSpec : GraphInterpreterSpecKit { /* * These tests were written for the previous version of the interpreter, the so called OneBoundedInterpreter. * These stages are now properly emulated by the GraphInterpreter and many of the edge cases were relevant to * the execution model of the old one. Still, these tests are very valuable, so please do not remove. */ public InterpreterSpec(ITestOutputHelper output = null) : base(output) { } private static readonly Take<int> TakeOne = new Take<int>(1); private static readonly Take<int> TakeTwo = new Take<int>(2); [Fact] public void Interpreter_should_implement_map_correctly() { WithOneBoundedSetup(new Select<int, int>(x => x + 1), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(2)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_implement_chain_of_maps_correctly() { WithOneBoundedSetup(new[] { new Select<int, int>(x => x + 1), new Select<int, int>(x => x * 2), new Select<int, int>(x => x + 1) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(3)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(5)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_only_boundary_ops() { WithOneBoundedSetup(new IStage<int, int>[0], (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(0)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_implement_one_to_many_many_to_one_chain_correctly() { WithOneBoundedSetup(new IGraphStageWithMaterializedValue<FlowShape<int, int>, object>[] { new Doubler<int>(), new Where<int>(x => x != 0) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_implement_many_to_one_one_to_many_chain_correctly() { WithOneBoundedSetup(new IGraphStageWithMaterializedValue<FlowShape<int, int>, object>[] { new Where<int>(x => x != 0), new Doubler<int>() }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_implement_take() { WithOneBoundedSetup(TakeTwo, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new Cancel(), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_take_inside_a_chain() { WithOneBoundedSetup<int, int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Where<int>(x => x != 0), TakeTwo, new Select<int, int>(x => x + 1) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(2)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(3), new Cancel(), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_fold() { WithOneBoundedSetup(new Aggregate<int, int>(0, (agg, x) => agg + x), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnNext(3), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_fold_with_proper_cancel() { WithOneBoundedSetup(new Aggregate<int, int>(0, (agg, x) => agg + x), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_work_if_fold_completes_while_not_in_a_push_position() { WithOneBoundedSetup(new Aggregate<int, int>(0, (agg, x) => agg + x), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); upstream.OnComplete(); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_grouped() { WithOneBoundedSetup(new Grouped<int>(3), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(new[] { 0, 1, 2 })); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(3); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnNext(new[] { 3 }), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_batch_conflate() { WithOneBoundedSetup<int>(new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(0), new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(3)); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(4); lastEvents().Should().BeEquivalentTo(new OnNext(4), new RequestOne()); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_implement_expand() { WithOneBoundedSetup<int>(new Expand<int, int>(e => Enumerable.Repeat(e, int.MaxValue).GetEnumerator()), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0)); upstream.OnNext(1); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_batch_batch_conflate_conflate() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x), new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(0)); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(3)); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(4); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(4)); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_work_with_expand_expand() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Expand<int, int>(e => Enumerable.Range(e, 100).GetEnumerator()), new Expand<int, int>(e => Enumerable.Range(e, 100).GetEnumerator()) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); upstream.OnNext(10); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2), new RequestOne()); // one element is still in the pipeline downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(10)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(11)); upstream.OnComplete(); downstream.RequestOne(); // This is correct! If you don't believe, run the interpreter with Debug on lastEvents().Should().BeEquivalentTo(new OnNext(12), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_batch_expand_conflate_expand() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x), new Expand<int, int>(e => Enumerable.Repeat(e, int.MaxValue).GetEnumerator()) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2)); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_implement_doubler_batch_doubler_conflate() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Doubler<int>(), new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(6)); }); } // Note, the new interpreter has no jumpback table, still did not want to remove the test [Fact] public void Interpreter_should_work_with_jumpback_table_and_completed_elements() { WithOneBoundedSetup(new IGraphStageWithMaterializedValue<FlowShape<int, int>, object>[] { new Select<int, int>(x => x), new Select<int, int>(x => x), new KeepGoing<int>(), new Select<int, int>(x => x), new Select<int, int>(x => x) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(2)); upstream.OnComplete(); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2)); }); } [Fact] public void Interpreter_should_work_with_PushAndFinish_if_upstream_completes_with_PushAndFinish() { WithOneBoundedSetup(new PushFinishStage<int>(), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_PushAndFinish_if_indirect_upstream_completes_with_PushAndFinish() { WithOneBoundedSetup(new IGraphStageWithMaterializedValue<FlowShape<int, int>, object>[] { new Select<int, int>(x => x), new PushFinishStage<int>(), new Select<int, int>(x => x) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_PushAndFinish_if_upstream_completes_with_PushAndFinish_and_downstream_immediately_pulls() { WithOneBoundedSetup(new IGraphStageWithMaterializedValue<FlowShape<int, int>, object>[] { new PushFinishStage<int>(), new Aggregate<int, int>(0, (x, y) => x + y) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_report_error_if_pull_is_called_while_op_is_terminating() { WithOneBoundedSetup(new PullWhileOpIsTerminating<int>(), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); EventFilter.Exception<ArgumentException>(new Regex(".*Cannot pull a closed port.*")) .ExpectOne(upstream.OnComplete); var ev = lastEvents(); ev.Should().NotBeEmpty(); ev.Where(e => !((e as OnError)?.Cause is ArgumentException)).Should().BeEmpty(); }); } [Fact] public void Interpreter_should_implement_take_take() { WithOneBoundedSetup(new[] { TakeOne, TakeOne }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new Cancel(), new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_take_take_with_PushAndFinish_from_upstream() { WithOneBoundedSetup(new[] { TakeOne, TakeOne }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_not_allow_AbsorbTermination_from_OnDownstreamFinish() { // This test must be kept since it tests the compatibility layer, which while is deprecated it is still here. WithOneBoundedSetup(ToGraphStage(new InvalidAbsorbTermination<int>()), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); EventFilter.Exception<NotSupportedException>( "It is not allowed to call AbsorbTermination() from OnDownstreamFinish.") .ExpectOne(() => { downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); }); } public class Doubler<T> : SimpleLinearGraphStage<T> { #region Logic private sealed class Logic : GraphStageLogic { private T _latest; private bool _oneMore; public Logic(Doubler<T> stage) : base(stage.Shape) { // Called when the output port has received a pull, and therefore ready to emit an element, i.e. GraphStageLogic.Push() // is now allowed to be called on this port. SetHandler(stage.Shape.Outlet, onPull: () => { if (_oneMore) { Push(stage.Shape.Outlet, _latest); _oneMore = false; } else Pull(stage.Shape.Inlet); }); SetHandler(stage.Shape.Inlet, onPush: () => { _latest = Grab(stage.Shape.Inlet); _oneMore = true; Push(stage.Shape.Outlet, _latest); }); } } #endregion protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } public class KeepGoing<T> : SimpleLinearGraphStage<T> { #region Logic private sealed class Logic : GraphStageLogic { private T _lastElement; public Logic(KeepGoing<T> stage) : base(stage.Shape) { // Called when the output port has received a pull, and therefore ready to emit an element, i.e. GraphStageLogic.Push() // is now allowed to be called on this port. SetHandler(stage.Shape.Outlet, onPull: () => { if (IsClosed(stage.Shape.Inlet)) Push(stage.Shape.Outlet, _lastElement); else Pull(stage.Shape.Inlet); }); SetHandler(stage.Shape.Inlet, onPush: () => { _lastElement = Grab(stage.Shape.Inlet); Push(stage.Shape.Outlet, _lastElement); }, onUpstreamFinish: () => { }); } } #endregion protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } public class PushFinishStage<T> : SimpleLinearGraphStage<T> { private sealed class Logic : GraphStageLogic { private readonly PushFinishStage<T> _stage; public Logic(PushFinishStage<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, onPull: () => Pull(stage.Inlet)); SetHandler(stage.Inlet, onPush: () => { Push(stage.Outlet, Grab(stage.Inlet)); CompleteStage(); }, onUpstreamFinish: () => FailStage(new TestException("Cannot happen"))); } public override void PostStop() => _stage._onPostStop(); } private readonly Action _onPostStop; public PushFinishStage(Action onPostStop = null) { _onPostStop = onPostStop ?? (() => { }); } protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } public class PullWhileOpIsTerminating<T> : SimpleLinearGraphStage<T> { private sealed class Logic : GraphStageLogic { public Logic(PullWhileOpIsTerminating<T> stage) : base(stage.Shape) { SetHandler(stage.Outlet, onPull: () => Pull(stage.Inlet)); SetHandler(stage.Inlet, onPush: () => Pull(stage.Inlet), onUpstreamFinish: () => { if (!HasBeenPulled(stage.Inlet)) Pull(stage.Inlet); }); } } protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } [Obsolete("Please use GraphStage instead.")] public class InvalidAbsorbTermination<T> : PushPullStage<T, T> { public override ISyncDirective OnPush(T element, IContext<T> context) { return context.Push(element); } public override ISyncDirective OnPull(IContext<T> context) { return context.Pull(); } public override ITerminationDirective OnDownstreamFinish(IContext<T> context) { return context.AbsorbTermination(); } } } }
#region copyright // VZF // Copyright (C) 2014-2016 Vladimir Zakharov // // http://www.code.coolhobby.ru/ // File VzfMySqlMembershipProvider.cs created on 2.6.2015 in 6:31 AM. // Last changed on 5.21.2016 in 1:12 PM. // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion using System.Web; namespace YAF.Providers.Membership { using System; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web.Security; using YAF.Classes; using YAF.Core; using YAF.Types.Interfaces; using YAF.Types.Constants; using VZF.Utils; using YAF.Providers.Utils; using VZF.Data.DAL; /// <summary> /// The yaf membership provider. /// </summary> public class VzfMySqlMembershipProvider : MembershipProvider { #region Constants and Fields /// <summary> /// The conn str app key name. /// </summary> public static string ConnStrAppKeyName = "YafMembershipConnectionString"; private static string _connectionString; /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnectionString { get { return _connectionString; } set { _connectionString = value; } } /// <summary> /// The _passwordsize. /// </summary> private const int _passwordsize = 14; // Instance Variables /// <summary> /// The _app name. /// </summary> private string _appName; /// <summary> /// The _conn str name. /// </summary> private string _connStrName; /// <summary> /// The _enable password reset. /// </summary> private bool _enablePasswordReset; /// <summary> /// The _enable password retrieval. /// </summary> private bool _enablePasswordRetrieval; /// <summary> /// The _hash case. /// </summary> private string _hashCase; /// <summary> /// The _hash hex. /// </summary> private bool _hashHex; /// <summary> /// The _hash remove chars. /// </summary> private string _hashRemoveChars; /// <summary> /// The _max invalid password attempts. /// </summary> private int _maxInvalidPasswordAttempts; /// <summary> /// The _minimum required password length. /// </summary> private int _minimumRequiredPasswordLength; /// <summary> /// The _min required non alphanumeric characters. /// </summary> private int _minRequiredNonAlphanumericCharacters; /// <summary> /// The _ms compliant. /// </summary> private bool _msCompliant; /// <summary> /// The _password attempt window. /// </summary> private int _passwordAttemptWindow; /// <summary> /// The _password format. /// </summary> private MembershipPasswordFormat _passwordFormat; /// <summary> /// The _password strength regular expression. /// </summary> private string _passwordStrengthRegularExpression; /// <summary> /// The _requires question and answer. /// </summary> private bool _requiresQuestionAndAnswer; /// <summary> /// The _requires unique email. /// </summary> private bool _requiresUniqueEmail; /// <summary> /// The _use salt. /// </summary> private bool _useSalt; #endregion #region Properties /// <summary> /// Gets or sets ApplicationName. /// </summary> public override string ApplicationName { get { return this._appName; } set { if (value != this._appName) { this._appName = value; } } } /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnectionStringName { get; set; } /// <summary> /// Gets or sets provider Description. /// </summary> public override string Description { get { return "YAF Native Membership Provider"; } } /// <summary> /// Gets a value indicating whether EnablePasswordReset. /// </summary> public override bool EnablePasswordReset { get { return this._enablePasswordReset; } } /// <summary> /// Gets a value indicating whether EnablePasswordRetrieval. /// </summary> public override bool EnablePasswordRetrieval { get { return this._enablePasswordRetrieval; } } /// <summary> /// Gets MaxInvalidPasswordAttempts. /// </summary> public override int MaxInvalidPasswordAttempts { get { return this._maxInvalidPasswordAttempts; } } /// <summary> /// Gets MinRequiredNonAlphanumericCharacters. /// </summary> public override int MinRequiredNonAlphanumericCharacters { get { return this._minRequiredNonAlphanumericCharacters; } } /// <summary> /// Gets MinRequiredPasswordLength. /// </summary> public override int MinRequiredPasswordLength { get { return this._minimumRequiredPasswordLength; } } /// <summary> /// Gets PasswordAttemptWindow. /// </summary> public override int PasswordAttemptWindow { get { return this._passwordAttemptWindow; } } /// <summary> /// Gets PasswordFormat. /// </summary> public override MembershipPasswordFormat PasswordFormat { get { return this._passwordFormat; } } /// <summary> /// Gets PasswordStrengthRegularExpression. /// </summary> public override string PasswordStrengthRegularExpression { get { return this._passwordStrengthRegularExpression; } } /// <summary> /// Gets a value indicating whether RequiresQuestionAndAnswer. /// </summary> public override bool RequiresQuestionAndAnswer { get { return this._requiresQuestionAndAnswer; } } /// <summary> /// Gets a value indicating whether RequiresUniqueEmail. /// </summary> public override bool RequiresUniqueEmail { get { return this._requiresUniqueEmail; } } /// <summary> /// Gets HashCase. /// </summary> internal string HashCase { get { return this._hashCase; } } /// <summary> /// Gets a value indicating whether HashHex. /// </summary> internal bool HashHex { get { return this._hashHex; } } /// <summary> /// Gets HashRemoveChars. /// </summary> internal string HashRemoveChars { get { return this._hashRemoveChars; } } /// <summary> /// Gets a value indicating whether MSCompliant. /// </summary> internal bool MSCompliant { get { return this._msCompliant; } } /// <summary> /// Gets a value indicating whether UseSalt. /// </summary> internal bool UseSalt { get { return this._useSalt; } } #endregion #region Public Methods /// <summary> /// Creates a password buffer from salt and password ready for hashing/encrypting /// </summary> /// <param name="salt"> /// Salt to be applied to hashing algorithm /// </param> /// <param name="clearString"> /// Clear string to hash /// </param> /// <param name="standardComp"> /// Use Standard asp.net membership method of creating the buffer /// </param> /// <returns> /// Salted Password as Byte Array /// </returns> public static byte[] GeneratePasswordBuffer(string salt, string clearString, bool standardComp) { byte[] unencodedBytes = Encoding.Unicode.GetBytes(clearString); byte[] saltBytes = Convert.FromBase64String(salt); var buffer = new byte[unencodedBytes.Length + saltBytes.Length]; if (standardComp) { // Compliant with ASP.NET Membership method of hash/salt Buffer.BlockCopy(saltBytes, 0, buffer, 0, saltBytes.Length); Buffer.BlockCopy(unencodedBytes, 0, buffer, saltBytes.Length, unencodedBytes.Length); } else { Buffer.BlockCopy(unencodedBytes, 0, buffer, 0, unencodedBytes.Length); Buffer.BlockCopy(saltBytes, 0, buffer, unencodedBytes.Length - 1, saltBytes.Length); } return buffer; } /// <summary> /// Hashes a clear string to the given hashtype /// </summary> /// <param name="clearString"> /// Clear string to hash /// </param> /// <param name="hashType"> /// hash Algorithm to be used /// </param> /// <param name="salt"> /// Salt to be applied to hashing algorithm /// </param> /// <param name="useSalt"> /// Should salt be applied to hashing algorithm /// </param> /// <param name="hashHex"> /// The hash Hex. /// </param> /// <param name="hashCase"> /// The hash Case. /// </param> /// <param name="hashRemoveChars"> /// The hash Remove Chars. /// </param> /// <param name="standardComp"> /// The standard Comp. /// </param> /// <returns> /// Hashed String as Hex or Base64 /// </returns> public static string Hash( string clearString, string hashType, string salt, bool useSalt, bool hashHex, string hashCase, string hashRemoveChars, bool standardComp) { byte[] buffer; if (useSalt) { buffer = GeneratePasswordBuffer(salt, clearString, standardComp); } else { byte[] unencodedBytes = Encoding.UTF8.GetBytes(clearString); // UTF8 used to maintain compatibility buffer = new byte[unencodedBytes.Length]; Buffer.BlockCopy(unencodedBytes, 0, buffer, 0, unencodedBytes.Length); } byte[] hashedBytes = Hash(buffer, hashType); // Hash string hashedString; hashedString = hashHex ? BitBoolExtensions.ToHexString(hashedBytes) : Convert.ToBase64String(hashedBytes); // Adjust the case of the hash output switch (hashCase.ToLower()) { case "upper": hashedString = hashedString.ToUpper(); break; case "lower": hashedString = hashedString.ToLower(); break; } if (hashRemoveChars.IsSet()) { hashedString = hashRemoveChars.Aggregate(hashedString, (current, removeChar) => current.Replace(removeChar.ToString(), string.Empty)); } return hashedString; } /// <summary> /// Change Users password /// </summary> /// <param name="username"> /// Username to change password for /// </param> /// <param name="oldPassword"> /// The old Password. /// </param> /// <param name="newPassword"> /// New question /// </param> /// <returns> /// Boolean depending on whether the change was successful /// </returns> public override bool ChangePassword(string username, string oldPassword, string newPassword) { string passwordSalt = string.Empty; string newEncPassword = string.Empty; // Clean input // Check password meets requirements as set by Configuration settings if (!this.IsPasswordCompliant(newPassword)) { return false; } MySqlUserPasswordInfo currentPasswordInfo = MySqlUserPasswordInfo.CreateInstanceFromDB( ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // validate the correct user information was found... if (currentPasswordInfo == null) { return false; } // validate the correct user password was entered... if (!currentPasswordInfo.IsCorrectPassword(oldPassword)) { return false; } if (this.UseSalt) { // generate a salt if one doesn't exist... passwordSalt = currentPasswordInfo.PasswordSalt.IsNotSet() ? GenerateSalt() : currentPasswordInfo.PasswordSalt; } // encode new password newEncPassword = EncodeString( newPassword, (int)this.PasswordFormat, passwordSalt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // Call SQL Password to Change MySQLDB.Current.ChangePassword(ConnectionStringName, this.ApplicationName, username, newEncPassword, passwordSalt, (int)this.PasswordFormat, currentPasswordInfo.PasswordAnswer); // Return True return true; } /// <summary> /// The change password question and answer. /// </summary> /// <param name="username"> /// The username. /// </param> /// <param name="password"> /// The password. /// </param> /// <param name="newPasswordQuestion"> /// The new password question. /// </param> /// <param name="newPasswordAnswer"> /// The new password answer. /// </param> /// <returns> /// The change password question and answer. /// </returns> /// <exception cref="ArgumentException"> /// </exception> public override bool ChangePasswordQuestionAndAnswer( string username, string password, string newPasswordQuestion, string newPasswordAnswer) { // Check arguments for null values if ((username == null) || (password == null) || (newPasswordQuestion == null) || (newPasswordAnswer == null)) { throw new ArgumentException("Username, Password, Password Question or Password Answer cannot be null"); } MySqlUserPasswordInfo currentPasswordInfo = MySqlUserPasswordInfo.CreateInstanceFromDB( ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); newPasswordAnswer = EncodeString( newPasswordAnswer, currentPasswordInfo.PasswordFormat, currentPasswordInfo.PasswordSalt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentPasswordInfo.IsCorrectPassword(password)) { try { MySQLDB.Current.ChangePasswordQuestionAndAnswer(ConnectionStringName, this.ApplicationName, username, newPasswordQuestion, newPasswordAnswer); return true; } catch { // will return false... } } return false; // Invalid password return false } /// <summary> /// Create user and add to provider /// </summary> /// <param name="username"> /// Username /// </param> /// <param name="password"> /// Password /// </param> /// <param name="email"> /// Email Address /// </param> /// <param name="passwordQuestion"> /// Password Question /// </param> /// <param name="passwordAnswer"> /// Password Answer - used for password retrievals. /// </param> /// <param name="isApproved"> /// Is the User approved? /// </param> /// <param name="providerUserKey"> /// Provider User Key to identify the User /// </param> /// <param name="status"> /// Out - MembershipCreateStatus object containing status of the Create User process /// </param> /// <returns> /// Boolean depending on whether the deletion was successful /// </returns> public override MembershipUser CreateUser( string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { // ValidatePasswordEventArgs e = new ValidatePasswordEventArgs( username, password, true ); // OnValidatingPassword( e ); // if ( e.Cancel ) // { // status = MembershipCreateStatus.InvalidPassword; // return null; // } string salt = string.Empty, pass = string.Empty; // Check password meets requirements as set out in the web.config if (!this.IsPasswordCompliant(password)) { status = MembershipCreateStatus.InvalidPassword; return null; } // Check password Question and Answer requirements. if (this.RequiresQuestionAndAnswer) { if (passwordQuestion.IsNotSet()) { status = MembershipCreateStatus.InvalidQuestion; return null; } if (passwordAnswer.IsNotSet()) { status = MembershipCreateStatus.InvalidAnswer; return null; } } // Check provider User Key if (!(providerUserKey == null)) { // IS not a duplicate key if (!(GetUser(providerUserKey, false) == null)) { status = MembershipCreateStatus.DuplicateProviderUserKey; return null; } } // Check for unique email if (this.RequiresUniqueEmail) { if (this.GetUserNameByEmail(email).IsSet()) { status = MembershipCreateStatus.DuplicateEmail; // Email exists return null; } } // Check for unique user name if (!(this.GetUser(username, false) == null)) { status = MembershipCreateStatus.DuplicateUserName; // Username exists return null; } if (this.UseSalt) { salt = GenerateSalt(); } pass = EncodeString( password, (int)this.PasswordFormat, salt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // Encode Password Answer string encodedPasswordAnswer = EncodeString( passwordAnswer, (int)this.PasswordFormat, salt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // Process database user creation request MySQLDB.Current.CreateUser(ConnectionStringName, this.ApplicationName, username, pass, salt, (int)this.PasswordFormat, email, passwordQuestion, encodedPasswordAnswer, isApproved, providerUserKey); status = MembershipCreateStatus.Success; return this.GetUser(username, false); } /// <summary> /// Delete User and User's information from provider /// </summary> /// <param name="username"> /// Username to delete /// </param> /// <param name="deleteAllRelatedData"> /// Delete all related daata /// </param> /// <returns> /// Boolean depending on whether the deletion was successful /// </returns> public override bool DeleteUser(string username, bool deleteAllRelatedData) { // Check username argument is not null if (username == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "USERNAMENULL"); } // Process database user deletion request try { MySQLDB.Current.DeleteUser(ConnectionStringName,this.ApplicationName, username, deleteAllRelatedData); return true; } catch { // will return false... } return false; } /// <summary> /// Retrieves all users into a MembershupUserCollection where Email Matches /// </summary> /// <param name="emailToMatch"> /// Email use as filter criteria /// </param> /// <param name="pageIndex"> /// Page Index /// </param> /// <param name="pageSize"> /// The page Size. /// </param> /// <param name="totalRecords"> /// Out - Number of records held /// </param> /// <returns> /// <see cref="MembershipUser"/> Collection /// </returns> public override MembershipUserCollection FindUsersByEmail( string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { var users = new MembershipUserCollection(); if (pageIndex < 0) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGEINDEX"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGESIZE"); } // Loop through all users foreach (DataRow dr in MySQLDB.Current.FindUsersByEmail(ConnectionStringName, this.ApplicationName, emailToMatch, pageIndex, pageSize).Rows) { // Add new user to collection users.Add(this.UserFromDataRow(dr)); } totalRecords = users.Count; return users; } /// <summary> /// Creates a new <see cref="MembershipUser"/> from a <see cref="DataRow"/> with proper fields. /// </summary> /// <param name="dr"></param> /// <returns></returns> private MembershipUser UserFromDataRow(DataRow dr) { return new MembershipUser( this.Name.ToStringDBNull(), dr["Username"].ToStringDBNull(), dr["UserID"].ToStringDBNull(), dr["Email"].ToStringDBNull(), dr["PasswordQuestion"].ToStringDBNull(), dr["Comment"].ToStringDBNull(), dr["IsApproved"].ToBool(), dr["IsLockedOut"].ToBool(), dr["Joined"].ToDateTime(DateTime.UtcNow), dr["LastLogin"].ToDateTime(DateTime.UtcNow), dr["LastActivity"].ToDateTime(DateTime.UtcNow), dr["LastPasswordChange"].ToDateTime(DateTime.UtcNow), dr["LastLockout"].ToDateTime(DateTime.UtcNow)); } /// <summary> /// Retrieves all users into a <see cref="MembershipUserCollection"/> where Username matches /// </summary> /// <param name="usernameToMatch"> /// Username use as filter criteria /// </param> /// <param name="pageIndex"> /// Page Index /// </param> /// <param name="pageSize"> /// The page Size. /// </param> /// <param name="totalRecords"> /// Out - Number of records held /// </param> /// <returns> /// <see cref="MembershipUser"/> Collection /// </returns> public override MembershipUserCollection FindUsersByName( string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { var users = new MembershipUserCollection(); if (pageIndex < 0) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGEINDEX"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGESIZE"); } // Loop through all users foreach (DataRow dr in MySQLDB.Current.FindUsersByName(ConnectionStringName, this.ApplicationName, usernameToMatch, pageIndex, pageSize).Rows) { // Add new user to collection users.Add(this.UserFromDataRow(dr)); } totalRecords = users.Count; return users; } /// <summary> /// Retrieves all users into a <see cref="MembershipUserCollection"/> /// </summary> /// <param name="pageIndex"> /// Page Index /// </param> /// <param name="pageSize"> /// The page Size. /// </param> /// <param name="totalRecords"> /// Out - Number of records held /// </param> /// <returns> /// <see cref="MembershipUser"/> Collection /// </returns> public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { var users = new MembershipUserCollection(); if (pageIndex < 0) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGEINDEX"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGESIZE"); } // Loop through all users foreach (DataRow dr in MySQLDB.Current.GetAllUsers(ConnectionStringName,this.ApplicationName, pageIndex, pageSize).Rows) { // Add new user to collection users.Add(this.UserFromDataRow(dr)); } totalRecords = users.Count; return users; } /// <summary> /// Retrieves the number of users currently online for this application /// </summary> /// <returns> /// Number of users online /// </returns> public override int GetNumberOfUsersOnline() { return MySQLDB.Current.GetNumberOfUsersOnline(ConnectionStringName,this.ApplicationName, Membership.UserIsOnlineTimeWindow); } /// <summary> /// Retrieves the Users password (if <see cref="EnablePasswordRetrieval"/> is <see langword="true"/>) /// </summary> /// <param name="username"> /// Username to retrieve password for /// </param> /// <param name="answer"> /// Answer to the Users Membership Question /// </param> /// <returns> /// Password unencrypted /// </returns> public override string GetPassword(string username, string answer) { if (!this.EnablePasswordRetrieval) { ExceptionReporter.ThrowNotSupported("MEMBERSHIP", "PASSWORDRETRIEVALNOTSUPPORTED"); } // Check for null arguments if ((username == null) || (answer == null)) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMEPASSWORDNULL"); } MySqlUserPasswordInfo currentPasswordInfo = MySqlUserPasswordInfo.CreateInstanceFromDB( ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentPasswordInfo != null && currentPasswordInfo.IsCorrectAnswer(answer)) { return DecodeString(currentPasswordInfo.Password, currentPasswordInfo.PasswordFormat); } return null; } /// <summary> /// Retrieves a <see cref="MembershipUser"/> object from the criteria given /// </summary> /// <param name="username"> /// Username to be foundr /// </param> /// <param name="userIsOnline"> /// Is the User currently online /// </param> /// <returns> /// MembershipUser object /// </returns> public override MembershipUser GetUser(string username, bool userIsOnline) { if (username == null) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMENULL"); } // if it's empty don't bother calling the MySQLDB. if (username.IsNotSet()) { return null; } DataRow dr = MySQLDB.Current.GetUser(ConnectionStringName,this.ApplicationName, null, username, userIsOnline); return dr != null ? this.UserFromDataRow(dr) : null; } /// <summary> /// Retrieves a <see cref="MembershipUser"/> object from the criteria given /// </summary> /// <param name="providerUserKey"> /// User to be found based on UserKey /// </param> /// <param name="userIsOnline"> /// Is the User currently online /// </param> /// <returns> /// MembershipUser object /// </returns> public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { if (providerUserKey == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "USERKEYNULL"); } DataRow dr = MySQLDB.Current.GetUser(ConnectionStringName,this.ApplicationName, providerUserKey, null, userIsOnline); return dr != null ? this.UserFromDataRow(dr) : null; } /// <summary> /// Retrieves a <see cref="MembershipUser"/> object from the criteria given /// </summary> /// <param name="email"> /// The email. /// </param> /// <returns> /// Username as string /// </returns> public override string GetUserNameByEmail(string email) { if (email == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "EMAILNULL"); } DataTable users = MySQLDB.Current.GetUserNameByEmail(ConnectionStringName,this.ApplicationName, email); if (this.RequiresUniqueEmail && users.Rows.Count > 1) { ExceptionReporter.ThrowProvider("MEMBERSHIP", "TOOMANYUSERNAMERETURNS"); } return users.Rows.Count == 0 ? null : users.Rows[0]["Username"].ToString(); } /// <summary> /// Initialize Membership Provider /// </summary> /// <param name="name"> /// Membership Provider Name /// </param> /// <param name="config"> /// <see cref="NameValueCollection"/> of configuration items /// </param> public override void Initialize(string name, NameValueCollection config) { // Verify that the configuration section was properly passed if (!config.HasKeys()) { ExceptionReporter.ThrowArgument("ROLES", "CONFIGNOTFOUND"); } // Retrieve information for provider from web config // config ints // Minimum Required Password Length from Provider configuration this._minimumRequiredPasswordLength = int.Parse(config["minRequiredPasswordLength"] ?? "6"); // Minimum Required Non Alpha-numeric Characters from Provider configuration this._minRequiredNonAlphanumericCharacters = int.Parse(config["minRequiredNonalphanumericCharacters"] ?? "0"); // Maximum number of allowed password attempts this._maxInvalidPasswordAttempts = int.Parse(config["maxInvalidPasswordAttempts"] ?? "5"); // Password Attempt Window when maximum attempts have been reached this._passwordAttemptWindow = int.Parse(config["passwordAttemptWindow"] ?? "10"); // Check whething Hashing methods should use Salt this._useSalt = (config["useSalt"] ?? "false").ToBool(); // Check whether password hashing should output as Hex instead of Base64 this._hashHex = (config["hashHex"] ?? "false").ToBool(); // Check to see if password hex case should be altered this._hashCase = config["hashCase"].ToStringDBNull("None"); // Check to see if password should have characters removed this._hashRemoveChars = config["hashRemoveChars"].ToStringDBNull(); // Check to see if password/salt combination needs to asp.net standard membership compliant this._msCompliant = (config["msCompliant"] ?? "false").ToBool(); // Application Name this._appName = config["applicationName"].ToStringDBNull(Config.ApplicationName); // Connection String Name this._connStrName = config["connectionStringName"].ToStringDBNull(Config.ConnectionStringName); this._passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"].ToStringDBNull(); // Password reset enabled from Provider Configuration this._enablePasswordReset = (config["enablePasswordReset"] ?? "true").ToBool(); this._enablePasswordRetrieval = (config["enablePasswordRetrieval"] ?? "false").ToBool(); this._requiresQuestionAndAnswer = (config["requiresQuestionAndAnswer"] ?? "true").ToBool(); this._requiresUniqueEmail = (config["requiresUniqueEmail"] ?? "true").ToBool(); string strPasswordFormat = config["passwordFormat"].ToStringDBNull("Hashed"); switch (strPasswordFormat) { case "Clear": this._passwordFormat = MembershipPasswordFormat.Clear; break; case "Encrypted": this._passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Hashed": this._passwordFormat = MembershipPasswordFormat.Hashed; break; default: ExceptionReporter.Throw("MEMBERSHIP", "BADPASSWORDFORMAT"); break; } // is the connection string set? if (this._connStrName.IsSet()) { string connStr = ConfigurationManager.ConnectionStrings[this._connStrName].ConnectionString; ConnectionString = connStr; ConnectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connStr); // set the app variable... if (YafContext.Current.Get<HttpApplicationStateBase>()[ConnStrAppKeyName] == null) { YafContext.Current.Get<HttpApplicationStateBase>().Add(ConnStrAppKeyName, connStr); } else { YafContext.Current.Get<HttpApplicationStateBase>()[ConnStrAppKeyName] = connStr; } } base.Initialize(name, config); } /// <summary> /// Reset a users password - * /// </summary> /// <param name="username"> /// User to be found based by Name /// </param> /// <param name="answer"> /// Verification that it is them /// </param> /// <returns> /// Username as string /// </returns> public override string ResetPassword(string username, string answer) { string newPassword = string.Empty, newPasswordEnc = string.Empty, newPasswordSalt = string.Empty, newPasswordAnswer = string.Empty; // Check Password reset is enabled if (!this.EnablePasswordReset) { ExceptionReporter.ThrowNotSupported("MEMBERSHIP", "RESETNOTSUPPORTED"); } // Check arguments for null values if (username == null) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMEPASSWORDNULL"); } // get an instance of the current password information class MySqlUserPasswordInfo currentPasswordInfo = MySqlUserPasswordInfo.CreateInstanceFromDB( ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentPasswordInfo != null) { if (this.UseSalt && currentPasswordInfo.PasswordSalt.IsNotSet()) { // get a new password salt... newPasswordSalt = GenerateSalt(); } else { // use existing salt... newPasswordSalt = currentPasswordInfo.PasswordSalt; } if (answer.IsSet()) { // verify answer is correct... if (!currentPasswordInfo.IsCorrectAnswer(answer)) { return null; } } // create a new password newPassword = GeneratePassword(this.MinRequiredPasswordLength, this.MinRequiredNonAlphanumericCharacters); // encode it... newPasswordEnc = EncodeString( newPassword, (int)this.PasswordFormat, newPasswordSalt, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); // save to the database MySQLDB.Current.ResetPassword(ConnectionStringName, this.ApplicationName, username, newPasswordEnc, newPasswordSalt, (int)this.PasswordFormat, this.MaxInvalidPasswordAttempts, this.PasswordAttemptWindow); // Return unencrypted password return newPassword; } return null; } /// <summary> /// Unlocks a users account /// </summary> /// <param name="userName"> /// The user Name. /// </param> /// <returns> /// True/False is users account has been unlocked /// </returns> public override bool UnlockUser(string userName) { // Check for null argument if (userName == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "USERNAMENULL"); } try { MySQLDB.Current.UnlockUser(ConnectionStringName, this.ApplicationName, userName); return true; } catch { // will return false below } return false; } /// <summary> /// Updates a providers user information /// </summary> /// <param name="user"> /// <see cref="MembershipUser"/> object /// </param> public override void UpdateUser(MembershipUser user) { // Check User object is not null if (user == null) { ExceptionReporter.ThrowArgumentNull("MEMBERSHIP", "MEMBERSHIPUSERNULL"); } // Update User int updateStatus = MySQLDB.Current.UpdateUser(ConnectionStringName, this.ApplicationName, user, this.RequiresUniqueEmail); // Check update was not successful if (updateStatus != 0) { // An error has occurred, determine which one. switch (updateStatus) { case 1: ExceptionReporter.Throw("MEMBERSHIP", "USERKEYNULL"); break; case 2: ExceptionReporter.Throw("MEMBERSHIP", "DUPLICATEEMAIL"); break; } } } /// <summary> /// Validates a user by user name / password /// </summary> /// <param name="username"> /// Username /// </param> /// <param name="password"> /// Password /// </param> /// /// /// <returns> /// True/False whether username/password match what is on database. /// </returns> public override bool ValidateUser(string username, string password) { MySqlUserPasswordInfo currentUser = MySqlUserPasswordInfo.CreateInstanceFromDB( ConnectionStringName, this.ApplicationName, username, false, this.UseSalt, this.HashHex, this.HashCase, this.HashRemoveChars, this.MSCompliant); if (currentUser != null && currentUser.IsApproved) { return currentUser.IsCorrectPassword(password); } return false; } #endregion #region Methods /// <summary> /// Encrypt string to hash method. /// </summary> /// <param name="clearString"> /// UnEncrypted Clear String /// </param> /// <param name="encFormat"> /// The enc Format. /// </param> /// <param name="salt"> /// Salt to be used in Hash method /// </param> /// <param name="useSalt"> /// Salt to be used in Hash method /// </param> /// <param name="hashHex"> /// The hash Hex. /// </param> /// <param name="hashCase"> /// The hash Case. /// </param> /// <param name="hashRemoveChars"> /// The hash Remove Chars. /// </param> /// <param name="msCompliant"> /// The ms Compliant. /// </param> /// <returns> /// Encrypted string /// </returns> internal static string EncodeString( string clearString, int encFormat, string salt, bool useSalt, bool hashHex, string hashCase, string hashRemoveChars, bool msCompliant) { string encodedPass = string.Empty; var passwordFormat = (MembershipPasswordFormat)Enum.ToObject(typeof(MembershipPasswordFormat), encFormat); // Multiple Checks to ensure UseSalt is valid. if (clearString.IsNotSet()) { // Check to ensure string is not null or empty. return String.Empty; } if (useSalt && salt.IsNotSet()) { // If Salt value is null disable Salt procedure useSalt = false; } if (useSalt && passwordFormat == MembershipPasswordFormat.Encrypted) { useSalt = false; // Cannot use Salt with encryption } // Check Encoding format / method switch (passwordFormat) { case MembershipPasswordFormat.Clear: // plain text encodedPass = clearString; break; case MembershipPasswordFormat.Hashed: encodedPass = Hash(clearString, HashType(), salt, useSalt, hashHex, hashCase, hashRemoveChars, msCompliant); break; case MembershipPasswordFormat.Encrypted: encodedPass = Encrypt(clearString, salt, msCompliant); break; default: encodedPass = Hash(clearString, HashType(), salt, useSalt, hashHex, hashCase, hashRemoveChars, msCompliant); break; } return encodedPass; } /// <summary> /// Decrypt string using passwordFormat. /// </summary> /// <param name="pass"> /// Password to be decrypted /// </param> /// <param name="passwordFormat"> /// Method of encryption /// </param> /// <returns> /// Unencrypted string /// </returns> private static string DecodeString(string pass, int passwordFormat) { switch ((MembershipPasswordFormat)Enum.ToObject(typeof(MembershipPasswordFormat), passwordFormat)) { case MembershipPasswordFormat.Clear: // MembershipPasswordFormat.Clear: return pass; case MembershipPasswordFormat.Hashed: // MembershipPasswordFormat.Hashed: ExceptionReporter.Throw("MEMBERSHIP", "DECODEHASH"); break; case MembershipPasswordFormat.Encrypted: byte[] bIn = Convert.FromBase64String(pass); byte[] bRet = (new VzfMySqlMembershipProvider()).DecryptPassword(bIn); if (bRet == null) { return null; } return Encoding.Unicode.GetString(bRet, 16, bRet.Length - 16); default: ExceptionReporter.Throw("MEMBERSHIP", "DECODEHASH"); break; } return String.Empty; // Removes "Not all paths return a value" warning. } /// <summary> /// The encrypt. /// </summary> /// <param name="clearString"> /// The clear string. /// </param> /// <param name="saltString"> /// The salt string. /// </param> /// <param name="standardComp"> /// The standard comp. /// </param> /// <returns> /// The encrypt. /// </returns> private static string Encrypt(string clearString, string saltString, bool standardComp) { byte[] buffer = GeneratePasswordBuffer(saltString, clearString, standardComp); return Convert.ToBase64String((new VzfMySqlMembershipProvider()).EncryptPassword(buffer)); } /// <summary> /// Creates a random password based on a miniumum length and a minimum number of non-alphanumeric characters /// </summary> /// <param name="minPassLength"> /// Minimum characters in the password /// </param> /// <param name="minNonAlphas"> /// Minimum non-alphanumeric characters /// </param> /// <returns> /// Random string /// </returns> private static string GeneratePassword(int minPassLength, int minNonAlphas) { return Membership.GeneratePassword(minPassLength < _passwordsize ? _passwordsize : minPassLength, minNonAlphas); } /// <summary> /// Creates a random string used as Salt for hashing /// </summary> /// <returns> /// Random string /// </returns> private static string GenerateSalt() { var buf = new byte[16]; var rngCryptoSp = new RNGCryptoServiceProvider(); rngCryptoSp.GetBytes(buf); return Convert.ToBase64String(buf); } /// <summary> /// Hashes clear bytes to given hashtype /// </summary> /// <param name="clearBytes"> /// Clear bytes to hash /// </param> /// <param name="hashType"> /// hash Algorithm to be used /// </param> /// <returns> /// Hashed bytes /// </returns> private static byte[] Hash(byte[] clearBytes, string hashType) { // MD5, SHA1, SHA256, SHA384, SHA512 byte[] hash = HashAlgorithm.Create(hashType).ComputeHash(clearBytes); return hash; } /// <summary> /// The hash type. /// </summary> /// <returns> /// The hash type. /// </returns> private static string HashType() { if (Membership.HashAlgorithmType.IsNotSet()) { return "MD5"; // Default Hash Algorithm Type } else { return Membership.HashAlgorithmType; } } /// <summary> /// Check to see if password(string) matches required criteria. /// </summary> /// <param name="password"> /// Password to be checked /// </param> /// <param name="minLength"> /// Minimum length required /// </param> /// <param name="minNonAlphaNumerics"> /// Minimum number of Non-alpha numerics in password /// </param> /// <param name="strengthRegEx"> /// Regular Expression Strength /// </param> /// <returns> /// True/False /// </returns> private static bool IsPasswordCompliant( string password, int minLength, int minNonAlphaNumerics, string strengthRegEx) { // Check password meets minimum length criteria. if (!(password.Length >= minLength)) { return false; } // Count Non alphanumerics int symbolCount = 0; foreach (char checkChar in password.ToCharArray()) { if (!char.IsLetterOrDigit(checkChar)) { symbolCount++; } } // Check password meets minimum alphanumeric criteria if (!(symbolCount >= minNonAlphaNumerics)) { return false; } // Check Reg Expression is present if (strengthRegEx.Length > 0) { // Check password strength meets Password Strength Regex Requirements if (!Regex.IsMatch(password, strengthRegEx)) { return false; } } // Check string meets requirements as set in config return true; } /// <summary> /// Check to see if password(string) matches required criteria. /// </summary> /// <param name="passsword"> /// The passsword. /// </param> /// <returns> /// True/False /// </returns> private bool IsPasswordCompliant(string passsword) { return IsPasswordCompliant( passsword, this.MinRequiredPasswordLength, this.MinRequiredNonAlphanumericCharacters, this.PasswordStrengthRegularExpression); } #endregion } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using JustGiving.EventStore.Http.Client; using JustGiving.EventStore.Http.Client.Common.Utils; using JustGiving.EventStore.Http.Client.Exceptions; using JustGiving.EventStore.Http.SubscriberHost.Monitoring; using log4net; namespace JustGiving.EventStore.Http.SubscriberHost { public class EventStreamSubscriber : IEventStreamSubscriber { public const string StreamIdentifierSeparator = "*@:^:@*"; private readonly IEventStoreHttpConnection _connection; private readonly IEventHandlerResolver _eventHandlerResolver; private readonly IStreamPositionRepository _streamPositionRepository; private readonly ISubscriptionTimerManager _subscriptionTimerManager; private readonly IEventTypeResolver _eventTypeResolver; private readonly ILog _log; private readonly TimeSpan _defaultPollingInterval; private readonly int _sliceSize; private readonly TimeSpan? _longPollingTimeout; private readonly IEnumerable<IEventStreamSubscriberPerformanceMonitor> _performanceMonitors; private readonly int _eventNotFoundRetryCount; private readonly TimeSpan _eventNotFoundRetryDelay; public IStreamSubscriberIntervalMonitor StreamSubscriberMonitor { get; private set; } public PerformanceStats AllEventsStats { get; private set; } public PerformanceStats ProcessedEventsStats { get; private set; } private readonly object _synchroot = new object(); /// <summary> /// Creates a new <see cref="IEventStreamSubscriber"/> to single node using default <see cref="ConnectionSettings"/> /// </summary> /// <param name="settings">The <see cref="ConnectionSettings"/> to apply to the new connection</param> /// <returns>a new <see cref="IEventStreamSubscriber"/></returns> public static IEventStreamSubscriber Create(EventStreamSubscriberSettings settings) { return new EventStreamSubscriber(settings); } /// <summary> /// Creates a new <see cref="IEventStreamSubscriber"/> to single node using default <see cref="ConnectionSettings"/> /// </summary> /// <returns>a new <see cref="IEventStreamSubscriber"/></returns> public static IEventStreamSubscriber Create(IEventStoreHttpConnection connection, IEventHandlerResolver eventHandlerResolver, IStreamPositionRepository streamPositionRepository) { return new EventStreamSubscriber(EventStreamSubscriberSettings.Default(connection, eventHandlerResolver, streamPositionRepository)); } internal EventStreamSubscriber(EventStreamSubscriberSettings settings) { _connection = settings.Connection; _eventHandlerResolver = settings.EventHandlerResolver; _streamPositionRepository = settings.StreamPositionRepository; _subscriptionTimerManager = settings.SubscriptionTimerManager; _eventTypeResolver = settings.EventTypeResolver; _defaultPollingInterval = settings.DefaultPollingInterval; _sliceSize = settings.SliceSize; _longPollingTimeout = settings.LongPollingTimeout; _performanceMonitors = settings.PerformanceMonitors; _log = settings.Log; _eventNotFoundRetryCount = settings.EventNotFoundRetryCount; _eventNotFoundRetryDelay = settings.EventNotFoundRetryDelay; StreamSubscriberMonitor = settings.SubscriberIntervalMonitor; AllEventsStats = new PerformanceStats(settings.MessageProcessingStatsWindowPeriod, settings.MessageProcessingStatsWindowCount); ProcessedEventsStats = new PerformanceStats(settings.MessageProcessingStatsWindowPeriod, settings.MessageProcessingStatsWindowCount); } public void SubscribeTo(string stream, string subscriberId, TimeSpan? pollInterval = null) { lock (_synchroot) { var interval = pollInterval ?? _defaultPollingInterval; Log.Info(_log, "Subscribing to {0}|{1} with an interval of {2}", stream, subscriberId ?? "default", interval); _subscriptionTimerManager.Add(stream, subscriberId, interval, async () => await PollAsync(stream, subscriberId).ConfigureAwait(false), () => StreamSubscriberMonitor.UpdateEventStreamSubscriberIntervalMonitor(stream, interval, subscriberId)); Log.Info(_log, "Subscribed to {0}|{1} with an interval of {2}", stream, subscriberId ?? "default", interval); } } public void UnsubscribeFrom(string stream, string subscriberId) { lock (_synchroot) { Log.Info(_log, "Unsubscribing from {0}|{1}", stream, subscriberId ?? "default"); _subscriptionTimerManager.Remove(stream, subscriberId); Log.Info(_log, "Unsubscribed from {0}|{1}", stream, subscriberId); StreamSubscriberMonitor.RemoveEventStreamMonitor(stream, subscriberId); Log.Info(_log, "Stream ticks monitor removed from {0}|{1}", stream, subscriberId ?? "default"); } } public async Task<AdHocInvocationResult> AdHocInvokeAsync(string stream, int eventNumber, string subscriberId = null) { var eventMetadata = await _connection.ReadEventAsync(stream, eventNumber).ConfigureAwait(false); if (eventMetadata.Status != EventReadStatus.Success) { return new AdHocInvocationResult(AdHocInvocationResult.AdHocInvocationResultCode.CouldNotFindEvent); } var eventInfo = eventMetadata.EventInfo; var handlers = GetEventHandlersFor(eventInfo.EventType, subscriberId); if (handlers.Any()) { var eventType = _eventTypeResolver.Resolve(eventInfo.EventType); var @event = eventInfo.Content.GetObject(eventType); var errors = await InvokeMessageHandlersForEventMessageAsync(stream, eventType, handlers, @event, eventInfo).ConfigureAwait(false); return errors.Any() ? new AdHocInvocationResult(errors) : new AdHocInvocationResult(AdHocInvocationResult.AdHocInvocationResultCode.Success); } return new AdHocInvocationResult(AdHocInvocationResult.AdHocInvocationResultCode.NoHandlersFound); } public async Task PollAsync(string stream, string subscriberId) { Log.Debug(_log, "{0}|{1}: Begin polling", stream, subscriberId ?? "default"); lock (_synchroot) { _subscriptionTimerManager.Pause(stream, subscriberId);//we want to be able to cane a stream if we are not up to date, without reading it twice } try { await PollAsyncInternal(stream, subscriberId).ConfigureAwait(false); } catch (Exception ex) { Log.Error(_log, ex, "{0}|{1}: Generic last-chance catch", stream, subscriberId ?? "default"); } lock (_synchroot) { _subscriptionTimerManager.Resume(stream, subscriberId); } Log.Debug(_log, "{0}|{1}: Finished polling", stream, subscriberId); } private async Task PollAsyncInternal(string stream, string subscriberId) { var runAgain = false; do { var lastPosition = await _streamPositionRepository.GetPositionForAsync(stream, subscriberId).ConfigureAwait(false) ?? -1; Log.Debug(_log, "{0}|{1}: Last position for stream was {2}", stream, subscriberId ?? "default", lastPosition); Log.Debug(_log, "{0}|{1}: Begin reading event metadata", stream, subscriberId??"default"); var processingBatch = await _connection.ReadStreamEventsForwardAsync(stream, lastPosition + 1, _sliceSize, _longPollingTimeout).ConfigureAwait(false); Log.Debug(_log, "{0}|{1}: Finished reading event metadata: {2}", stream, subscriberId ?? "default", processingBatch.Status); if (processingBatch.Status == StreamReadStatus.Success) { Log.Debug(_log, "{0}|{1}: Processing {2} events", stream, subscriberId ?? "default", processingBatch.Entries.Count); foreach (var message in processingBatch.Entries) { var handlers = GetEventHandlersFor(message.EventType, subscriberId); AllEventsStats.MessageProcessed(stream); if (handlers.Any()) { await ProcessSingleMessageAsync(stream, _eventTypeResolver.Resolve(message.EventType), handlers, message, subscriberId).ConfigureAwait(false); ProcessedEventsStats.MessageProcessed(stream); } else { _performanceMonitors.AsParallel() .ForAll( m => m.Accept(stream, message.EventType, message.Updated, 0, Enumerable.Empty<KeyValuePair<Type, Exception>>()) ); } Log.Debug(_log, "{0}|{1}: Storing last read event as {2}", stream, subscriberId ?? "default", message.PositionEventNumber); await _streamPositionRepository.SetPositionForAsync(stream, subscriberId, message.PositionEventNumber).ConfigureAwait(false); if (!IsSubscribed(subscriberId)) { Log.Debug(_log, "{0}|{1}: subscriber unsubscribed.", stream, subscriberId ?? "default"); break; } } runAgain = processingBatch.Entries.Any() && IsSubscribed(subscriberId); if (runAgain) { Log.Debug(_log, "{0}|{1}: New items were found; repolling", stream, subscriberId ?? "default"); } } else { runAgain = false; } } while (runAgain); } private bool IsSubscribed(string subscriberId) { lock (_synchroot) { return _subscriptionTimerManager.GetSubscriptions().Any(x => x.SubscriberId == subscriberId); } } public IEnumerable<object> GetEventHandlersFor(string eventTypeName, string subscriberId) { var eventType = _eventTypeResolver.Resolve(eventTypeName); if (eventType == null) { Log.Info(_log, "An unsupported event type was passed in. No event type found for {0}", eventTypeName); return Enumerable.Empty<object>(); } var baseHandlerInterfaceType = typeof(IHandleEventsOf<>).MakeGenericType(eventType); var baseMetadataHandlerInterfaceType = typeof(IHandleEventsAndMetadataOf<>).MakeGenericType(eventType); var handlers = _eventHandlerResolver.GetHandlersOf(baseHandlerInterfaceType).Cast<object>().ToList(); var metadataHandlers = _eventHandlerResolver.GetHandlersOf(baseMetadataHandlerInterfaceType).Cast<object>(); var allHandlers = handlers.Concat(metadataHandlers); var handlersForSubscriberId = GetHandlersApplicableToSubscriberId(allHandlers, subscriberId).ToList(); if (handlersForSubscriberId.Any()) { Log.Debug(_log, "{0} handlers found for {1}", handlersForSubscriberId.Count, eventType.FullName); } else { Log.Debug(_log, "No handlers found for {0}", eventType.FullName); } return handlersForSubscriberId; } public IEnumerable<object> GetHandlersApplicableToSubscriberId(IEnumerable<object> handlers, string subscriberId) { if (subscriberId == null) { return handlers.Where(x => !x.GetType().GetCustomAttributes<NonDefaultSubscriberAttribute>().Any()); } return handlers.Where(x =>x.GetType().GetCustomAttributes<NonDefaultSubscriberAttribute>() .Any(att => att.SupportedSubscriberId == subscriberId)); } /// <remarks> /// If the event store is deployed as a cluster, it may be possible to get transient read failures. /// If an event could not be found on the event stream, try again. ///</remarks> private async Task ProcessSingleMessageAsync(string stream, Type eventType, IEnumerable handlers, BasicEventInfo eventInfo, string subscriberId) { var maxAttempts = Math.Max(_eventNotFoundRetryCount, 1); object @event = null; for (var i = 0; i < maxAttempts; i++) { if (i > 0) { await Task.Delay(_eventNotFoundRetryDelay).ConfigureAwait(false); } try { Log.Debug(_log, "{0}|{1}: Processing event {2}. Attempt: {3}", stream, subscriberId ?? "default", eventInfo.Id, i + 1); @event = await _connection.ReadEventBodyAsync(eventType, eventInfo.CanonicalEventLink).ConfigureAwait(false); if (@event != null) { break; } } catch (EventNotFoundException ex) { if (i < maxAttempts - 1) { Log.Warning(_log, "{0}|{1}: Event could not be found. Attempting to process the event again. {2}: {3}", stream, subscriberId ?? "default", eventInfo.Id, ex.Message); } else { Log.Error(_log, "{0}|{1}: Event could not be found after {2} attempts. {3}: {4}", stream, subscriberId ?? "default", i + 1, eventInfo.Id, ex.Message); return; } } catch (Exception ex) { Log.Error(_log, "{0}|{1}: Error getting message {2}: {3}", stream, subscriberId ?? "default", eventInfo.Id, ex); return; } } try { await InvokeMessageHandlersForEventMessageAsync(stream, eventType, handlers, @event, eventInfo).ConfigureAwait(false); } catch (Exception ex) { Log.Error(_log, "{0}|{1}: Error invoking message handlers for message {2}: {3}", stream, subscriberId ?? "default", eventInfo.Id, ex); } } public async Task<IDictionary<Type, Exception>> InvokeMessageHandlersForEventMessageAsync(string stream, Type eventType, IEnumerable handlers, object @event, BasicEventInfo eventInfo) { var handlerCount = 0; var eventTitle = eventInfo.Title; var updated = eventInfo.Updated; var errors = new Dictionary<Type, Exception>(); foreach (var handler in handlers) { handlerCount++; var handlerType = handler.GetType(); var handleMethod = GetMethodFromHandler(handlerType, eventType, "Handle"); if (handleMethod == null) { Log.Warning(_log, "Could not find the handle method for: {0}", handlerType.FullName); continue; } try { try { var arguments = new[] {@event, eventInfo}.Take(handleMethod.GetParameters().Length); await ((Task)handleMethod.Invoke(handler, arguments.ToArray())).ConfigureAwait(false); } catch (Exception invokeException) { errors[handlerType] = invokeException.InnerException; var errorMessage = string.Format("{0} thrown processing event {1}", invokeException.GetType().FullName, eventTitle); Log.Error(_log, errorMessage, invokeException); var errorMethod = GetMethodFromHandler(handlerType, eventType, "OnError"); errorMethod.Invoke(handler, new[] { invokeException, @event }); } } catch (Exception errorHandlingException) { var errorMessage = string.Format("{0} thrown whilst handling error from event {1}", errorHandlingException.GetType().FullName, eventTitle); Log.Error(_log, errorMessage, errorHandlingException); } } _performanceMonitors.AsParallel().ForAll(x => x.Accept(stream, eventType.FullName, updated, handlerCount, errors)); return errors; } ConcurrentDictionary<string, MethodInfo> methodCache = new ConcurrentDictionary<string, MethodInfo>(); public MethodInfo GetMethodFromHandler(Type concreteHandlerType, Type eventType, string methodName) { var cacheKey = string.Format("{0}.{1}({2})", concreteHandlerType, methodName, eventType.FullName); MethodInfo result; if (methodCache.TryGetValue(cacheKey, out result)) { return result; } var handlerInterfaces = new[] {typeof (IHandleEventsOf<>), typeof (IHandleEventsAndMetadataOf<>)}; var @interface = concreteHandlerType.GetInterfaces() .Where(x => x.IsGenericType && handlerInterfaces.Contains(x.GetGenericTypeDefinition()) && x.GetGenericArguments()[0].IsAssignableFrom(eventType)) .OrderBy(x => x.GetGenericArguments()[0], new TypeInheritanceComparer()) .FirstOrDefault(); //a type can explicitly implement two IHandle<> interfaces (which would be insane, but will now at least work) if (@interface == null) { Log.Warning(_log, "{0}, which handles {1} did not contain a suitable method named {2}", concreteHandlerType.FullName, eventType.FullName, methodName); methodCache.TryAdd(cacheKey, result); return null; } result = @interface.GetMethod(methodName); methodCache.TryAdd(cacheKey, result); return result; } public IEnumerable<StreamSubscription> GetSubscriptions() { lock (_synchroot) { return _subscriptionTimerManager.GetSubscriptions() .ToList() .AsReadOnly(); } } } }
using Parse; using Parse.Common.Internal; using NUnit.Framework; using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; namespace ParseTest { [TestFixture] public class JsonTests { [Test] public void TestEmptyJsonStringFail() { Assert.Throws<ArgumentException>(() => Json.Parse("")); } [Test] public void TestInvalidJsonStringAsRootFail() { Assert.Throws<ArgumentException>(() => Json.Parse("\n")); Assert.Throws<ArgumentException>(() => Json.Parse("a")); Assert.Throws<ArgumentException>(() => Json.Parse("abc")); Assert.Throws<ArgumentException>(() => Json.Parse("\u1234")); Assert.Throws<ArgumentException>(() => Json.Parse("\t")); Assert.Throws<ArgumentException>(() => Json.Parse("\t\n\r")); Assert.Throws<ArgumentException>(() => Json.Parse(" ")); Assert.Throws<ArgumentException>(() => Json.Parse("1234")); Assert.Throws<ArgumentException>(() => Json.Parse("1,3")); Assert.Throws<ArgumentException>(() => Json.Parse("{1")); Assert.Throws<ArgumentException>(() => Json.Parse("3}")); Assert.Throws<ArgumentException>(() => Json.Parse("}")); } [Test] public void TestEmptyJsonObject() { var parsed = Json.Parse("{}"); Assert.IsTrue(parsed is IDictionary); } [Test] public void TestEmptyJsonArray() { var parsed = Json.Parse("[]"); Assert.IsTrue(parsed is IList); } [Test] public void TestOneJsonObject() { Assert.Throws<ArgumentException>(() => Json.Parse("{ 1 }")); Assert.Throws<ArgumentException>(() => Json.Parse("{ 1 : 1 }")); Assert.Throws<ArgumentException>(() => Json.Parse("{ 1 : \"abc\" }")); var parsed = Json.Parse("{\"abc\" : \"def\"}"); Assert.IsTrue(parsed is IDictionary); var parsedDict = parsed as IDictionary; Assert.AreEqual("def", parsedDict["abc"]); parsed = Json.Parse("{\"abc\" : {} }"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.IsTrue(parsedDict["abc"] is IDictionary); parsed = Json.Parse("{\"abc\" : \"6060\"}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.AreEqual("6060", parsedDict["abc"]); parsed = Json.Parse("{\"\" : \"\"}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.AreEqual("", parsedDict[""]); parsed = Json.Parse("{\" abc\" : \"def \"}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.AreEqual("def ", parsedDict[" abc"]); parsed = Json.Parse("{\"1\" : 6060}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.AreEqual((Int64)6060, parsedDict["1"]); parsed = Json.Parse("{\"1\" : null}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.IsNull(parsedDict["1"]); parsed = Json.Parse("{\"1\" : true}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.IsTrue((bool)parsedDict["1"]); parsed = Json.Parse("{\"1\" : false}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.IsFalse((bool)parsedDict["1"]); } [Test] public void TestMultipleJsonObjectAsRootFail() { Assert.Throws<ArgumentException>(() => Json.Parse("{},")); Assert.Throws<ArgumentException>(() => Json.Parse("{\"abc\" : \"def\"},")); Assert.Throws<ArgumentException>(() => Json.Parse("{\"abc\" : \"def\" \"def\"}")); Assert.Throws<ArgumentException>(() => Json.Parse("{}, {}")); Assert.Throws<ArgumentException>(() => Json.Parse("{},\n{}")); } [Test] public void TestOneJsonArray() { Assert.Throws<ArgumentException>(() => Json.Parse("[ 1 : 1 ]")); Assert.Throws<ArgumentException>(() => Json.Parse("[ 1 1 ]")); Assert.Throws<ArgumentException>(() => Json.Parse("[ 1 : \"1\" ]")); Assert.Throws<ArgumentException>(() => Json.Parse("[ \"1\" : \"1\" ]")); var parsed = Json.Parse("[ 1 ]"); Assert.IsTrue(parsed is IList); var parsedList = parsed as IList; Assert.AreEqual((Int64)1, parsedList[0]); parsed = Json.Parse("[ \n ]"); Assert.IsTrue(parsed is IList); parsedList = parsed as IList; Assert.AreEqual(0, parsedList.Count); parsed = Json.Parse("[ \"asdf\" ]"); Assert.IsTrue(parsed is IList); parsedList = parsed as IList; Assert.AreEqual("asdf", parsedList[0]); parsed = Json.Parse("[ \"\u849c\" ]"); Assert.IsTrue(parsed is IList); parsedList = parsed as IList; Assert.AreEqual("\u849c", parsedList[0]); } [Test] public void TestMultipleJsonArrayAsRootFail() { Assert.Throws<ArgumentException>(() => Json.Parse("[],")); Assert.Throws<ArgumentException>(() => Json.Parse("[\"abc\" : \"def\"],")); Assert.Throws<ArgumentException>(() => Json.Parse("[], []")); Assert.Throws<ArgumentException>(() => Json.Parse("[],\n[]")); } [Test] public void TestJsonArrayInsideJsonObject() { Assert.Throws<ArgumentException>(() => Json.Parse("{ [] }")); Assert.Throws<ArgumentException>(() => Json.Parse("{ [], [] }")); Assert.Throws<ArgumentException>(() => Json.Parse("{ \"abc\": [], [] }")); var parsed = Json.Parse("{ \"abc\": [] }"); Assert.IsTrue(parsed is IDictionary); var parsedDict = parsed as IDictionary; Assert.IsTrue(parsedDict["abc"] is IList); parsed = Json.Parse("{ \"6060\" :\n[ 6060 ]\t}"); Assert.IsTrue(parsed is IDictionary); parsedDict = parsed as IDictionary; Assert.IsTrue(parsedDict["6060"] is IList); var parsedList = parsedDict["6060"] as IList; Assert.AreEqual((Int64)6060, parsedList[0]); } [Test] public void TestJsonObjectInsideJsonArray() { Assert.Throws<ArgumentException>(() => Json.Parse("[ {} : {} ]")); // whitespace test var parsed = Json.Parse("[\t\n{}\r\t]"); Assert.IsTrue(parsed is IList); var parsedList = parsed as IList; Assert.IsTrue(parsedList[0] is IDictionary); parsed = Json.Parse("[ {}, { \"final\" : \"fantasy\"} ]"); Assert.IsTrue(parsed is IList); parsedList = parsed as IList; Assert.IsTrue(parsedList[0] is IDictionary); Assert.IsTrue(parsedList[1] is IDictionary); var parsedDictionary = parsedList[1] as IDictionary; Assert.AreEqual("fantasy", parsedDictionary["final"]); } [Test] public void TestJsonObjectWithElements() { // Just make sure they don't throw exception as we already check their content correctness // in other unit tests. Json.Parse("{ \"mura\": \"masa\" }"); Json.Parse("{ \"mura\": 1234 }"); Json.Parse("{ \"mura\": { \"masa\": 1234 } }"); Json.Parse("{ \"mura\": { \"masa\": [ 1234 ] } }"); Json.Parse("{ \"mura\": { \"masa\": [ 1234 ] }, \"arr\": [] }"); } [Test] public void TestJsonArrayWithElements() { // Just make sure they don't throw exception as we already check their content correctness // in other unit tests. Json.Parse("[ \"mura\" ]"); Json.Parse("[ \"\u1234\" ]"); Json.Parse("[ \"\u1234ff\", \"\u1234\" ]"); Json.Parse("[ [], [], [], [] ]"); Json.Parse("[ [], [ {}, {} ], [ {} ], [] ]"); } [Test] public void TestEncodeJson() { var dict = new Dictionary<string, object>(); string encoded = Json.Encode(dict); Assert.AreEqual("{}", encoded); var list = new List<object>(); encoded = Json.Encode(list); Assert.AreEqual("[]", encoded); var dictChild = new Dictionary<string, object>(); list.Add(dictChild); encoded = Json.Encode(list); Assert.AreEqual("[{}]", encoded); list.Add("1234 a\t\r\n"); list.Add(1234); list.Add(12.34); list.Add(1.23456789123456789); encoded = Json.Encode(list); Assert.AreEqual("[{},\"1234 a\\t\\r\\n\",1234,12.34,1.23456789123457]", encoded); dict["arr"] = new List<object>(); encoded = Json.Encode(dict); Assert.AreEqual("{\"arr\":[]}", encoded); dict["\u1234"] = "\u1234"; encoded = Json.Encode(dict); Assert.AreEqual("{\"arr\":[],\"\u1234\":\"\u1234\"}", encoded); var newList = new List<object>(); newList.Add(true); newList.Add(false); newList.Add(null); encoded = Json.Encode(newList); Assert.AreEqual("[true,false,null]", encoded); } [Test] public void TestSpecialJsonNumbersAndModifiers() { Assert.Throws<ArgumentException>(() => Json.Parse("+123456789")); Json.Parse("{ \"mura\": -123456789123456789 }"); Json.Parse("{ \"mura\": 1.1234567891234567E308 }"); Json.Parse("{ \"PI\": 3.141e-10 }"); Json.Parse("{ \"PI\": 3.141E-10 }"); var parsed = Json.Parse("{ \"mura\": 123456789123456789 }") as IDictionary; Assert.AreEqual(123456789123456789, parsed["mura"]); } } }
// // 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 Hyak.Common; using Microsoft.Azure.Management.Internal.Resources.Models; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.Management.Internal.Resources { /// <summary> /// Operations for managing providers. /// </summary> internal partial class ProviderOperations : IServiceOperations<ResourceManagementClient>, IProviderOperations { /// <summary> /// Initializes a new instance of the ProviderOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ProviderOperations(ResourceManagementClient client) { this._client = client; } private ResourceManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient. /// </summary> public ResourceManagementClient Client { get { return this._client; } } /// <summary> /// Gets a resource provider. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource provider information. /// </returns> public async Task<ProviderGetResult> GetAsync(string resourceProviderNamespace, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // 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 ProviderGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Provider providerInstance = new Provider(); result.Provider = providerInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = responseDoc["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = responseDoc["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = responseDoc["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } 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> /// Gets a list of resource providers. /// </summary> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all /// deployments. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource providers. /// </returns> public async Task<ProviderListResult> ListAsync(ProviderListParameters parameters, 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>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers"; List<string> queryParameters = new List<string>(); if (parameters != null && parameters.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString())); } queryParameters.Add("api-version=2014-04-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // 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 ProviderListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Provider providerInstance = new Provider(); result.Providers.Add(providerInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = valueValue["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = valueValue["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = valueValue["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } 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> /// Get a list of deployments. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource providers. /// </returns> public async Task<ProviderListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; 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 // 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 ProviderListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Provider providerInstance = new Provider(); result.Providers.Add(providerInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = valueValue["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = valueValue["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = valueValue["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } 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> /// Registers provider to be used with a subscription. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public async Task<ProviderRegistionResult> RegisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); TracingAdapter.Enter(invocationId, this, "RegisterAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/register"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // 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 ProviderRegistionResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderRegistionResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Provider providerInstance = new Provider(); result.Provider = providerInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = responseDoc["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = responseDoc["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = responseDoc["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } 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> /// Unregisters provider from a subscription. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public async Task<ProviderUnregistionResult> UnregisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); TracingAdapter.Enter(invocationId, this, "UnregisterAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/unregister"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // 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 ProviderUnregistionResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderUnregistionResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Provider providerInstance = new Provider(); result.Provider = providerInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = responseDoc["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = responseDoc["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = responseDoc["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.2.18. Identifies a unique event in a simulation via the combination of three values /// </summary> [Serializable] [XmlRoot] public partial class EventID { /// <summary> /// The application ID /// </summary> private ushort _application; /// <summary> /// The site ID /// </summary> private ushort _site; /// <summary> /// the number of the event /// </summary> private ushort _eventNumber; /// <summary> /// Initializes a new instance of the <see cref="EventID"/> class. /// </summary> public EventID() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(EventID left, EventID right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(EventID left, EventID right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 2; // this._application marshalSize += 2; // this._site marshalSize += 2; // this._eventNumber return marshalSize; } /// <summary> /// Gets or sets the The application ID /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "application")] public ushort Application { get { return this._application; } set { this._application = value; } } /// <summary> /// Gets or sets the The site ID /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "site")] public ushort Site { get { return this._site; } set { this._site = value; } } /// <summary> /// Gets or sets the the number of the event /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "eventNumber")] public ushort EventNumber { get { return this._eventNumber; } set { this._eventNumber = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteUnsignedShort((ushort)this._application); dos.WriteUnsignedShort((ushort)this._site); dos.WriteUnsignedShort((ushort)this._eventNumber); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._application = dis.ReadUnsignedShort(); this._site = dis.ReadUnsignedShort(); this._eventNumber = dis.ReadUnsignedShort(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<EventID>"); try { sb.AppendLine("<application type=\"ushort\">" + this._application.ToString(CultureInfo.InvariantCulture) + "</application>"); sb.AppendLine("<site type=\"ushort\">" + this._site.ToString(CultureInfo.InvariantCulture) + "</site>"); sb.AppendLine("<eventNumber type=\"ushort\">" + this._eventNumber.ToString(CultureInfo.InvariantCulture) + "</eventNumber>"); sb.AppendLine("</EventID>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as EventID; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(EventID obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._application != obj._application) { ivarsEqual = false; } if (this._site != obj._site) { ivarsEqual = false; } if (this._eventNumber != obj._eventNumber) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._application.GetHashCode(); result = GenerateHash(result) ^ this._site.GetHashCode(); result = GenerateHash(result) ^ this._eventNumber.GetHashCode(); return result; } } }
// Copyright 2018 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 ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Rasters; using System; using System.Collections.Generic; using Windows.UI.Popups; using Windows.UI.Xaml; namespace ArcGISRuntime.UWP.Samples.ChangeStretchRenderer { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Stretch renderer", category: "Layers", description: "Use a stretch renderer to enhance the visual contrast of raster data for analysis.", instructions: "Choose one of the stretch parameter types:", tags: new[] { "analysis", "deviation", "histogram", "imagery", "interpretation", "min-max", "percent clip", "pixel", "raster", "stretch", "symbology", "visualization" })] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("95392f99970d4a71bd25951beb34a508")] public partial class ChangeStretchRenderer { public ChangeStretchRenderer() { InitializeComponent(); // Create the UI, setup the control references and execute initialization Initialize(); } private async void Initialize() { // Initialize the GUI controls appearance RendererTypes.Items.Add("Min Max"); RendererTypes.Items.Add("Percent Clip"); RendererTypes.Items.Add("Standard Deviation"); RendererTypes.SelectedIndex = 0; // Add an imagery basemap MyMapView.Map = new Map(BasemapStyle.ArcGISImageryStandard); // Get the file name string filepath = GetRasterPath(); // Load the raster file Raster myRasterFile = new Raster(filepath); // Create the layer RasterLayer myRasterLayer = new RasterLayer(myRasterFile); // Add the layer to the map MyMapView.Map.OperationalLayers.Add(myRasterLayer); try { // Wait for the layer to load await myRasterLayer.LoadAsync(); // Set the viewpoint await MyMapView.SetViewpointGeometryAsync(myRasterLayer.FullExtent); } catch (Exception e) { await new MessageDialog(e.ToString(), "Error").ShowAsync(); } } private async void OnUpdateRendererClicked(object sender, RoutedEventArgs e) { // Convert the text to doubles and return if they're invalid. double input1; double input2; try { input1 = Convert.ToDouble(FirstParameterInput.Text); input2 = Convert.ToDouble(SecondParameterInput.Text); } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); return; } // Get the user choice for the raster stretch render string myRendererTypeChoice = RendererTypes.SelectedValue.ToString(); // Create an IEnumerable from an empty list of doubles for the gamma values in the stretch render IEnumerable<double> myGammaValues = new List<double>(); // Create a color ramp for the stretch renderer ColorRamp myColorRamp = ColorRamp.Create(PresetColorRampType.DemLight, 1000); // Create the place holder for the stretch renderer StretchRenderer myStretchRenderer = null; switch (myRendererTypeChoice) { case "Min Max": // This section creates a stretch renderer based on a MinMaxStretchParameters // TODO: Add you own logic to ensure that accurate min/max stretch values are used // Create an IEnumerable from a list of double min stretch value doubles IEnumerable<double> myMinValues = new List<double> { input1 }; // Create an IEnumerable from a list of double max stretch value doubles IEnumerable<double> myMaxValues = new List<double> { input2 }; // Create a new MinMaxStretchParameters based on the user choice for min and max stretch values MinMaxStretchParameters myMinMaxStretchParameters = new MinMaxStretchParameters(myMinValues, myMaxValues); // Create the stretch renderer based on the user defined min/max stretch values, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myMinMaxStretchParameters, myGammaValues, true, myColorRamp); break; case "Percent Clip": // This section creates a stretch renderer based on a PercentClipStretchParameters // TODO: Add you own logic to ensure that accurate min/max percent clip values are used // Create a new PercentClipStretchParameters based on the user choice for min and max percent clip values PercentClipStretchParameters myPercentClipStretchParameters = new PercentClipStretchParameters(input1, input2); // Create the percent clip renderer based on the user defined min/max percent clip values, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myPercentClipStretchParameters, myGammaValues, true, myColorRamp); break; case "Standard Deviation": // This section creates a stretch renderer based on a StandardDeviationStretchParameters // TODO: Add you own logic to ensure that an accurate standard deviation value is used // Create a new StandardDeviationStretchParameters based on the user choice for standard deviation value StandardDeviationStretchParameters myStandardDeviationStretchParameters = new StandardDeviationStretchParameters(input1); // Create the standard deviation renderer based on the user defined standard deviation value, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myStandardDeviationStretchParameters, myGammaValues, true, myColorRamp); break; } // Get the existing raster layer in the map RasterLayer myRasterLayer = (RasterLayer)MyMapView.Map.OperationalLayers[0]; // Apply the stretch renderer to the raster layer myRasterLayer.Renderer = myStretchRenderer; } private void RendererTypes_SelectionChanged(object sender, Windows.UI.Xaml.Controls.SelectionChangedEventArgs e) { // Get the user choice for the raster stretch render string myRendererTypeChoice = e.AddedItems[0].ToString(); switch (myRendererTypeChoice) { case "Min Max": // This section displays/resets the user choice options for MinMaxStretchParameters // Make sure all the GUI items are visible FirstParameterLabel.Visibility = Visibility.Visible; SecondParameterLabel.Visibility = Visibility.Visible; FirstParameterInput.Visibility = Visibility.Visible; SecondParameterInput.Visibility = Visibility.Visible; // Define what values/options the user sees FirstParameterLabel.Text = "Minimum value (0 - 255):"; SecondParameterLabel.Text = "Maximum value (0 - 255):"; FirstParameterInput.Text = "10"; SecondParameterInput.Text = "150"; break; case "Percent Clip": // This section displays/resets the user choice options for PercentClipStretchParameters // Make sure all the GUI items are visible FirstParameterLabel.Visibility = Visibility.Visible; SecondParameterLabel.Visibility = Visibility.Visible; FirstParameterInput.Visibility = Visibility.Visible; SecondParameterInput.Visibility = Visibility.Visible; // Define what values/options the user sees FirstParameterLabel.Text = "Minimum (0 - 100):"; SecondParameterLabel.Text = "Maximum (0 - 100)"; FirstParameterInput.Text = "0"; SecondParameterInput.Text = "50"; break; case "Standard Deviation": // This section displays/resets the user choice options for StandardDeviationStretchParameters // Make sure that only the necessary GUI items are visible FirstParameterLabel.Visibility = Visibility.Visible; SecondParameterLabel.Visibility = Visibility.Collapsed; FirstParameterInput.Visibility = Visibility.Visible; SecondParameterInput.Visibility = Visibility.Collapsed; // Define what values/options the user sees FirstParameterLabel.Text = "Factor (.25 to 4):"; FirstParameterInput.Text = "0.5"; break; } } private static string GetRasterPath() { return DataManager.GetDataFolder("95392f99970d4a71bd25951beb34a508", "shasta", "ShastaBW.tif"); } } }
/* Copyright (c) 2015 Joe Bogner joebogner@gmail.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. */ //building on mono: mcs microj.cs /define:CSSCRIPT /r:bin/CSScriptLibrary using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Globalization; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Reflection; using System.IO; #if CSSCRIPT using CSScriptLibrary; #endif namespace App { using MicroJ; public static class Program { [STAThread] public static void Main(string[] args) { var argList = args.ToList(); var jsIdx = argList.FindIndex(c => c.Contains("-js")); var debug = argList.FindIndex(c => c.Contains("-d")) > -1; var runRepl = argList.FindIndex(c => c.Contains("-i")) > -1 || args.Length == 0; if (debug) { Debugger.Launch(); } if (args.Length > 0 && jsIdx > -1 && !runRepl) { int times = 1; var timeIdx = args.Take(jsIdx).ToList().FindIndex(c => c.Contains("-n")); if (timeIdx > -1) { times = int.Parse(args[timeIdx + 1]); } long kbAtExecution = GC.GetTotalMemory(false) / 1024; var watch = new Stopwatch(); var parser = new Parser(); watch.Start(); AType ret = null; var cmd = String.Join(" ", args.Skip(jsIdx + 1).ToArray()); Console.WriteLine(cmd); try { for (var i = 0; i < times; i++) { ret = parser.parse(cmd); } } catch (Exception e) { Console.WriteLine(e); } watch.Stop(); if (ret != null) Console.WriteLine(ret.ToString()); Console.WriteLine("Took: {0} ms", (watch.ElapsedMilliseconds) / (double)times); Console.WriteLine("Total: {0} ms", (watch.ElapsedMilliseconds)); long kbAfter1 = GC.GetTotalMemory(false) / 1024; long kbAfter2 = GC.GetTotalMemory(true) / 1024; Console.WriteLine(kbAtExecution + " Started with this kb."); Console.WriteLine(kbAfter1 + " After the test."); Console.WriteLine(kbAfter1 - kbAtExecution + " Amt. Added."); Console.WriteLine(kbAfter2 + " Amt. After Collection"); Console.WriteLine(kbAfter2 - kbAfter1 + " Amt. Collected by GC."); } else if (args.Length > 0 && args[0] == "-tp") { } else { var repl = new Parser(); MicroJ.Parser.MAX_DECIMAL = 6; var files = new List<string>(); if (File.Exists("stdlib.ijs")) { files.Add("stdlib.ijs"); } if (File.Exists("profile.ijs")) { files.Add("profile.ijs"); } if (File.Exists("..\\stdlib.ijs")) { files.Add("..\\stdlib.ijs"); } if (args.Length > 0) { files.Add(args[0]); } bool testMode = argList.FindIndex(c => c.Contains("-t")) > -1; if (testMode) new Tests().TestAll(); foreach(var file in files.Where(x=>!x.StartsWith("-"))) { if (!File.Exists(file) && !file.StartsWith("~")) { Console.WriteLine("file: " + file + " does not exist"); return; } testMode = argList.FindIndex(c => c.Contains("-t")) > -1; bool quiet = argList.FindIndex(c => c.Contains("-q")) > -1; if (file == "stdlib.ijs") { quiet = true; testMode = false;} string[] lines = null; if (!file.StartsWith("~")) lines = File.ReadAllLines(file); else lines = new string[] { file.Substring(1) }; for (var i = 0; i < lines.Length; i++) { var line = lines[i]; try { if (line.StartsWith("NB.") || line.TrimStart(new char[] { ' ', '\t' }).Length == 0) continue; if (line.StartsWith("exit")) break; if (line.StartsWith("!B")) { Debugger.Launch(); Debugger.Break(); line = line.Substring(2, line.Length - 2); } repl.ReadLine = () => { i++; return lines[i]; }; var ret = repl.parse(line).ToString(); if (testMode && ret != "1" && !line.EndsWith("3 : 0") && !line.EndsWith("4 : 0")) { var eqIdx = line.IndexOf("="); var rerun = ""; if (eqIdx > -1) { rerun = repl.parse(line.Substring(0, eqIdx)).ToString(); } eqIdx = line.IndexOf("-:"); if (eqIdx > -1) { rerun = repl.parse(line.Substring(0, eqIdx)).ToString(); } Console.WriteLine("TEST FAILED - " + line + " returned " + ret + " output: " + rerun); } if (!quiet){ Console.WriteLine(ret); } } catch (Exception e) { Console.WriteLine(line + "\n" + e); //if (Parser.ThrowError) { throw; } break; } } } if (runRepl) { string prompt = " "; bool hasError = false; while (true || hasError) { Console.Write(prompt); repl.ReadLine = Console.ReadLine; var line = Console.ReadLine(); if (line == null) break; // on Linux, pressing arrow keys will insert null characters to line line = line.Replace("\0", ""); if (line == "exit") break; line = line.Trim(); if (line == "") continue; try { var ret = repl.parse(line); if (ret.GetCount() > 1000) { var formatter = new Formatter(ret.Shape); for (var i = 0; i < ret.GetCount() && i < 1000; i++) { formatter.Add(ret.GetString(i)); } Console.WriteLine(formatter.ToString()); } else { Console.WriteLine(ret.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); hasError = true; } } } } } } public class Tests { bool equals<T>(T[] a1, T[] a2) { return a1.OrderBy(a => a).SequenceEqual(a2.OrderBy(a => a)); } public void TestAll() { var j = new Parser(); var tests = new Dictionary<string, Func<bool>>(); Func<string, string[]> toWords = w => j.toWords(w); tests["returns itself"] = () => equals(toWords("abc"), new[] { "abc" }); tests["parses spaces"] = () => equals(toWords("+ -"), new[] { "+", "-" }); tests["parses strings"] = () => equals(toWords("1 'hello world' 2"), new[] { "1", "'hello world'", "2" }); tests["parses strings with number"] = () => equals(toWords("1 'hello 2 world' 2"), new[] { "1", "'hello 2 world'", "2" }); //todo failing //tests["parses strings with embedded quote"] = () => equals(toWords("'hello ''this'' world'"), new string[] { "'hello 'this' world'" }); tests["parentheses"] = () => equals(toWords("(abc)"), new[] { "(", "abc", ")" }); tests["parentheses2"] = () => equals(toWords("((abc))"), new[] { "(", "(", "abc", ")", ")" }); tests["numbers"] = () => equals(toWords("1 2 3 4"), new[] { "1 2 3 4" }); tests["floats"] = () => equals(toWords("1.5 2 3 4"), new[] { "1.5 2 3 4" }); tests["op with numbers"] = () => equals(toWords("# 1 2 3 4"), new[] { "#", "1 2 3 4" }); tests["op with numbers 2"] = () => equals(toWords("1 + 2"), new[] { "1", "+", "2" }); tests["op with no spaces"] = () => equals(toWords("1+i. 10"), new[] { "1", "+", "i.", "10" }); tests["op with no spaces 2-1"] = () => equals(toWords("2-1"), new[] { "2", "-", "1" }); tests["op with no spaces i.5"] = () => equals(toWords("i.5"), new[] { "i.", "5" }); tests["adverb +/"] = () => equals(toWords("+/ 1 2 3"), new[] { "+", "/", "1 2 3" }); tests["no spaces 1+2"] = () => equals(toWords("1+2"), new[] { "1", "+", "2" }); tests["copula abc =: '123'"] = () => equals(toWords("abc =: '123'"), new[] { "abc", "=:", "'123'" }); tests["copula abc=:'123'"] = () => equals(toWords("abc=:'123'"), new[] { "abc", "=:", "'123'" }); tests["|: i. 2 3"] = () => equals(toWords("|: i. 2 3"), new[] { "|:", "i.", "2 3" }); tests["negative numbers _5 _6"] = () => equals(toWords("_5 _6"), new[] { "_5 _6" }); tests["negative numbers _5 6 _3"] = () => equals(toWords("_5 6 _3"), new[] { "_5 6 _3" }); tests["names with number"] = () => equals(toWords("a1b =: 1"), new[] { "a1b", "=:", "1" }); tests["names with underscore"] = () => equals(toWords("a_b =: 1"), new[] { "a_b", "=:", "1" }); tests["is with no parens"] = () => equals(toWords("i.3-:3"), new[] { "i.", "3", "-:", "3" }); tests["foreign conjunction"] = () => equals(toWords("(15!:0) 'abc'"), new[] { "(", "15", "!:", ")", "0", "'abc'" }); tests["boxing"] = () => equals(toWords("($ < i. 2 2)"), new[] { "(", "$", "<", "i.", "2 2", ")" }); tests["verb assignment"] = () => { var parser = new Parser(); parser.parse("plus=: +"); var z = parser.parse("1 plus 2").ToString(); return z == "3"; }; tests["double verb assignment"] = () => { var parser = new Parser(); parser.parse("plus=: +"); parser.parse("plusx=: plus"); var z = parser.parse("1 plusx 2").ToString(); return z == "3"; }; tests["rank conjunction /+\"1 i.3"] = () => equals(toWords("/+\"1 i.3"), new[] { "/", "+", "\"", "1", "i.", "3" }); foreach (var key in tests.Keys) { if (!tests[key]()) { //throw new ApplicationException(key); Console.WriteLine("TEST " + key + " failed"); } } } } }
//------------------------------------------------------------------------------ // <copyright file="WebUtility.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // Don't entity encode high chars (160 to 256), to fix bugs VSWhidbey 85857/111927 // #define ENTITY_ENCODE_HIGH_ASCII_CHARS namespace System.Net { using System; using System.Collections.Generic; #if !FEATURE_NETCORE using System.Configuration; #endif using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net.Configuration; using System.Runtime.Versioning; using System.Text; #if FEATURE_NETCORE using System.Security; #endif public static class WebUtility { // some consts copied from Char / CharUnicodeInfo since we don't have friend access to those types private const char HIGH_SURROGATE_START = '\uD800'; private const char LOW_SURROGATE_START = '\uDC00'; private const char LOW_SURROGATE_END = '\uDFFF'; private const int UNICODE_PLANE00_END = 0x00FFFF; private const int UNICODE_PLANE01_START = 0x10000; private const int UNICODE_PLANE16_END = 0x10FFFF; private const int UnicodeReplacementChar = '\uFFFD'; private static readonly char[] _htmlEntityEndingChars = new char[] { ';', '&' }; private static volatile UnicodeDecodingConformance _htmlDecodeConformance = UnicodeDecodingConformance.Auto; private static volatile UnicodeEncodingConformance _htmlEncodeConformance = UnicodeEncodingConformance.Auto; #region HtmlEncode / HtmlDecode methods public static string HtmlEncode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create string writer if we don't have nothing to encode int index = IndexOfHtmlEncodingChars(value, 0); if (index == -1) { return value; } StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); HtmlEncode(value, writer); return writer.ToString(); } #if FEATURE_NETCORE [SecuritySafeCritical] #endif public static unsafe void HtmlEncode(string value, TextWriter output) { if (value == null) { return; } if (output == null) { throw new ArgumentNullException("output"); } int index = IndexOfHtmlEncodingChars(value, 0); if (index == -1) { output.Write(value); return; } Debug.Assert(0 <= index && index <= value.Length, "0 <= index && index <= value.Length"); UnicodeEncodingConformance encodeConformance = HtmlEncodeConformance; int cch = value.Length - index; fixed (char* str = value) { char* pch = str; while (index-- > 0) { output.Write(*pch++); } for (; cch > 0; cch--, pch++) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': output.Write("&lt;"); break; case '>': output.Write("&gt;"); break; case '"': output.Write("&quot;"); break; case '\'': output.Write("&#39;"); break; case '&': output.Write("&amp;"); break; default: output.Write(ch); break; } } else { int valueToEncode = -1; // set to >= 0 if needs to be encoded #if ENTITY_ENCODE_HIGH_ASCII_CHARS if (ch >= 160 && ch < 256) { // The seemingly arbitrary 160 comes from RFC valueToEncode = ch; } else #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS if (encodeConformance == UnicodeEncodingConformance.Strict && Char.IsSurrogate(ch)) { int scalarValue = GetNextUnicodeScalarValueFromUtf16Surrogate(ref pch, ref cch); if (scalarValue >= UNICODE_PLANE01_START) { valueToEncode = scalarValue; } else { // Don't encode BMP characters (like U+FFFD) since they wouldn't have // been encoded if explicitly present in the string anyway. ch = (char)scalarValue; } } if (valueToEncode >= 0) { // value needs to be encoded output.Write("&#"); output.Write(valueToEncode.ToString(NumberFormatInfo.InvariantInfo)); output.Write(';'); } else { // write out the character directly output.Write(ch); } } } } } public static string HtmlDecode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create string writer if we don't have nothing to encode if (!StringRequiresHtmlDecoding(value)) { return value; } StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); HtmlDecode(value, writer); return writer.ToString(); } [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.UInt16.TryParse(System.String,System.Globalization.NumberStyles,System.IFormatProvider,System.UInt16@)", Justification="UInt16.TryParse guarantees that result is zero if the parse fails.")] public static void HtmlDecode(string value, TextWriter output) { if (value == null) { return; } if (output == null) { throw new ArgumentNullException("output"); } if (!StringRequiresHtmlDecoding(value)) { output.Write(value); // good as is return; } UnicodeDecodingConformance decodeConformance = HtmlDecodeConformance; int l = value.Length; for (int i = 0; i < l; i++) { char ch = value[i]; if (ch == '&') { // We found a '&'. Now look for the next ';' or '&'. The idea is that // if we find another '&' before finding a ';', then this is not an entity, // and the next '&' might start a real entity (VSWhidbey 275184) int index = value.IndexOfAny(_htmlEntityEndingChars, i + 1); if (index > 0 && value[index] == ';') { string entity = value.Substring(i + 1, index - i - 1); if (entity.Length > 1 && entity[0] == '#') { // The # syntax can be in decimal or hex, e.g. // &#229; --> decimal // &#xE5; --> same char in hex // See http://www.w3.org/TR/REC-html40/charset.html#entities bool parsedSuccessfully; uint parsedValue; if (entity[1] == 'x' || entity[1] == 'X') { parsedSuccessfully = UInt32.TryParse(entity.Substring(2), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out parsedValue); } else { parsedSuccessfully = UInt32.TryParse(entity.Substring(1), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out parsedValue); } if (parsedSuccessfully) { switch (decodeConformance) { case UnicodeDecodingConformance.Strict: // decoded character must be U+0000 .. U+10FFFF, excluding surrogates parsedSuccessfully = ((parsedValue < HIGH_SURROGATE_START) || (LOW_SURROGATE_END < parsedValue && parsedValue <= UNICODE_PLANE16_END)); break; case UnicodeDecodingConformance.Compat: // decoded character must be U+0001 .. U+FFFF // null chars disallowed for compat with 4.0 parsedSuccessfully = (0 < parsedValue && parsedValue <= UNICODE_PLANE00_END); break; case UnicodeDecodingConformance.Loose: // decoded character must be U+0000 .. U+10FFFF parsedSuccessfully = (parsedValue <= UNICODE_PLANE16_END); break; default: Debug.Assert(false, "Should never get here!"); parsedSuccessfully = false; break; } } if (parsedSuccessfully) { if (parsedValue <= UNICODE_PLANE00_END) { // single character output.Write((char)parsedValue); } else { // multi-character char leadingSurrogate, trailingSurrogate; ConvertSmpToUtf16(parsedValue, out leadingSurrogate, out trailingSurrogate); output.Write(leadingSurrogate); output.Write(trailingSurrogate); } i = index; // already looked at everything until semicolon continue; } } else { i = index; // already looked at everything until semicolon char entityChar = HtmlEntities.Lookup(entity); if (entityChar != (char)0) { ch = entityChar; } else { output.Write('&'); output.Write(entity); output.Write(';'); continue; } } } } output.Write(ch); } } #if FEATURE_NETCORE [SecuritySafeCritical] #endif private static unsafe int IndexOfHtmlEncodingChars(string s, int startPos) { Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length"); UnicodeEncodingConformance encodeConformance = HtmlEncodeConformance; int cch = s.Length - startPos; fixed (char* str = s) { for (char* pch = &str[startPos]; cch > 0; pch++, cch--) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': case '>': case '"': case '\'': case '&': return s.Length - cch; } } #if ENTITY_ENCODE_HIGH_ASCII_CHARS else if (ch >= 160 && ch < 256) { return s.Length - cch; } #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS else if (encodeConformance == UnicodeEncodingConformance.Strict && Char.IsSurrogate(ch)) { return s.Length - cch; } } } return -1; } private static UnicodeDecodingConformance HtmlDecodeConformance { get { if (_htmlDecodeConformance != UnicodeDecodingConformance.Auto) { return _htmlDecodeConformance; } UnicodeDecodingConformance defaultDecodeConformance = (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) ? UnicodeDecodingConformance.Strict : UnicodeDecodingConformance.Compat; UnicodeDecodingConformance decodingConformance = defaultDecodeConformance; #if !FEATURE_NETCORE try { // Read from config decodingConformance = SettingsSectionInternal.Section.WebUtilityUnicodeDecodingConformance; // Normalize conformance settings (turn 'Auto' into the actual setting) if (decodingConformance <= UnicodeDecodingConformance.Auto || decodingConformance > UnicodeDecodingConformance.Loose) { decodingConformance = defaultDecodeConformance; } } catch (ConfigurationException) { // Continue with default values // HtmlDecode and related methods can still be called and format the error page intended for the client // No need to retry again to initialize from the config in case of config errors decodingConformance = defaultDecodeConformance; } catch { // DevDiv: 642025 // ASP.NET uses own ConfigurationManager which can throw in more situations than config errors (i.e. BadRequest) // It's ok to ---- the exception here and continue using the default value // Try to initialize again the next time return defaultDecodeConformance; } #endif _htmlDecodeConformance = decodingConformance; return _htmlDecodeConformance; } } private static UnicodeEncodingConformance HtmlEncodeConformance { get { if (_htmlEncodeConformance != UnicodeEncodingConformance.Auto) { return _htmlEncodeConformance; } UnicodeEncodingConformance defaultEncodeConformance = (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) ? UnicodeEncodingConformance.Strict : UnicodeEncodingConformance.Compat; UnicodeEncodingConformance encodingConformance = defaultEncodeConformance; #if !FEATURE_NETCORE try { // Read from config encodingConformance = SettingsSectionInternal.Section.WebUtilityUnicodeEncodingConformance; // Normalize conformance settings (turn 'Auto' into the actual setting) if (encodingConformance <= UnicodeEncodingConformance.Auto || encodingConformance > UnicodeEncodingConformance.Compat) { encodingConformance = defaultEncodeConformance; } } catch (ConfigurationException) { // Continue with default values // HtmlEncode and related methods can still be called and format the error page intended for the client // No need to retry again to initialize from the config in case of config errors encodingConformance = defaultEncodeConformance; } catch { // DevDiv: 642025 // ASP.NET uses own ConfigurationManager which can throw in more situations than config errors (i.e. BadRequest) // It's ok to ---- the exception here and continue using the default value // Try to initialize again the next time return defaultEncodeConformance; } #endif _htmlEncodeConformance = encodingConformance; return _htmlEncodeConformance; } } #endregion #region UrlEncode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. private static byte[] UrlEncode(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue) { byte[] encoded = UrlEncode(bytes, offset, count); return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes)) ? (byte[])encoded.Clone() : encoded; } private static byte[] UrlEncode(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int cSpaces = 0; int cUnsafe = 0; // count them first for (int i = 0; i < count; i++) { char ch = (char)bytes[offset + i]; if (ch == ' ') cSpaces++; else if (!IsUrlSafeChar(ch)) cUnsafe++; } // nothing to expand? if (cSpaces == 0 && cUnsafe == 0) return bytes; // expand not 'safe' characters into %XX, spaces to +s byte[] expandedBytes = new byte[count + cUnsafe * 2]; int pos = 0; for (int i = 0; i < count; i++) { byte b = bytes[offset + i]; char ch = (char)b; if (IsUrlSafeChar(ch)) { expandedBytes[pos++] = b; } else if (ch == ' ') { expandedBytes[pos++] = (byte)'+'; } else { expandedBytes[pos++] = (byte)'%'; expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf); expandedBytes[pos++] = (byte)IntToHex(b & 0x0f); } } return expandedBytes; } #endregion #region UrlEncode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification="Already shipped public API; code moved here as part of API consolidation")] public static string UrlEncode(string value) { if (value == null) return null; byte[] bytes = Encoding.UTF8.GetBytes(value); return Encoding.UTF8.GetString(UrlEncode(bytes, 0, bytes.Length, false /* alwaysCreateNewReturnValue */)); } public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return UrlEncode(value, offset, count, true /* alwaysCreateNewReturnValue */); } #endregion #region UrlDecode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Changes done - Removed the logic to handle %Uxxxx as it is not standards compliant. private static string UrlDecodeInternal(string value, Encoding encoding) { if (value == null) { return null; } int count = value.Length; UrlDecoder helper = new UrlDecoder(count, encoding); // go through the string's chars collapsing %XX and // appending each char as char, with exception of %XX constructs // that are appended as bytes for (int pos = 0; pos < count; pos++) { char ch = value[pos]; if (ch == '+') { ch = ' '; } else if (ch == '%' && pos < count - 2) { int h1 = HexToInt(value[pos + 1]); int h2 = HexToInt(value[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); continue; } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } return helper.GetString(); } private static byte[] UrlDecodeInternal(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int decodedBytesCount = 0; byte[] decodedBytes = new byte[count]; for (int i = 0; i < count; i++) { int pos = offset + i; byte b = bytes[pos]; if (b == '+') { b = (byte)' '; } else if (b == '%' && i < count - 2) { int h1 = HexToInt((char)bytes[pos + 1]); int h2 = HexToInt((char)bytes[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars b = (byte)((h1 << 4) | h2); i += 2; } } decodedBytes[decodedBytesCount++] = b; } if (decodedBytesCount < decodedBytes.Length) { byte[] newDecodedBytes = new byte[decodedBytesCount]; Array.Copy(decodedBytes, newDecodedBytes, decodedBytesCount); decodedBytes = newDecodedBytes; } return decodedBytes; } #endregion #region UrlDecode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification="Already shipped public API; code moved here as part of API consolidation")] public static string UrlDecode(string encodedValue) { if (encodedValue == null) return null; return UrlDecodeInternal(encodedValue, Encoding.UTF8); } public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return UrlDecodeInternal(encodedValue, offset, count); } #endregion #region Helper methods // similar to Char.ConvertFromUtf32, but doesn't check arguments or generate strings // input is assumed to be an SMP character private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate) { Debug.Assert(UNICODE_PLANE01_START <= smpChar && smpChar <= UNICODE_PLANE16_END); int utf32 = (int)(smpChar - UNICODE_PLANE01_START); leadingSurrogate = (char)((utf32 / 0x400) + HIGH_SURROGATE_START); trailingSurrogate = (char)((utf32 % 0x400) + LOW_SURROGATE_START); } #if FEATURE_NETCORE [SecuritySafeCritical] #endif private static unsafe int GetNextUnicodeScalarValueFromUtf16Surrogate(ref char* pch, ref int charsRemaining) { // invariants Debug.Assert(charsRemaining >= 1); Debug.Assert(Char.IsSurrogate(*pch)); if (charsRemaining <= 1) { // not enough characters remaining to resurrect the original scalar value return UnicodeReplacementChar; } char leadingSurrogate = pch[0]; char trailingSurrogate = pch[1]; if (Char.IsSurrogatePair(leadingSurrogate, trailingSurrogate)) { // we're going to consume an extra char pch++; charsRemaining--; // below code is from Char.ConvertToUtf32, but without the checks (since we just performed them) return (((leadingSurrogate - HIGH_SURROGATE_START) * 0x400) + (trailingSurrogate - LOW_SURROGATE_START) + UNICODE_PLANE01_START); } else { // unmatched surrogate return UnicodeReplacementChar; } } private static int HexToInt(char h) { return (h >= '0' && h <= '9') ? h - '0' : (h >= 'a' && h <= 'f') ? h - 'a' + 10 : (h >= 'A' && h <= 'F') ? h - 'A' + 10 : -1; } private static char IntToHex(int n) { Debug.Assert(n < 0x10); if (n <= 9) return (char)(n + (int)'0'); else return (char)(n - 10 + (int)'A'); } // Set of safe chars, from RFC 1738.4 minus '+' private static bool IsUrlSafeChar(char ch) { if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') return true; switch (ch) { case '-': case '_': case '.': case '!': case '*': case '(': case ')': return true; } return false; } private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count) { if (bytes == null && count == 0) return false; if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } return true; } private static bool StringRequiresHtmlDecoding(string s) { if (HtmlDecodeConformance == UnicodeDecodingConformance.Compat) { // this string requires html decoding only if it contains '&' return (s.IndexOf('&') >= 0); } else { // this string requires html decoding if it contains '&' or a surrogate character for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c == '&' || Char.IsSurrogate(c)) { return true; } } return false; } } #endregion #region UrlDecoder nested class // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes private class UrlDecoder { private int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[] _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[] _byteBuffer; // Encoding to convert chars to bytes private Encoding _encoding; private void FlushBytes() { if (_numBytes > 0) { _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = new char[bufferSize]; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } internal String GetString() { if (_numBytes > 0) FlushBytes(); if (_numChars > 0) return new String(_charBuffer, 0, _numChars); else return String.Empty; } } #endregion #region HtmlEntities nested class // helper class for lookup of HTML encoding entities private static class HtmlEntities { // The list is from http://www.w3.org/TR/REC-html40/sgml/entities.html, except for &apos;, which // is defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent. private static String[] _entitiesList = new String[] { "\x0022-quot", "\x0026-amp", "\x0027-apos", "\x003c-lt", "\x003e-gt", "\x00a0-nbsp", "\x00a1-iexcl", "\x00a2-cent", "\x00a3-pound", "\x00a4-curren", "\x00a5-yen", "\x00a6-brvbar", "\x00a7-sect", "\x00a8-uml", "\x00a9-copy", "\x00aa-ordf", "\x00ab-laquo", "\x00ac-not", "\x00ad-shy", "\x00ae-reg", "\x00af-macr", "\x00b0-deg", "\x00b1-plusmn", "\x00b2-sup2", "\x00b3-sup3", "\x00b4-acute", "\x00b5-micro", "\x00b6-para", "\x00b7-middot", "\x00b8-cedil", "\x00b9-sup1", "\x00ba-ordm", "\x00bb-raquo", "\x00bc-frac14", "\x00bd-frac12", "\x00be-frac34", "\x00bf-iquest", "\x00c0-Agrave", "\x00c1-Aacute", "\x00c2-Acirc", "\x00c3-Atilde", "\x00c4-Auml", "\x00c5-Aring", "\x00c6-AElig", "\x00c7-Ccedil", "\x00c8-Egrave", "\x00c9-Eacute", "\x00ca-Ecirc", "\x00cb-Euml", "\x00cc-Igrave", "\x00cd-Iacute", "\x00ce-Icirc", "\x00cf-Iuml", "\x00d0-ETH", "\x00d1-Ntilde", "\x00d2-Ograve", "\x00d3-Oacute", "\x00d4-Ocirc", "\x00d5-Otilde", "\x00d6-Ouml", "\x00d7-times", "\x00d8-Oslash", "\x00d9-Ugrave", "\x00da-Uacute", "\x00db-Ucirc", "\x00dc-Uuml", "\x00dd-Yacute", "\x00de-THORN", "\x00df-szlig", "\x00e0-agrave", "\x00e1-aacute", "\x00e2-acirc", "\x00e3-atilde", "\x00e4-auml", "\x00e5-aring", "\x00e6-aelig", "\x00e7-ccedil", "\x00e8-egrave", "\x00e9-eacute", "\x00ea-ecirc", "\x00eb-euml", "\x00ec-igrave", "\x00ed-iacute", "\x00ee-icirc", "\x00ef-iuml", "\x00f0-eth", "\x00f1-ntilde", "\x00f2-ograve", "\x00f3-oacute", "\x00f4-ocirc", "\x00f5-otilde", "\x00f6-ouml", "\x00f7-divide", "\x00f8-oslash", "\x00f9-ugrave", "\x00fa-uacute", "\x00fb-ucirc", "\x00fc-uuml", "\x00fd-yacute", "\x00fe-thorn", "\x00ff-yuml", "\x0152-OElig", "\x0153-oelig", "\x0160-Scaron", "\x0161-scaron", "\x0178-Yuml", "\x0192-fnof", "\x02c6-circ", "\x02dc-tilde", "\x0391-Alpha", "\x0392-Beta", "\x0393-Gamma", "\x0394-Delta", "\x0395-Epsilon", "\x0396-Zeta", "\x0397-Eta", "\x0398-Theta", "\x0399-Iota", "\x039a-Kappa", "\x039b-Lambda", "\x039c-Mu", "\x039d-Nu", "\x039e-Xi", "\x039f-Omicron", "\x03a0-Pi", "\x03a1-Rho", "\x03a3-Sigma", "\x03a4-Tau", "\x03a5-Upsilon", "\x03a6-Phi", "\x03a7-Chi", "\x03a8-Psi", "\x03a9-Omega", "\x03b1-alpha", "\x03b2-beta", "\x03b3-gamma", "\x03b4-delta", "\x03b5-epsilon", "\x03b6-zeta", "\x03b7-eta", "\x03b8-theta", "\x03b9-iota", "\x03ba-kappa", "\x03bb-lambda", "\x03bc-mu", "\x03bd-nu", "\x03be-xi", "\x03bf-omicron", "\x03c0-pi", "\x03c1-rho", "\x03c2-sigmaf", "\x03c3-sigma", "\x03c4-tau", "\x03c5-upsilon", "\x03c6-phi", "\x03c7-chi", "\x03c8-psi", "\x03c9-omega", "\x03d1-thetasym", "\x03d2-upsih", "\x03d6-piv", "\x2002-ensp", "\x2003-emsp", "\x2009-thinsp", "\x200c-zwnj", "\x200d-zwj", "\x200e-lrm", "\x200f-rlm", "\x2013-ndash", "\x2014-mdash", "\x2018-lsquo", "\x2019-rsquo", "\x201a-sbquo", "\x201c-ldquo", "\x201d-rdquo", "\x201e-bdquo", "\x2020-dagger", "\x2021-Dagger", "\x2022-bull", "\x2026-hellip", "\x2030-permil", "\x2032-prime", "\x2033-Prime", "\x2039-lsaquo", "\x203a-rsaquo", "\x203e-oline", "\x2044-frasl", "\x20ac-euro", "\x2111-image", "\x2118-weierp", "\x211c-real", "\x2122-trade", "\x2135-alefsym", "\x2190-larr", "\x2191-uarr", "\x2192-rarr", "\x2193-darr", "\x2194-harr", "\x21b5-crarr", "\x21d0-lArr", "\x21d1-uArr", "\x21d2-rArr", "\x21d3-dArr", "\x21d4-hArr", "\x2200-forall", "\x2202-part", "\x2203-exist", "\x2205-empty", "\x2207-nabla", "\x2208-isin", "\x2209-notin", "\x220b-ni", "\x220f-prod", "\x2211-sum", "\x2212-minus", "\x2217-lowast", "\x221a-radic", "\x221d-prop", "\x221e-infin", "\x2220-ang", "\x2227-and", "\x2228-or", "\x2229-cap", "\x222a-cup", "\x222b-int", "\x2234-there4", "\x223c-sim", "\x2245-cong", "\x2248-asymp", "\x2260-ne", "\x2261-equiv", "\x2264-le", "\x2265-ge", "\x2282-sub", "\x2283-sup", "\x2284-nsub", "\x2286-sube", "\x2287-supe", "\x2295-oplus", "\x2297-otimes", "\x22a5-perp", "\x22c5-sdot", "\x2308-lceil", "\x2309-rceil", "\x230a-lfloor", "\x230b-rfloor", "\x2329-lang", "\x232a-rang", "\x25ca-loz", "\x2660-spades", "\x2663-clubs", "\x2665-hearts", "\x2666-diams", }; private static Dictionary<string, char> _lookupTable = GenerateLookupTable(); private static Dictionary<string, char> GenerateLookupTable() { // e[0] is unicode char, e[1] is '-', e[2+] is entity string Dictionary<string, char> lookupTable = new Dictionary<string, char>(StringComparer.Ordinal); foreach (string e in _entitiesList) { lookupTable.Add(e.Substring(2), e[0]); } return lookupTable; } public static char Lookup(string entity) { char theChar; _lookupTable.TryGetValue(entity, out theChar); return theChar; } } #endregion } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // 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> //----------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Linq; using WootzJs.Testing; namespace WootzJs.Compiler.Tests.Linq { public class EnumerableTests : TestFixture { [Test] public void Aggregate() { var array = new[] { 1, 2, 3 }; var result = array.Aggregate((x, y) => x + y); AssertEquals(result, 6); } [Test] public void AggregateWithSeed() { var array = new[] { 1, 2, 3 }; var result = array.Aggregate(10, (x, y) => x + y); AssertEquals(result, 16); } [Test] public void AggregateWithSeedAndResult() { var array = new[] { 1, 2, 3 }; var result = array.Aggregate(10, (x, y) => x + y, x => x.ToString()); AssertEquals(result, "16"); } [Test] public void All() { var array = new[] { 1, 2, 3 }; AssertEquals(array.All(x => x > 0), true); AssertEquals(array.All(x => x > 1), false); } [Test] public void Where() { var array = new[] { "1", "2", "3" }; var two = array.Where(x => x == "2").Single(); AssertEquals(two, "2"); } [Test] public void WhereWithIndex() { var array = new[] { "1", "2", "3" }; var result = array.Where((x, i) => x == "2" || i == 2).ToArray(); AssertEquals(result.Length, 2); AssertEquals(result[0], "2"); AssertEquals(result[1], "3"); } [Test] public void Select() { var array = new[] { "1", "2", "3" }; var two = array.Select(x => x + "a").ToArray(); AssertEquals(two[0], "1a"); AssertEquals(two[1], "2a"); AssertEquals(two[2], "3a"); } [Test] public void SelectWithIndex() { var array = new[] { "1", "2", "3" }; var two = array.Select((x, i) => x + "a" + i).ToArray(); AssertEquals(two[0], "1a0"); AssertEquals(two[1], "2a1"); AssertEquals(two[2], "3a2"); } [Test] public void SelectMany() { var arrays = new[] { new[] { "1", "2", "3" }, new[] { "4", "5", "6" } }; var elements = arrays.SelectMany(x => x).ToArray(); AssertEquals(elements.Length, 6); AssertEquals(elements[0], "1"); AssertEquals(elements[1], "2"); AssertEquals(elements[2], "3"); AssertEquals(elements[3], "4"); AssertEquals(elements[4], "5"); AssertEquals(elements[5], "6"); } [Test] public void SelectManyWithIndex() { var arrays = new[] { new[] { "1", "2", "3" }, new[] { "4", "5", "6" } }; var elements = arrays.SelectMany((x, i) => x.Select(y => y + i)).ToArray(); AssertEquals(elements.Length, 6); AssertEquals(elements[0], "10"); AssertEquals(elements[1], "20"); AssertEquals(elements[2], "30"); AssertEquals(elements[3], "41"); AssertEquals(elements[4], "51"); AssertEquals(elements[5], "61"); } [Test] public void SelectManyWithIndexAndResultSelector() { var arrays = new[] { new[] { "1", "2", "3" }, new[] { "4", "5", "6" } }; var elements = arrays.SelectMany((x, i) => x.Select(y => y + i), (row, item) => row.Length*int.Parse(item)).ToArray(); AssertEquals(elements.Length, 6); AssertEquals(elements[0], 30); AssertEquals(elements[1], 60); AssertEquals(elements[2], 90); AssertEquals(elements[3], 123); AssertEquals(elements[4], 153); AssertEquals(elements[5], 183); } [Test] public void SelectManyWithResultSelector() { var arrays = new[] { new[] { "1", "2", "3" }, new[] { "4", "5", "6" } }; var elements = arrays.SelectMany(x => x, (row, item) => row.Length*int.Parse(item)).ToArray(); AssertEquals(elements.Length, 6); AssertEquals(elements[0], 3); AssertEquals(elements[1], 6); AssertEquals(elements[2], 9); AssertEquals(elements[3], 12); AssertEquals(elements[4], 15); AssertEquals(elements[5], 18); } [Test] public void Max() { AssertEquals(new[] { 1, 2, 3 }.Max(), 3); AssertEquals(new[] { 1.3, 2.4, 3.5 }.Max(), 3.5); } [Test] public void Min() { AssertEquals(new[] { -1, 2, 3 }.Min(), -1); AssertEquals(new[] { 1.3, -2.4, 3.5 }.Min(), -2.4); } [Test] public void Take() { var ints = new[] { 8, 3, 5, 1 }.Take(3).ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 8); AssertEquals(ints[1], 3); AssertEquals(ints[2], 5); } [Test] public void TakeWhile() { var ints = new[] { 1, 2, 3, 4, 5 }.TakeWhile(x => x < 3).ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); } [Test] public void TakeWhileWithIndex() { var ints = new[] { 1, 2, 3, 4, 5 }.TakeWhile((x, i) => i < 3).ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 1); AssertEquals(ints[1], 2); AssertEquals(ints[2], 3); } [Test] public void Skip() { var ints = new[] { 8, 3, 5, 1 }.Skip(2).ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 5); AssertEquals(ints[1], 1); } [Test] public void SkipWhile() { var ints = new[] { 1, 2, 3, 4, 5 }.SkipWhile(x => x < 3).ToArray(); AssertEquals(ints.Length, 3); AssertEquals(ints[0], 3); AssertEquals(ints[1], 4); AssertEquals(ints[2], 5); } [Test] public void SkipWhileWithIndex() { var ints = new[] { 1, 2, 3, 4, 5 }.SkipWhile((x, i) => i < 3).ToArray(); AssertEquals(ints.Length, 2); AssertEquals(ints[0], 4); AssertEquals(ints[1], 5); } [Test] public void Join() { var ints1 = new[] { 1, 2, 3, 4 }; var ints2 = new[] { 3, 4, 5, 6 }; var join = ints1.Join(ints2, x => x, x => x, (x, y) => x + y).ToArray(); AssertEquals(@join.Length, 2); AssertEquals(@join[0], 6); AssertEquals(@join[1], 8); } [Test] public void Except() { var ints1 = new[] { 1, 2, 3, 4 }; var ints2 = new[] { 3, 4, 5, 6 }; var join = ints1.Except(ints2).ToArray(); AssertEquals(@join.Length, 2); AssertEquals(@join[0], 1); AssertEquals(@join[1], 2); } [Test] public void Single() { var ints1 = new[] { 1 }; var int1 = ints1.Single(); AssertEquals(int1, 1); } [Test] public void SingleThrowsWhenEmpty() { var ints1 = new int[0]; try { var int1 = ints1.Single(); AssertTrue(false); } catch (Exception e) { AssertTrue(true); } } [Test] public void SumInt() { var ints = new[] { 1, 2, 3 }; var sum = ints.Sum(); AssertEquals(sum, 6); } [Test] public void SingleThrowsWhenContainsMany() { var ints1 = new[] { 1, 2 }; try { var int1 = ints1.Single(); AssertTrue(false); } catch (Exception e) { AssertTrue(true); } } [Test] public void Reverse() { var ints = new[] { 1, 2, 3 }; var reverse = ints.Reverse().ToArray(); AssertEquals(reverse.Length, 3); AssertEquals(reverse[0], 3); AssertEquals(reverse[1], 2); AssertEquals(reverse[2], 1); } [Test] public void ToDictionary() { var items = new[] { new DictionaryClass { Name = "John", Value = "Austria" }, new DictionaryClass { Name = "Gary", Value = "California" } }; var dictionary = items.ToDictionary(x => x.Name, x => x.Value); AssertEquals(dictionary["John"], "Austria"); AssertEquals(dictionary["Gary"], "California"); } [Test] public void SequenceEqual() { var ints1 = new[] { 1, 2, 3 }; var ints2 = new[] { 1, 2, 3 }; AssertTrue(ints1.SequenceEqual(ints2)); } [Test] public void Last() { var ints = new[] { 1, 2, 3, 4 }; var last = ints.Last(); AssertEquals(last, 4); } [Test] public void OfType() { var objects = new object[] { 1, "5", 5d, "8" }; var strings = objects.OfType<string>().ToArray(); AssertEquals(strings[0], "5"); AssertEquals(strings[1], "8"); } [Test] public void OrderBy() { var list = new[] { 8, 53, 1, 888, 444, 234, 3 }.OrderBy(x => x).ToArray(); AssertEquals(list[0], 1); AssertEquals(list[1], 3); AssertEquals(list[2], 8); AssertEquals(list[3], 53); AssertEquals(list[4], 234); AssertEquals(list[5], 444); AssertEquals(list[6], 888); } [Test] public void OrderByDescending() { var list = new[] { 8, 53, 1 }.OrderByDescending(x => x).ToArray(); AssertEquals(list[0], 53); AssertEquals(list[1], 8); AssertEquals(list[2], 1); } [Test] public void ThenBy() { var list = new[] { new KeyValueClass { Key = "a", Value = 2 }, new KeyValueClass { Key = "a", Value = 1 }, new KeyValueClass { Key = "b", Value = 1 }, new KeyValueClass { Key = "c", Value = 3 }, new KeyValueClass { Key = "c", Value = 4 }, new KeyValueClass { Key = "c", Value = 1 }, }.OrderBy(x => x.Key).ThenBy(x => x.Value).ToArray(); AssertEquals(list[0].Key, "a"); AssertEquals(list[0].Value, 1); AssertEquals(list[1].Key, "a"); AssertEquals(list[1].Value, 2); AssertEquals(list[2].Key, "b"); AssertEquals(list[2].Value, 1); AssertEquals(list[3].Key, "c"); AssertEquals(list[3].Value, 1); AssertEquals(list[4].Key, "c"); AssertEquals(list[4].Value, 3); AssertEquals(list[5].Key, "c"); AssertEquals(list[5].Value, 4); } [Test] public void ThenByDescending() { var list = new[] { new KeyValueClass { Key = "a", Value = 2 }, new KeyValueClass { Key = "a", Value = 1 }, new KeyValueClass { Key = "b", Value = 1 }, new KeyValueClass { Key = "c", Value = 3 }, new KeyValueClass { Key = "c", Value = 4 }, new KeyValueClass { Key = "c", Value = 1 } }.OrderBy(x => x.Key).ThenByDescending(x => x.Value).ToArray(); AssertEquals(list[0].Key, "a"); AssertEquals(list[0].Value, 2); AssertEquals(list[1].Key, "a"); AssertEquals(list[1].Value, 1); AssertEquals(list[2].Key, "b"); AssertEquals(list[2].Value, 1); AssertEquals(list[3].Key, "c"); AssertEquals(list[3].Value, 4); AssertEquals(list[4].Key, "c"); AssertEquals(list[4].Value, 3); AssertEquals(list[5].Key, "c"); AssertEquals(list[5].Value, 1); } [Test] public void Empty() { var enumerator = Enumerable.Empty<string>().GetEnumerator(); AssertTrue((!enumerator.MoveNext())); } [Test] public void DefaultIfEmpty() { var s = new string[0].DefaultIfEmpty().Single(); AssertEquals(s, null); var i = new int[0].DefaultIfEmpty().Single(); AssertEquals(i, 0); } [Test] public void DefaultIfEmptyExplicitDefault() { var s = new string[0].DefaultIfEmpty("default").Single(); AssertEquals(s, "default"); var i = new int[0].DefaultIfEmpty(5).Single(); AssertEquals(i, 5); } [Test] public void GroupBy() { var items = new[] { new KeyValueClass { Key = "a", Value = 2 }, new KeyValueClass { Key = "a", Value = 1 }, new KeyValueClass { Key = "b", Value = 1 }, new KeyValueClass { Key = "c", Value = 3 }, new KeyValueClass { Key = "c", Value = 4 }, new KeyValueClass { Key = "c", Value = 1 }, }; var groups = items.GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToArray()); var a = groups["a"]; var b = groups["b"]; var c = groups["c"]; AssertEquals(a[0], 2); AssertEquals(a[1], 1); AssertEquals(b[0], 1); AssertEquals(c[0], 3); AssertEquals(c[1], 4); AssertEquals(c[2], 1); } [Test] public void ToLookup() { var items = new[] { new KeyValueClass { Key = "a", Value = 2 }, new KeyValueClass { Key = "a", Value = 1 }, new KeyValueClass { Key = "b", Value = 1 }, new KeyValueClass { Key = "c", Value = 3 }, new KeyValueClass { Key = "c", Value = 4 }, new KeyValueClass { Key = "c", Value = 1 }, }; var groups = items.ToLookup(x => x.Key); var a = groups["a"].Select(x => x.Value).ToArray(); var b = groups["b"].Select(x => x.Value).ToArray(); var c = groups["c"].Select(x => x.Value).ToArray(); AssertEquals(a[0], 2); AssertEquals(a[1], 1); AssertEquals(b[0], 1); AssertEquals(c[0], 3); AssertEquals(c[1], 4); AssertEquals(c[2], 1); } [Test] public void Distinct() { var items = new[] { 1, 3, 6, 3, 4, 1 }; var distinct = items.Distinct().ToArray(); AssertEquals(distinct.Length, 4); AssertEquals(distinct[0], 1); AssertEquals(distinct[1], 3); AssertEquals(distinct[2], 6); AssertEquals(distinct[3], 4); } [Test] public void ElementAt() { var items = new[] { 0, 1, 2 }; AssertEquals(items.ElementAt(0), 0); AssertEquals(items.ElementAt(1), 1); AssertEquals(items.ElementAt(2), 2); } [Test] public void ElementAtOrDefault() { var items = new[] { 0, 1, 2 }; AssertEquals(items.ElementAtOrDefault(0), 0); AssertEquals(items.ElementAtOrDefault(1), 1); AssertEquals(items.ElementAtOrDefault(2), 2); AssertEquals(items.ElementAtOrDefault(3), 0); } [Test] public void Zip() { var ints1 = new[] { 1, 2, 3 }; var ints2 = new[] { 4, 5, 6 }; var zipped = ints1.Zip(ints2, (x, y) => new { x, y }).ToArray(); AssertEquals(zipped[0].x, 1); AssertEquals(zipped[0].y, 4); AssertEquals(zipped[1].x, 2); AssertEquals(zipped[1].y, 5); AssertEquals(zipped[2].x, 3); AssertEquals(zipped[2].y, 6); } [Test] public void Union() { var union = new[] { 1, 1, 2 }.Union(new[] { 1, 2, 2, 3 }).ToArray(); AssertEquals(union.Length, 3); AssertEquals(union[0], 1); AssertEquals(union[1], 2); AssertEquals(union[2], 3); } [Test] public void Intersect() { var intersection = new[] { 1, 1, 2 }.Intersect(new[] { 1, 2, 2, 3 }).ToArray(); AssertEquals(intersection.Length, 2); AssertEquals(intersection[0], 1); AssertEquals(intersection[1], 2); } [Test] public void AverageDouble() { AssertEquals(new double[] { 1, 2, 3, 4, 5, 6, 7 }.Average(), 4); AssertEquals(new double[] { 1, 2, 3, 4, 5, 6 }.Average(), 3.5); } [Test] public void AverageInt() { AssertEquals(new[] { 1, 2, 3, 4, 5, 6, 7 }.Average(), 4); AssertEquals(new[] { 1, 2, 3, 4, 5, 6 }.Average(), 3.5); } [Test] public void Count() { var values = new[] { 1, 2, 3, 4, 5 }; AssertEquals(values.Count(), 5); } [Test] public void Contains() { IEnumerable<string> values = new[] { "one", "two", "three" }; AssertTrue(values.Contains("one")); AssertTrue(values.Contains("two")); AssertTrue(values.Contains("three")); } public class DictionaryClass { public string Name { get; set; } public string Value { get; set; } } public class KeyValueClass { public string Key { get; set; } public int Value { get; set; } } } }
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime; using System.Threading; using System.Threading.Tasks; namespace Rothko.Net.Http { public interface IHttpClient : IDisposable { /// <summary> /// Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<string> GetStringAsync(string requestUri); /// <summary> /// Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<string> GetStringAsync(Uri requestUri); /// <summary> /// Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<byte[]> GetByteArrayAsync(string requestUri); /// <summary> /// Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<byte[]> GetByteArrayAsync(Uri requestUri); /// <summary> /// Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<Stream> GetStreamAsync(string requestUri); /// <summary> /// Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<Stream> GetStreamAsync(Uri requestUri); /// <summary> /// Send a GET request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> GetAsync(string requestUri); /// <summary> /// Send a GET request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] Task<HttpResponseMessage> GetAsync(Uri requestUri); /// <summary> /// Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption); /// <summary> /// Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption); /// <summary> /// Send a GET request to the specified Uri with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken); /// <summary> /// Send a GET request to the specified Uri with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken); /// <summary> /// Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken); /// <summary> /// Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken); /// <summary> /// Send a POST request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content); /// <summary> /// Send a POST request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content); /// <summary> /// Send a POST request with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, CancellationToken cancellationToken); /// <summary> /// Send a POST request with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken); /// <summary> /// Send a PUT request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content); /// <summary> /// Send a PUT request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content); /// <summary> /// Send a PUT request with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, CancellationToken cancellationToken); /// <summary> /// Send a PUT request with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="content">The HTTP request content sent to the server.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception> Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken); /// <summary> /// Send a DELETE request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> Task<HttpResponseMessage> DeleteAsync(string requestUri); /// <summary> /// Send a DELETE request to the specified Uri as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> Task<HttpResponseMessage> DeleteAsync(Uri requestUri); /// <summary> /// Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken); /// <summary> /// Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="requestUri">The Uri the request is sent to.</param><param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="requestUri"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken); /// <summary> /// Send an HTTP request as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="request">The HTTP request message to send.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> Task<HttpResponseMessage> SendAsync(HttpRequestMessage request); /// <summary> /// Send an HTTP request as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="request">The HTTP request message to send.</param><param name="cancellationToken">The cancellation token to cancel operation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken); /// <summary> /// Send an HTTP request as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="request">The HTTP request message to send.</param><param name="completionOption">When the operation should complete (as soon as a response is available or after reading the whole response content).</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption); /// <summary> /// Send an HTTP request as an asynchronous operation. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>.The task object representing the asynchronous operation. /// </returns> /// <param name="request">The HTTP request message to send.</param><param name="completionOption">When the operation should complete (as soon as a response is available or after reading the whole response content).</param><param name="cancellationToken">The cancellation token to cancel operation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> was null.</exception><exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient"/> instance.</exception> Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken); /// <summary> /// Cancel all pending requests on this instance. /// </summary> void CancelPendingRequests(); /// <summary> /// Gets the headers which should be sent with each request. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Net.Http.Headers.HttpRequestHeaders"/>.The headers which should be sent with each request. /// </returns> HttpRequestHeaders DefaultRequestHeaders { get; } /// <summary> /// Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Uri"/>.The base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests. /// </returns> Uri BaseAddress { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; } /// <summary> /// Gets or sets the number of milliseconds to wait before the request times out. /// </summary> /// /// <returns> /// Returns <see cref="T:System.TimeSpan"/>.The number of milliseconds to wait before the request times out. /// </returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The timeout specified is less than or equal to zero and is not <see cref="F:System.Threading.Timeout.Infinite"/>.</exception><exception cref="T:System.InvalidOperationException">An operation has already been started on the current instance. </exception><exception cref="T:System.ObjectDisposedException">The current instance has been disposed.</exception> TimeSpan Timeout { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; } /// <summary> /// Gets or sets the maximum number of bytes to buffer when reading the response content. /// </summary> /// /// <returns> /// Returns <see cref="T:System.Int32"/>.The maximum number of bytes to buffer when reading the response content. The default value for this property is 2 gigabytes. /// </returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The size specified is less than or equal to zero.</exception><exception cref="T:System.InvalidOperationException">An operation has already been started on the current instance. </exception><exception cref="T:System.ObjectDisposedException">The current instance has been disposed. </exception> long MaxResponseContentBufferSize { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; } } }
// 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.IO; using System.Collections.Generic; using Microsoft.Win32; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// This public class is used for reading event records from event log. /// </summary> public class EventLogReader : IDisposable { private readonly EventLogQuery _eventQuery; private int _batchSize; // // access to the data member reference is safe, while // invoking methods on it is marked SecurityCritical as appropriate. // private readonly EventLogHandle _handle; /// <summary> /// events buffer holds batched event (handles). /// </summary> private IntPtr[] _eventsBuffer; /// <summary> /// The current index where the function GetNextEvent is (inside the eventsBuffer). /// </summary> private int _currentIndex; /// <summary> /// The number of events read from the batch into the eventsBuffer /// </summary> private int _eventCount; /// <summary> /// When the reader finishes (will always return only ERROR_NO_MORE_ITEMS). /// For subscription, this means we need to wait for next event. /// </summary> private bool _isEof; /// <summary> /// Maintains cached display / metadata information returned from /// EventRecords that were obtained from this reader. /// </summary> private readonly ProviderMetadataCachedInformation _cachedMetadataInformation; public EventLogReader(string path) : this(new EventLogQuery(path, PathType.LogName), null) { } public EventLogReader(string path, PathType pathType) : this(new EventLogQuery(path, pathType), null) { } public EventLogReader(EventLogQuery eventQuery) : this(eventQuery, null) { } public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark) { if (eventQuery == null) throw new ArgumentNullException(nameof(eventQuery)); string logfile = null; if (eventQuery.ThePathType == PathType.FilePath) logfile = eventQuery.Path; _cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, logfile, 50); // Explicit data _eventQuery = eventQuery; // Implicit _batchSize = 64; _eventsBuffer = new IntPtr[_batchSize]; // // compute the flag. // int flag = 0; if (_eventQuery.ThePathType == PathType.LogName) flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath; else flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath; if (_eventQuery.ReverseDirection) flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryReverseDirection; if (_eventQuery.TolerateQueryErrors) flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryTolerateQueryErrors; _handle = NativeWrapper.EvtQuery(_eventQuery.Session.Handle, _eventQuery.Path, _eventQuery.Query, flag); EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark); if (!bookmarkHandle.IsInvalid) { using (bookmarkHandle) { NativeWrapper.EvtSeek(_handle, 1, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark); } } } public int BatchSize { get { return _batchSize; } set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value)); _batchSize = value; } } private bool GetNextBatch(TimeSpan ts) { int timeout = -1; if (ts != TimeSpan.MaxValue) timeout = (int)ts.TotalMilliseconds; // batchSize was changed by user, reallocate buffer. if (_batchSize != _eventsBuffer.Length) _eventsBuffer = new IntPtr[_batchSize]; int newEventCount = 0; bool results = NativeWrapper.EvtNext(_handle, _batchSize, _eventsBuffer, timeout, 0, ref newEventCount); if (!results) { _eventCount = 0; _currentIndex = 0; return false; // No more events in the result set } _currentIndex = 0; _eventCount = newEventCount; return true; } public EventRecord ReadEvent() { return ReadEvent(TimeSpan.MaxValue); } public EventRecord ReadEvent(TimeSpan timeout) { if (_isEof) throw new InvalidOperationException(); if (_currentIndex >= _eventCount) { // buffer is empty, get next batch. GetNextBatch(timeout); if (_currentIndex >= _eventCount) { _isEof = true; return null; } } EventLogRecord eventInstance = new EventLogRecord(new EventLogHandle(_eventsBuffer[_currentIndex], true), _eventQuery.Session, _cachedMetadataInformation); _currentIndex++; return eventInstance; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { while (_currentIndex < _eventCount) { NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]); _currentIndex++; } if (_handle != null && !_handle.IsInvalid) _handle.Dispose(); } internal void SeekReset() { // // Close all unread event handles in the buffer // while (_currentIndex < _eventCount) { NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]); _currentIndex++; } // Reset the indexes used by Next _currentIndex = 0; _eventCount = 0; _isEof = false; } internal void SeekCommon(long offset) { // // modify offset that we're going to send to service to account for the // fact that we've already read some events in our buffer that the user // hasn't seen yet. // offset = offset - (_eventCount - _currentIndex); SeekReset(); NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToCurrent); } public void Seek(EventBookmark bookmark) { Seek(bookmark, 0); } public void Seek(EventBookmark bookmark, long offset) { if (bookmark == null) throw new ArgumentNullException(nameof(bookmark)); SeekReset(); using (EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark)) { NativeWrapper.EvtSeek(_handle, offset, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark); } } public void Seek(SeekOrigin origin, long offset) { switch (origin) { case SeekOrigin.Begin: SeekReset(); NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToFirst); return; case SeekOrigin.End: SeekReset(); NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToLast); return; case SeekOrigin.Current: if (offset >= 0) { // We can reuse elements in the batch. if (_currentIndex + offset < _eventCount) { // // We don't call Seek here, we can reposition within the batch. // // Close all event handles between [currentIndex, currentIndex + offset) int index = _currentIndex; while (index < _currentIndex + offset) { NativeWrapper.EvtClose(_eventsBuffer[index]); index++; } _currentIndex = (int)(_currentIndex + offset); // Leave the eventCount unchanged // Leave the same Eof } else { SeekCommon(offset); } } else { SeekCommon(offset); } return; } } public void CancelReading() { NativeWrapper.EvtCancel(_handle); } public IList<EventLogStatus> LogStatus { get { List<EventLogStatus> list = null; string[] channelNames = null; int[] errorStatuses = null; EventLogHandle queryHandle = _handle; if (queryHandle.IsInvalid) throw new InvalidOperationException(); channelNames = (string[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames); errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses); if (channelNames.Length != errorStatuses.Length) throw new InvalidOperationException(); list = new List<EventLogStatus>(channelNames.Length); for (int i = 0; i < channelNames.Length; i++) { EventLogStatus cs = new EventLogStatus(channelNames[i], errorStatuses[i]); list.Add(cs); } return list.AsReadOnly(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Transactions; using PCSComMaterials.Inventory.DS; using PCSComProduction.DCP.DS; using PCSComUtils.Common; using PCSComUtils.Common.DS; using PCSComUtils.DataAccess; using PCSComUtils.DataContext; using PCSComUtils.PCSExc; namespace PCSComProduction.DCP.BO { public class DCPReportBO { private const string THIS = "PCSComProduction.DCP.BO.DCPReportBO"; /// <summary> /// Gets Cycle Detail from Master /// </summary> /// <param name="pintCycleMasterID">Cycle Master ID</param> /// <returns>Cycle Detail</returns> public DataTable GetCycleDetail(int pintCycleMasterID) { PRO_DCOptionDetailDS dsDetail = new PRO_DCOptionDetailDS(); return dsDetail.GetDetailByMaster(pintCycleMasterID).Tables[0]; } /// <summary> /// Gets all Production Line /// </summary> /// <param name="pintCCNID">CCN</param> /// <returns>DataTable</returns> public DataTable GetAllProductionLine(int pintCCNID) { PRO_ProductionLineDS dsProductionLine = new PRO_ProductionLineDS(); return dsProductionLine.List(pintCCNID); } public DataTable GetTotalWO(string pstrCCNID) { DCPReportDS dsDCPReport = new DCPReportDS(); return dsDCPReport.GetTotalWO(pstrCCNID); } /// <summary> /// Gets working time of work center /// </summary> /// <param name="pintProductionLineID">Production Line</param> /// <returns>DataTable</returns> public DataTable GetWorkingTime(int pintProductionLineID) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetWorkingTime(pintProductionLineID); } /// <summary> /// Gets working time of work center /// </summary> /// <returns>DataTable</returns> public DataTable GetWorkingTime() { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetWorkingTime(); } public ArrayList GetWorkingDayByYear(int pintYear) { UtilsDS dsUtil = new UtilsDS(); return dsUtil.GetWorkingDayByYear(pintYear); } public ArrayList GetHolidaysInYear(int pintYear) { UtilsDS dsUtils = new UtilsDS(); return dsUtils.GetHolidaysInYear(pintYear); } public DataTable ListProductionLine() { DCPReportDS dsReport = new DCPReportDS(); return dsReport.ListProductionLine(); } public DataTable ListProduct(string pstrCCNID, string pstrProductionLineList) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.ListProduct(pstrCCNID, pstrProductionLineList); } public DataTable GetPlanningOffset(string pstrCCNID) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetPlanningOffset(pstrCCNID); } public DataTable GetBeginStockForReportData() { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetBeginStockForReportData(); } public DataTable GetBeginNetQuantity(string pstrCCNID) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetBeginNetQuantity(pstrCCNID); } public DataTable GetTransactionHistory() { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetTransactionHistory(); } public DataTable GetDeliveryForSO() { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetDeliveryForSO(); } public DataTable GetProduce() { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetProduce(); } public DataTable GetDeliveryForParent(string pstrCCNID) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetDemandWO(pstrCCNID); } public DataTable GetWorkingDateFromWCCapacity(int pintProductionLineID) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetWorkingDateFromWCCapacity(pintProductionLineID); } public ArrayList GetPlanningPeriod(string pstrCCNID) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetPlanningPeriod(pstrCCNID); } public DataTable GetCycles(string pstrCCNID) { DCPReportDS dsReport = new DCPReportDS(); return dsReport.GetCycles(pstrCCNID); } public void UpdateBeginStockData(DataSet pdstData) { DCPReportDS dsReport = new DCPReportDS(); dsReport.UpdateBeginStockData(pdstData); } public object GetCyclerMasterObject(int pintMasterID) { PRO_DCOptionMasterDS dsOption = new PRO_DCOptionMasterDS(); DataRow drowData = dsOption.GetDCOptionMaster(pintMasterID); PRO_DCOptionMasterVO voOption = new PRO_DCOptionMasterVO(); try { voOption.DCOptionMasterID = Convert.ToInt32(drowData[PRO_DCOptionMasterTable.DCOPTIONMASTERID_FLD]); } catch{} try { voOption.AsOfDate = Convert.ToDateTime(drowData[PRO_DCOptionMasterTable.ASOFDATE_FLD]); } catch{} try { voOption.UseCacheAsBegin = Convert.ToBoolean(drowData[PRO_DCOptionMasterTable.USECACHE_ASBEGIN_FLD]); } catch{} voOption.CCNID = Convert.ToInt32(drowData[PRO_DCOptionMasterTable.CCNID_FLD]); try { voOption.LastUpdate = Convert.ToDateTime(drowData[PRO_DCOptionMasterTable.LASTUPDATE_FLD]); } catch{} try { voOption.PlanHorizon = Convert.ToInt32(drowData[PRO_DCOptionMasterTable.PLANHORIZON_FLD]); } catch{} try { voOption.PlanningPeriod = Convert.ToDateTime(drowData[PRO_DCOptionMasterTable.PLANNINGPERIOD_FLD]); } catch{} try { voOption.Version = Convert.ToInt32(drowData[PRO_DCOptionMasterTable.VERSION_FLD]); } catch{} return voOption; } /// <summary> /// Get begin data of cycle /// </summary> /// <param name="pintCycleId"></param> /// <returns></returns> public DataTable GetBeginData(int pintCycleId) { PRO_DCOptionMasterDS dsDCOptionMaster = new PRO_DCOptionMasterDS(); return dsDCOptionMaster.GetBeginData(pintCycleId); } /// <summary> /// Get begin balance in OK and Buffer bin /// </summary> /// <param name="pdtmMonth">Effect date</param> /// <returns></returns> public DataTable GetBeginBalance(DateTime pdtmMonth) { IV_BalanceBinDS dsBalance = new IV_BalanceBinDS(); return dsBalance.GetBeginBalance(pdtmMonth); } /// <summary> /// get begin stock of selected date /// </summary> /// <param name="date"></param> /// <returns></returns> public List<IV_BeginDCPReport> GetBeginStock(DateTime date) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); // get begin stock of previous month and current month return dataContext.IV_BeginDCPReports.Where(b => b.EffectDate == date).ToList(); } public PRO_PlanningOffset GetPlanningOffset(int cycleId) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); return dataContext.PRO_PlanningOffsets.FirstOrDefault(b => b.DCOptionMasterID == cycleId); } public List<PRO_DCOptionMaster> ListCycle(DateTime year) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); return dataContext.PRO_DCOptionMasters.Where(c => c.AsOfDate.GetValueOrDefault(DateTime.Now).Year == year.Year).ToList(); } public List<PRO_ProductionLine> GetProductionLine() { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); return dataContext.PRO_ProductionLines.ToList(); } public List<ITM_Product> ListProduct(List<int> productionLines) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); var result = new List<ITM_Product>(); foreach (var productionLine in productionLines) { result.AddRange(dataContext.ITM_Products.Where(p => p.ProductionLineID == productionLine)); } return result; } public List<DeliveryScheduleData> GetDeliveryForParent(DateTime fromDate, DateTime toDate) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); var query = from dcpDetail in dataContext.PRO_DCPResultDetails join dcpMaster in dataContext.PRO_DCPResultMasters on dcpDetail.DCPResultMasterID equals dcpMaster.DCPResultMasterID join optionMaster in dataContext.PRO_DCOptionMasters on dcpMaster.DCOptionMasterID equals optionMaster.DCOptionMasterID join bom in dataContext.ITM_BOMs on dcpMaster.ProductID equals bom.ProductID join workCenter in dataContext.MST_WorkCenters on dcpMaster.WorkCenterID equals workCenter.WorkCenterID where optionMaster.AsOfDate <= toDate && optionMaster.AsOfDate >= fromDate select new DeliveryScheduleData { Quantity = (dcpDetail.Quantity * bom.Quantity.GetValueOrDefault(0)) / ((100 - bom.Shrink.GetValueOrDefault(0)) / 100), ProductId = bom.ComponentID, ScheduleDate = dcpDetail.WorkingDate.GetValueOrDefault(DateTime.Now), StartTime = dcpDetail.StartTime, EndTime = dcpDetail.EndTime, LeadTime = bom.LeadTimeOffset, WorkCenterId = workCenter.WorkCenterID }; return query.ToList(); } public List<PRO_WCCapacity> GetWorkingDateFromWCCapacity(List<int> productionLineId) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); var query = from wcCapacity in dataContext.PRO_WCCapacities join workCenter in dataContext.MST_WorkCenters on wcCapacity.WorkCenterID equals workCenter.WorkCenterID where workCenter.IsMain.GetValueOrDefault(false) && productionLineId.Contains(workCenter.ProductionLineID.GetValueOrDefault(0)) select wcCapacity; return query.ToList(); } public List<DeliveryScheduleData> GetDeliveryForSale(DateTime fromDate, DateTime toDate) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); var query = dataContext.SO_DeliverySchedules.Where(d => d.ScheduleDate >= fromDate && d.ScheduleDate < toDate).Select( d => new DeliveryScheduleData {ProductId = d.SO_SaleOrderDetail.ProductID, Quantity = (decimal)d.DeliveryQuantity}); return query.ToList(); } public List<DeliveryScheduleData> GetProduce(DateTime fromDate, DateTime toDate) { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); var query = from dcpDetail in dataContext.PRO_DCPResultDetails join dcpMaster in dataContext.PRO_DCPResultMasters on dcpDetail.DCPResultMasterID equals dcpMaster.DCPResultMasterID join optionMaster in dataContext.PRO_DCOptionMasters on dcpMaster.DCOptionMasterID equals optionMaster.DCOptionMasterID join workCenter in dataContext.MST_WorkCenters on dcpMaster.WorkCenterID equals workCenter.WorkCenterID where optionMaster.AsOfDate <= toDate && optionMaster.AsOfDate >= fromDate select new DeliveryScheduleData { Quantity = dcpDetail.Quantity, ProductId = dcpMaster.ProductID.GetValueOrDefault(0), StartTime = dcpDetail.StartTime, EndTime = dcpDetail.EndTime }; return query.ToList(); } /// <summary> /// Gets the working time. /// </summary> /// <returns></returns> public List<PRO_ShiftPattern> ListWorkingTime() { var dataContext = new PCSDataContext(Utils.Instance.ConnectionString); var shiftDesc = new[] { "1S", "2S", "3S" }; return (from pattern in dataContext.PRO_ShiftPatterns join shift in dataContext.PRO_Shifts on pattern.ShiftID equals shift.ShiftID where shiftDesc.Contains(shift.ShiftDesc) select pattern).ToList(); } public void UpdateBeginStock(List<IV_BeginDCPReport> beginDcp, DateTime effectDate, List<ITM_Product> productList) { const string methodName = THIS + ".UpdateBeginStock()"; try { using (var trans = new TransactionScope()) { using (var dataContext = new PCSDataContext(Utils.Instance.ConnectionString)) { var productids = productList.Select(p => p.ProductID.ToString()).ToArray(); var query = string.Join(",", productids); var deleteCommand = string.Format("DELETE FROM IV_BeginDCPReport WHERE effectDate = '{0}' AND ProductID IN ({1})", effectDate.ToString("yyyy-MM-dd"), query); dataContext.ExecuteCommand(deleteCommand); dataContext.IV_BeginDCPReports.InsertAllOnSubmit(beginDcp); // submit changes dataContext.SubmitChanges(); trans.Complete(); } } } catch (SqlException ex) { if (ex.Errors.Count > 1) { if (ex.Number == ErrorCode.SQLDUPLICATE_KEYCODE) throw new PCSDBException(ErrorCode.DUPLICATE_KEY, methodName, ex); throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex); } throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Land { public class LandChannel : ILandChannel { #region Constants //Land types set with flags in ParcelOverlay. //Only one of these can be used. public const float BAN_LINE_SAFETY_HEIGHT = 5000; // min height over land if explicitly banned public const float NON_PUBLIC_SAFETY_HEIGHT = 50; // min height over land for non-public parcels public const byte LAND_FLAG_PROPERTY_BORDER_SOUTH = 128; //Equals 10000000 public const byte LAND_FLAG_PROPERTY_BORDER_WEST = 64; //Equals 01000000 //RequestResults (I think these are right, they seem to work): public const int LAND_RESULT_MULTIPLE = 1; // The request they made contained more than a single peice of land public const int LAND_RESULT_SINGLE = 0; // The request they made contained only a single piece of land //ParcelSelectObjects public const int LAND_SELECT_OBJECTS_GROUP = 4; public const int LAND_SELECT_OBJECTS_OTHER = 8; public const int LAND_SELECT_OBJECTS_OWNER = 2; public const byte LAND_TYPE_IS_BEING_AUCTIONED = 5; //Equals 00000101 public const byte LAND_TYPE_IS_FOR_SALE = 4; //Equals 00000100 public const byte LAND_TYPE_OWNED_BY_GROUP = 2; //Equals 00000010 public const byte LAND_TYPE_OWNED_BY_OTHER = 1; //Equals 00000001 public const byte LAND_TYPE_OWNED_BY_REQUESTER = 3; //Equals 00000011 public const byte LAND_TYPE_PUBLIC = 0; //Equals 00000000 // Other parcel overlay flags public const byte LAND_SOUND_LOCAL = 32; //Equals 00100000 //These are other constants. Yay! public const int START_LAND_LOCAL_ID = 1; #endregion private readonly Scene m_scene; private readonly LandManagementModule m_landManagementModule; public LandChannel(Scene scene, LandManagementModule landManagementMod) { m_scene = scene; m_landManagementModule = landManagementMod; } #region ILandChannel Members public ILandObject GetLandObject(float x_float, float y_float) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x_float, y_float); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.landData.Name = "NO LAND"; return obj; } public ILandObject GetNearestLandObjectInRegion(float x_float, float y_float) { if (m_landManagementModule != null) { return m_landManagementModule.GetNearestLandObjectInRegion(x_float, y_float); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.landData.Name = "NO LAND"; return obj; } public ILandObject GetLandObject(int localID) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(localID); } return null; } public ILandObject GetLandObject(int x, int y) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x, y); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.landData.Name = "NO LAND"; return obj; } public List<ILandObject> AllParcels() { if (m_landManagementModule != null) { return m_landManagementModule.AllParcels(); } return new List<ILandObject>(); } public List<ILandObject> ParcelsNearPoint(Vector3 position) { if (m_landManagementModule != null) { return m_landManagementModule.ParcelsNearPoint(position); } return new List<ILandObject>(); } public bool IsLandPrimCountTainted() { if (m_landManagementModule != null) { return m_landManagementModule.IsLandPrimCountTainted(); } return false; } public bool IsForcefulBansAllowed() { if (m_landManagementModule != null) { return m_landManagementModule.AllowedForcefulBans; } return false; } public float GetBanHeight(bool isBanned) { if (m_landManagementModule != null) { return isBanned ? m_landManagementModule.BanHeight : m_landManagementModule.NonPublicHeight; } return 0.0f; } public void UpdateLandObject(int localID, LandData data) { if (m_landManagementModule != null) { m_landManagementModule.UpdateLandObject(localID, data); } } public void RemoveAvatarFromParcel(UUID userID) { if (m_landManagementModule != null) { m_landManagementModule.RemoveAvatarFromParcel(userID); } } public void UpdateLandPrimCounts() { if (m_landManagementModule != null) { m_landManagementModule.UpdateLandPrimCounts(); } } public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { if (m_landManagementModule != null) { m_landManagementModule.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); } } public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setParcelObjectMaxOverride(overrideDel); } } public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setSimulatorObjectMaxOverride(overrideDel); } } public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) { if (m_landManagementModule != null) { m_landManagementModule.setParcelOtherCleanTime(remoteClient, localID, otherCleanTime); } } public void RefreshParcelInfo(IClientAPI remoteClient, bool force) { if (m_landManagementModule != null) { m_landManagementModule.RefreshParcelInfo(remoteClient, force); } } // Region support for Plus parcel web updates public LandData ClaimPlusParcel(UUID parcelID, UUID userID) { LandData parcel = null; if (m_landManagementModule != null) { parcel = m_landManagementModule.ClaimPlusParcel(parcelID, userID); } return parcel; } public LandData AbandonPlusParcel(UUID parcelID) { LandData parcel = null; if (m_landManagementModule != null) { parcel = m_landManagementModule.AbandonPlusParcel(parcelID); } return parcel; } #endregion } }
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt) using System; using UnityEngine; namespace UnityEditor { public class StandardShaderVCGUI : ShaderGUI { private enum WorkflowMode { Specular, Metallic, Dielectric } public enum BlendMode { Opaque, Cutout, Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply } public enum SmoothnessMapChannel { SpecularMetallicAlpha, AlbedoAlpha, } private static class Styles { public static GUIContent uvSetLabel = new GUIContent("UV Set"); public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)"); public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff"); public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)"); public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)"); public static GUIContent smoothnessText = new GUIContent("Smoothness", "Smoothness value"); public static GUIContent smoothnessScaleText = new GUIContent("Smoothness", "Smoothness scale factor"); public static GUIContent smoothnessMapChannelText = new GUIContent("Source", "Smoothness texture and channel"); public static GUIContent highlightsText = new GUIContent("Specular Highlights", "Specular Highlights"); public static GUIContent reflectionsText = new GUIContent("Reflections", "Glossy Reflections"); public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map"); public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)"); public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)"); public static GUIContent emissionText = new GUIContent("Color", "Emission (RGB)"); public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)"); public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2"); public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map"); public static string primaryMapsText = "Main Maps"; public static string secondaryMapsText = "Secondary Maps"; public static string forwardText = "Forward Rendering Options"; public static string renderingMode = "Rendering Mode"; public static string advancedText = "Advanced Options"; public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive."); public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode)); public static GUIContent vcLabel = new GUIContent("Vertex Color", "Vertex Color Intensity"); } MaterialProperty blendMode = null; MaterialProperty albedoMap = null; MaterialProperty albedoColor = null; MaterialProperty alphaCutoff = null; MaterialProperty specularMap = null; MaterialProperty specularColor = null; MaterialProperty metallicMap = null; MaterialProperty metallic = null; MaterialProperty smoothness = null; MaterialProperty smoothnessScale = null; MaterialProperty smoothnessMapChannel = null; MaterialProperty highlights = null; MaterialProperty reflections = null; MaterialProperty bumpScale = null; MaterialProperty bumpMap = null; MaterialProperty occlusionStrength = null; MaterialProperty occlusionMap = null; MaterialProperty heigtMapScale = null; MaterialProperty heightMap = null; MaterialProperty emissionColorForRendering = null; MaterialProperty emissionMap = null; MaterialProperty detailMask = null; MaterialProperty detailAlbedoMap = null; MaterialProperty detailNormalMapScale = null; MaterialProperty detailNormalMap = null; MaterialProperty uvSetSecondary = null; MaterialProperty vertexColor = null; MaterialEditor m_MaterialEditor; WorkflowMode m_WorkflowMode = WorkflowMode.Specular; ColorPickerHDRConfig m_ColorPickerHDRConfig = new ColorPickerHDRConfig(0f, 99f, 1 / 99f, 3f); bool m_FirstTimeApply = true; public void FindProperties(MaterialProperty[] props) { blendMode = FindProperty("_Mode", props); albedoMap = FindProperty("_MainTex", props); albedoColor = FindProperty("_Color", props); alphaCutoff = FindProperty("_Cutoff", props); specularMap = FindProperty("_SpecGlossMap", props, false); specularColor = FindProperty("_SpecColor", props, false); metallicMap = FindProperty("_MetallicGlossMap", props, false); metallic = FindProperty("_Metallic", props, false); if (specularMap != null && specularColor != null) m_WorkflowMode = WorkflowMode.Specular; else if (metallicMap != null && metallic != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; smoothness = FindProperty("_Glossiness", props); smoothnessScale = FindProperty("_GlossMapScale", props, false); smoothnessMapChannel = FindProperty("_SmoothnessTextureChannel", props, false); highlights = FindProperty("_SpecularHighlights", props, false); reflections = FindProperty("_GlossyReflections", props, false); bumpScale = FindProperty("_BumpScale", props); bumpMap = FindProperty("_BumpMap", props); heigtMapScale = FindProperty("_Parallax", props); heightMap = FindProperty("_ParallaxMap", props); occlusionStrength = FindProperty("_OcclusionStrength", props); occlusionMap = FindProperty("_OcclusionMap", props); emissionColorForRendering = FindProperty("_EmissionColor", props); emissionMap = FindProperty("_EmissionMap", props); detailMask = FindProperty("_DetailMask", props); detailAlbedoMap = FindProperty("_DetailAlbedoMap", props); detailNormalMapScale = FindProperty("_DetailNormalMapScale", props); detailNormalMap = FindProperty("_DetailNormalMap", props); uvSetSecondary = FindProperty("_UVSec", props); vertexColor = FindProperty("_IntensityVC", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly m_MaterialEditor = materialEditor; Material material = materialEditor.target as Material; // Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing // material to a standard shader. // Do this before any GUI code has been issued to prevent layout issues in subsequent GUILayout statements (case 780071) if (m_FirstTimeApply) { MaterialChanged(material, m_WorkflowMode); m_FirstTimeApply = false; } ShaderPropertiesGUI(material); } public void ShaderPropertiesGUI(Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; // Detect any changes to the material EditorGUI.BeginChangeCheck(); { BlendModePopup(); // Primary properties GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel); DoAlbedoArea(material); DoSpecularMetallicArea(); m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightMap.textureValue != null ? heigtMapScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null); m_MaterialEditor.TexturePropertySingleLine(Styles.detailMaskText, detailMask); DoEmissionArea(material); EditorGUI.BeginChangeCheck(); m_MaterialEditor.TextureScaleOffsetProperty(albedoMap); if (EditorGUI.EndChangeCheck()) emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake EditorGUILayout.Space(); m_MaterialEditor.ShaderProperty(vertexColor, "Vertex Color"); // Secondary properties GUILayout.Label(Styles.secondaryMapsText, EditorStyles.boldLabel); m_MaterialEditor.TexturePropertySingleLine(Styles.detailAlbedoText, detailAlbedoMap); m_MaterialEditor.TexturePropertySingleLine(Styles.detailNormalMapText, detailNormalMap, detailNormalMapScale); m_MaterialEditor.TextureScaleOffsetProperty(detailAlbedoMap); m_MaterialEditor.ShaderProperty(uvSetSecondary, Styles.uvSetLabel.text); // Third properties GUILayout.Label(Styles.forwardText, EditorStyles.boldLabel); if (highlights != null) m_MaterialEditor.ShaderProperty(highlights, Styles.highlightsText); if (reflections != null) m_MaterialEditor.ShaderProperty(reflections, Styles.reflectionsText); } if (EditorGUI.EndChangeCheck()) { foreach (var obj in blendMode.targets) MaterialChanged((Material)obj, m_WorkflowMode); } EditorGUILayout.Space(); // NB renderqueue editor is not shown on purpose: we want to override it based on blend mode GUILayout.Label(Styles.advancedText, EditorStyles.boldLabel); m_MaterialEditor.EnableInstancingField(); m_MaterialEditor.DoubleSidedGIField(); } internal void DetermineWorkflow(MaterialProperty[] props) { if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null) m_WorkflowMode = WorkflowMode.Specular; else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; } public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) { // _Emission property is lost after assigning Standard shader to the material // thus transfer it before assigning the new shader if (material.HasProperty("_Emission")) { material.SetColor("_EmissionColor", material.GetColor("_Emission")); } base.AssignNewShaderToMaterial(material, oldShader, newShader); if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/")) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode")); return; } BlendMode blendMode = BlendMode.Opaque; if (oldShader.name.Contains("/Transparent/Cutout/")) { blendMode = BlendMode.Cutout; } else if (oldShader.name.Contains("/Transparent/")) { // NOTE: legacy shaders did not provide physically based transparency // therefore Fade mode blendMode = BlendMode.Fade; } material.SetFloat("_Mode", (float)blendMode); DetermineWorkflow(MaterialEditor.GetMaterialProperties(new Material[] { material })); MaterialChanged(material, m_WorkflowMode); } void BlendModePopup() { EditorGUI.showMixedValue = blendMode.hasMixedValue; var mode = (BlendMode)blendMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); blendMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } void DoAlbedoArea(Material material) { m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); } } void DoEmissionArea(Material material) { // Emission for GI? if (m_MaterialEditor.EmissionEnabledProperty()) { bool hadEmissionTexture = emissionMap.textureValue != null; // Texture and HDR color controls m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionText, emissionMap, emissionColorForRendering, m_ColorPickerHDRConfig, false); // If texture was assigned and color was black set color to white float brightness = emissionColorForRendering.colorValue.maxColorComponent; if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f) emissionColorForRendering.colorValue = Color.white; // change the GI flag and fix it up with emissive as black if necessary m_MaterialEditor.LightmapEmissionFlagsProperty(MaterialEditor.kMiniTextureFieldLabelIndentLevel, true); } } void DoSpecularMetallicArea() { bool hasGlossMap = false; if (m_WorkflowMode == WorkflowMode.Specular) { hasGlossMap = specularMap.textureValue != null; m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap, hasGlossMap ? null : specularColor); } else if (m_WorkflowMode == WorkflowMode.Metallic) { hasGlossMap = metallicMap.textureValue != null; m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap, hasGlossMap ? null : metallic); } bool showSmoothnessScale = hasGlossMap; if (smoothnessMapChannel != null) { int smoothnessChannel = (int)smoothnessMapChannel.floatValue; if (smoothnessChannel == (int)SmoothnessMapChannel.AlbedoAlpha) showSmoothnessScale = true; } int indentation = 2; // align with labels of texture properties m_MaterialEditor.ShaderProperty(showSmoothnessScale ? smoothnessScale : smoothness, showSmoothnessScale ? Styles.smoothnessScaleText : Styles.smoothnessText, indentation); ++indentation; if (smoothnessMapChannel != null) m_MaterialEditor.ShaderProperty(smoothnessMapChannel, Styles.smoothnessMapChannelText, indentation); } public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode) { switch (blendMode) { case BlendMode.Opaque: material.SetOverrideTag("RenderType", ""); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; break; case BlendMode.Cutout: material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; break; case BlendMode.Fade: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; case BlendMode.Transparent: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; } } static SmoothnessMapChannel GetSmoothnessMapChannel(Material material) { int ch = (int)material.GetFloat("_SmoothnessTextureChannel"); if (ch == (int)SmoothnessMapChannel.AlbedoAlpha) return SmoothnessMapChannel.AlbedoAlpha; else return SmoothnessMapChannel.SpecularMetallicAlpha; } static void SetMaterialKeywords(Material material, WorkflowMode workflowMode) { // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap") || material.GetTexture("_DetailNormalMap")); if (workflowMode == WorkflowMode.Specular) SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap")); else if (workflowMode == WorkflowMode.Metallic) SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap")); SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap")); SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap")); // A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect // or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color. // The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color. MaterialEditor.FixupEmissiveFlag(material); bool shouldEmissionBeEnabled = (material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.EmissiveIsBlack) == 0; SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled); if (material.HasProperty("_SmoothnessTextureChannel")) { SetKeyword(material, "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A", GetSmoothnessMapChannel(material) == SmoothnessMapChannel.AlbedoAlpha); } float intensity = material.GetFloat("_IntensityVC"); if (intensity <= 0f) { SetKeyword(material, "_VERTEXCOLOR_LERP", false); SetKeyword(material, "_VERTEXCOLOR", false); } else if (intensity > 0f && intensity < 1f) { SetKeyword(material, "_VERTEXCOLOR_LERP", true); SetKeyword(material, "_VERTEXCOLOR", false); } else { SetKeyword(material, "_VERTEXCOLOR_LERP", false); SetKeyword(material, "_VERTEXCOLOR", true); } } static void MaterialChanged(Material material, WorkflowMode workflowMode) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode")); SetMaterialKeywords(material, workflowMode); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } } // namespace UnityEditor
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Analyzer.Utilities; using Microsoft.CodeAnalysis.Semantics; namespace System.Runtime.Analyzers { /// <summary> /// CA2241: Provide correct arguments to formatting methods /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class ProvideCorrectArgumentsToFormattingMethodsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2241"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsMessage), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Usage, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: @"https://msdn.microsoft.com/en-us/library/ms182361.aspx", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterCompilationStartAction(compilationContext => { var formatInfo = new StringFormatInfo(compilationContext.Compilation); compilationContext.RegisterOperationAction(operationContext => { var invocation = (IInvocationExpression)operationContext.Operation; StringFormatInfo.Info info = formatInfo.TryGet(invocation.TargetMethod); if (info == null || invocation.ArgumentsInParameterOrder.Length <= info.FormatStringIndex) { // not a target method return; } IArgument formatStringArgument = invocation.ArgumentsInParameterOrder[info.FormatStringIndex]; if (!object.Equals(formatStringArgument?.Value?.Type, formatInfo.String) || !(formatStringArgument?.Value?.ConstantValue.Value is string)) { // wrong argument return; } var stringFormat = (string)formatStringArgument.Value.ConstantValue.Value; int expectedStringFormatArgumentCount = GetFormattingArguments(stringFormat); // explict parameter case if (info.ExpectedStringFormatArgumentCount >= 0) { // TODO: due to a bug - https://github.com/dotnet/roslyn/issues/7346 // vararg case is disabled. // we might check this only for C# since __arglist is not supported in VB // // we need to implement proper support for __arglist once the bug is fixed. if (invocation.TargetMethod.IsVararg) { // can't deal with this for now. return; } if (info.ExpectedStringFormatArgumentCount != expectedStringFormatArgumentCount) { operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule)); } return; } // params case IArgument paramsArgument = invocation.ArgumentsInParameterOrder[info.FormatStringIndex + 1]; if (paramsArgument.ArgumentKind != ArgumentKind.ParamArray) { // wrong format return; } var arrayCreation = paramsArgument.Value as IArrayCreationExpression; if (arrayCreation == null || !object.Equals(arrayCreation.ElementType, formatInfo.Object) || arrayCreation.DimensionSizes.Length != 1) { // wrong format return; } // compiler generating object array for params case IArrayInitializer intializer = arrayCreation.Initializer; if (intializer == null) { // unsupported format return; } // REVIEW: "ElementValues" is a bit confusing where I need to double dot those to get number of elements int actualArgumentCount = intializer.ElementValues.Length; if (actualArgumentCount != expectedStringFormatArgumentCount) { operationContext.ReportDiagnostic(operationContext.Operation.Syntax.CreateDiagnostic(Rule)); } }, OperationKind.InvocationExpression); }); } private int GetFormattingArguments(string format) { // code is from mscorlib // https://github.com/dotnet/coreclr/blob/bc146608854d1db9cdbcc0b08029a87754e12b49/src/mscorlib/src/System/Text/StringBuilder.cs#L1312 // return count of this format - {index[,alignment][:formatString]} var count = 0; var pos = 0; int len = format.Length; var ch = '\x0'; // main loop while (true) { int p = pos; int i = pos; // loop to find starting "{" while (pos < len) { ch = format[pos]; pos++; if (ch == '}') { if (pos < len && format[pos] == '}') // Treat as escape character for }} pos++; else return -1; } if (ch == '{') { if (pos < len && format[pos] == '{') // Treat as escape character for {{ pos++; else { pos--; break; } } } // finished with "{" if (pos == len) { break; } pos++; if (pos == len || (ch = format[pos]) < '0' || ch > '9') { // finished with "{x" return -1; } // searching for index var index = 0; do { index = index * 10 + ch - '0'; pos++; if (pos == len) { // wrong index format return -1; } ch = format[pos]; } while (ch >= '0' && ch <= '9' && index < 1000000); // eat up whitespace while (pos < len && (ch = format[pos]) == ' ') { pos++; } // searching for alignment var width = 0; if (ch == ',') { pos++; // eat up whitespace while (pos < len && format[pos] == ' ') { pos++; } if (pos == len) { // wrong format, reached end without "}" return -1; } ch = format[pos]; if (ch == '-') { pos++; if (pos == len) { // wrong format. reached end without "}" return -1; } ch = format[pos]; } if (ch < '0' || ch > '9') { // wrong format after "-" return -1; } do { width = width * 10 + ch - '0'; pos++; if (pos == len) { // wrong width format return -1; } ch = format[pos]; } while (ch >= '0' && ch <= '9' && width < 1000000); } // eat up whitespace while (pos < len && (ch = format[pos]) == ' ') { pos++; } // searching for embeded format string if (ch == ':') { pos++; p = pos; i = pos; while (true) { if (pos == len) { // reached end without "}" return -1; } ch = format[pos]; pos++; if (ch == '{') { if (pos < len && format[pos] == '{') // Treat as escape character for {{ pos++; else return -1; } else if (ch == '}') { if (pos < len && format[pos] == '}') // Treat as escape character for }} pos++; else { pos--; break; } } } } if (ch != '}') { // "}" is expected return -1; } pos++; count++; } // end of main loop return count; } private class StringFormatInfo { private const string Format = "format"; private readonly ImmutableDictionary<IMethodSymbol, Info> _map; public StringFormatInfo(Compilation compilation) { ImmutableDictionary<IMethodSymbol, Info>.Builder builder = ImmutableDictionary.CreateBuilder<IMethodSymbol, Info>(); INamedTypeSymbol console = WellKnownTypes.Console(compilation); AddStringFormatMap(builder, console, "Write"); AddStringFormatMap(builder, console, "WriteLine"); INamedTypeSymbol @string = WellKnownTypes.String(compilation); AddStringFormatMap(builder, @string, "Format"); _map = builder.ToImmutable(); String = @string; Object = WellKnownTypes.Object(compilation); } public INamedTypeSymbol String { get; } public INamedTypeSymbol Object { get; } public Info TryGet(IMethodSymbol method) { Info info; if (_map.TryGetValue(method, out info)) { return info; } return null; } private void AddStringFormatMap(ImmutableDictionary<IMethodSymbol, Info>.Builder builder, INamedTypeSymbol type, string methodName) { if (type == null) { return; } foreach (IMethodSymbol method in type.GetMembers(methodName).OfType<IMethodSymbol>()) { int formatIndex = FindParameterIndexOfName(method.Parameters, Format); if (formatIndex < 0 || formatIndex == method.Parameters.Length - 1) { // no valid format string continue; } int expectedArguments = GetExpectedNumberOfArguments(method.Parameters, formatIndex); builder.Add(method, new Info(formatIndex, expectedArguments)); } } private int GetExpectedNumberOfArguments(ImmutableArray<IParameterSymbol> parameters, int formatIndex) { // check params IParameterSymbol nextParameter = parameters[formatIndex + 1]; if (nextParameter.IsParams) { return -1; } return parameters.Length - formatIndex - 1; } private int FindParameterIndexOfName(ImmutableArray<IParameterSymbol> parameters, string name) { for (var i = 0; i < parameters.Length; i++) { if (string.Equals(parameters[i].Name, name, StringComparison.Ordinal)) { return i; } } return -1; } public class Info { public Info(int formatIndex, int expectedArguments) { FormatStringIndex = formatIndex; ExpectedStringFormatArgumentCount = expectedArguments; } public int FormatStringIndex { get; } public int ExpectedStringFormatArgumentCount { get; } } } } }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary>Base class from which all of the memory mapped files test classes derive.</summary> public abstract class MemoryMappedFilesTestBase : FileCleanupTestBase { /// <summary>Gets whether named maps are supported by the current platform.</summary> protected static bool MapNamesSupported { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } /// <summary>Creates a map name guaranteed to be unique.</summary> protected static string CreateUniqueMapName() { return Guid.NewGuid().ToString("N"); } /// <summary>Creates a map name guaranteed to be unique and contain only whitespace characters.</summary> protected static string CreateUniqueWhitespaceMapName() { var data = Guid.NewGuid().ToByteArray(); var sb = StringBuilderCache.Acquire(data.Length * 4); for (int i = 0; i < data.Length; i++) { byte b = data[i]; sb.Append(s_fourWhitespaceCharacters[b & 0x3]); sb.Append(s_fourWhitespaceCharacters[(b & 0xC) >> 2]); sb.Append(s_fourWhitespaceCharacters[(b & 0x30) >> 4]); sb.Append(s_fourWhitespaceCharacters[(b & 0xC0) >> 6]); } return StringBuilderCache.GetStringAndRelease(sb); } /// <summary>An array of four whitespace characters.</summary> private static readonly char[] s_fourWhitespaceCharacters = { ' ', '\t', '\r', '\n' }; /// <summary>Creates a set of valid map names to use to test various map creation scenarios.</summary> public static IEnumerable<object[]> CreateValidMapNames() // often used with [MemberData] { // Normal name yield return new object[] { CreateUniqueMapName() }; // Name that's entirely whitespace yield return new object[] { CreateUniqueWhitespaceMapName() }; // Names with prefixes recognized by Windows yield return new object[] { "local/" + CreateUniqueMapName() }; yield return new object[] { "global/" + CreateUniqueMapName() }; // Very long name yield return new object[] { CreateUniqueMapName() + new string('a', 1000) }; } /// <summary> /// Creates and yields a variety of different maps, suitable for a wide range of testing of /// views created from maps. /// </summary> protected IEnumerable<MemoryMappedFile> CreateSampleMaps( int capacity = 4096, MemoryMappedFileAccess access = MemoryMappedFileAccess.ReadWrite, [CallerMemberName]string fileName = null, [CallerLineNumber] int lineNumber = 0) { yield return MemoryMappedFile.CreateNew(null, capacity, access); yield return MemoryMappedFile.CreateFromFile(Path.Combine(TestDirectory, Guid.NewGuid().ToString("N")), FileMode.CreateNew, null, capacity, access); if (MapNamesSupported) { yield return MemoryMappedFile.CreateNew(CreateUniqueMapName(), capacity, access); yield return MemoryMappedFile.CreateFromFile(GetTestFilePath(null, fileName, lineNumber), FileMode.CreateNew, CreateUniqueMapName(), capacity, access); } } /// <summary>Performs basic verification on a map.</summary> /// <param name="mmf">The map.</param> /// <param name="expectedCapacity">The capacity that was specified to create the map.</param> /// <param name="expectedAccess">The access specified to create the map.</param> /// <param name="expectedInheritability">The inheritability specified to create the map.</param> protected static void ValidateMemoryMappedFile(MemoryMappedFile mmf, long expectedCapacity, MemoryMappedFileAccess expectedAccess = MemoryMappedFileAccess.ReadWrite, HandleInheritability expectedInheritability = HandleInheritability.None) { // Validate that we got a MemoryMappedFile object and that its handle is valid Assert.NotNull(mmf); Assert.NotNull(mmf.SafeMemoryMappedFileHandle); Assert.Same(mmf.SafeMemoryMappedFileHandle, mmf.SafeMemoryMappedFileHandle); Assert.False(mmf.SafeMemoryMappedFileHandle.IsClosed); Assert.False(mmf.SafeMemoryMappedFileHandle.IsInvalid); AssertInheritability(mmf.SafeMemoryMappedFileHandle, expectedInheritability); // Create and validate one or more views from the map if (IsReadable(expectedAccess) && IsWritable(expectedAccess)) { CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Read); CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Write); CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.ReadWrite); } else if (IsWritable(expectedAccess)) { CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Write); } else if (IsReadable(expectedAccess)) { CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Read); } else { Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.Read)); Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.Write)); Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.ReadWrite)); } } /// <summary>Creates and validates a view accessor and a view stream from the map.</summary> /// <param name="mmf">The map.</param> /// <param name="capacity">The capacity to use when creating the view.</param> /// <param name="access">The access to use when creating the view.</param> private static void CreateAndValidateViews(MemoryMappedFile mmf, long capacity, MemoryMappedFileAccess access) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(0, capacity, access)) { ValidateMemoryMappedViewAccessor(accessor, capacity, access); } using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, capacity, access)) { ValidateMemoryMappedViewStream(stream, capacity, access); } } /// <summary>Performs validation on a view accessor.</summary> /// <param name="accessor">The accessor to validate.</param> /// <param name="capacity">The capacity specified when creating the accessor.</param> /// <param name="access">The access specified when creating the accessor.</param> protected static void ValidateMemoryMappedViewAccessor(MemoryMappedViewAccessor accessor, long capacity, MemoryMappedFileAccess access) { // Validate the accessor and its handle Assert.NotNull(accessor); Assert.NotNull(accessor.SafeMemoryMappedViewHandle); Assert.Same(accessor.SafeMemoryMappedViewHandle, accessor.SafeMemoryMappedViewHandle); // Ensure its properties match the criteria specified when it was created Assert.InRange(capacity, 0, accessor.Capacity); // the capacity may be rounded up to page size, so all we guarantee is that the accessor's capacity >= capacity Assert.Equal(0, accessor.PointerOffset); // If it's supposed to be readable, try to read from it. // Otherwise, verify we can't. if (IsReadable(access)) { Assert.True(accessor.CanRead); Assert.Equal(0, accessor.ReadByte(0)); Assert.Equal(0, accessor.ReadByte(capacity - 1)); } else { Assert.False(accessor.CanRead); Assert.Throws<NotSupportedException>(() => accessor.ReadByte(0)); } // If it's supposed to be writable, try to write to it if (IsWritable(access) || access == MemoryMappedFileAccess.CopyOnWrite) { Assert.True(accessor.CanWrite); // Write some data accessor.Write(0, (byte)42); accessor.Write(capacity - 1, (byte)42); // If possible, ensure we can read it back if (IsReadable(access)) { Assert.Equal(42, accessor.ReadByte(0)); Assert.Equal(42, accessor.ReadByte(capacity - 1)); } // Write 0 back where we wrote data accessor.Write(0, (byte)0); accessor.Write(capacity - 1, (byte)0); } else { Assert.False(accessor.CanWrite); Assert.Throws<NotSupportedException>(() => accessor.Write(0, (byte)0)); } } /// <summary>Performs validation on a view stream.</summary> /// <param name="stream">The stream to verify.</param> /// <param name="capacity">The capacity specified when the stream was created.</param> /// <param name="access">The access specified when the stream was created.</param> protected static void ValidateMemoryMappedViewStream(MemoryMappedViewStream stream, long capacity, MemoryMappedFileAccess access) { // Validate the stream and its handle Assert.NotNull(stream); Assert.NotNull(stream.SafeMemoryMappedViewHandle); Assert.Same(stream.SafeMemoryMappedViewHandle, stream.SafeMemoryMappedViewHandle); // Validate its properties report the values they should Assert.InRange(capacity, 0, stream.Length); // the capacity may be rounded up to page size, so all we guarantee is that the stream's length >= capacity // If it's supposed to be readable, read from it. if (IsReadable(access)) { Assert.True(stream.CanRead); // Seek to the beginning stream.Position = 0; Assert.Equal(0, stream.Position); // Read a byte Assert.Equal(0, stream.ReadByte()); Assert.Equal(1, stream.Position); // Seek to just before the end Assert.Equal(capacity - 1, stream.Seek(capacity - 1, SeekOrigin.Begin)); // Read another byte Assert.Equal(0, stream.ReadByte()); Assert.Equal(capacity, stream.Position); } else { Assert.False(stream.CanRead); } // If it's supposed to be writable, try to write to it. if (IsWritable(access) || access == MemoryMappedFileAccess.CopyOnWrite) { Assert.True(stream.CanWrite); // Seek to the beginning, write a byte, seek to the almost end, write a byte stream.Position = 0; stream.WriteByte(42); stream.Position = stream.Length - 1; stream.WriteByte(42); // Verify the written bytes if possible if (IsReadable(access)) { stream.Position = 0; Assert.Equal(42, stream.ReadByte()); stream.Position = stream.Length - 1; Assert.Equal(42, stream.ReadByte()); } // Reset the written bytes stream.Position = 0; stream.WriteByte(0); stream.Position = stream.Length - 1; stream.WriteByte(0); } else { Assert.False(stream.CanWrite); } } /// <summary>Gets whether the specified access implies writability.</summary> protected static bool IsWritable(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Write: case MemoryMappedFileAccess.ReadWrite: case MemoryMappedFileAccess.ReadWriteExecute: return true; default: return false; } } /// <summary>Gets whether the specified access implies readability.</summary> protected static bool IsReadable(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.CopyOnWrite: case MemoryMappedFileAccess.Read: case MemoryMappedFileAccess.ReadExecute: case MemoryMappedFileAccess.ReadWrite: case MemoryMappedFileAccess.ReadWriteExecute: return true; default: return false; } } /// <summary>Gets the system's page size.</summary> protected static Lazy<int> s_pageSize = new Lazy<int>(() => { int pageSize; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { SYSTEM_INFO info; GetSystemInfo(out info); pageSize = (int)info.dwPageSize; } else { const int _SC_PAGESIZE_FreeBSD = 47; const int _SC_PAGESIZE_Linux = 30; const int _SC_PAGESIZE_NetBSD = 28; const int _SC_PAGESIZE_OSX = 29; pageSize = sysconf( RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? _SC_PAGESIZE_OSX : RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")) ? _SC_PAGESIZE_FreeBSD : RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")) ? _SC_PAGESIZE_NetBSD : _SC_PAGESIZE_Linux); } Assert.InRange(pageSize, 1, Int32.MaxValue); return pageSize; }); /// <summary>Asserts that the handle's inheritability matches the specified value.</summary> protected static void AssertInheritability(SafeHandle handle, HandleInheritability inheritability) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { uint flags; Assert.True(GetHandleInformation(handle.DangerousGetHandle(), out flags)); Assert.Equal(inheritability == HandleInheritability.Inheritable, (flags & HANDLE_FLAG_INHERIT) != 0); } } #region Windows [DllImport("kernel32.dll")] private static extern bool GetHandleInformation(IntPtr hObject, out uint lpdwFlags); private const uint HANDLE_FLAG_INHERIT = 0x00000001; [DllImport("kernel32.dll")] private static extern void GetSystemInfo(out SYSTEM_INFO input); [StructLayout(LayoutKind.Sequential)] private struct SYSTEM_INFO { internal uint dwOemId; internal uint dwPageSize; internal IntPtr lpMinimumApplicationAddress; internal IntPtr lpMaximumApplicationAddress; internal IntPtr dwActiveProcessorMask; internal uint dwNumberOfProcessors; internal uint dwProcessorType; internal uint dwAllocationGranularity; internal short wProcessorLevel; internal short wProcessorRevision; } #endregion #region Unix [DllImport("libc", SetLastError = true)] private static extern int sysconf(int name); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.UnitTesting; using Xunit; namespace System.ComponentModel.Composition { [Export] public class TypeCatalogTestsExporter { } // This is a glorious do nothing ReflectionContext public class TypeCatalogTestsReflectionContext : ReflectionContext { public override Assembly MapAssembly(Assembly assembly) { return assembly; } public override TypeInfo MapType(TypeInfo type) { return type; } } public class TypeCatalogTests { public static void Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull(Func<ReflectionContext, TypeCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("reflectionContext", () => { var catalog = catalogCreator(null); }); } public static void Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull(Func<ICompositionElement, TypeCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("definitionOrigin", () => { var catalog = catalogCreator(null); }); } [Fact] public void Constructor1_ReflectOnlyTypes_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new TypeCatalog(new Type[0], rc); }); } [Fact] public void Constructor3_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new TypeCatalog(new Type[0], dO); }); } [Fact] public void Constructor4_NullReflectionContextArgument_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new TypeCatalog(new Type[0], rc, new TypeCatalog(new Type[0])); }); } [Fact] public void Constructor4_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new TypeCatalog(new Type[0], new TypeCatalogTestsReflectionContext(), dO); }); } [Fact] public void Constructor2_NullAsTypesArgument_ShouldThrowArgumentNull() { Assert.Throws<ArgumentNullException>("types", () => { new TypeCatalog((Type[])null); }); } [Fact] public void Constructor3_NullAsTypesArgument_ShouldThrowArgumentNull() { Assert.Throws<ArgumentNullException>("types", () => { new TypeCatalog((IEnumerable<Type>)null); }); } [Fact] public void Constructor2_ArrayWithNullAsTypesArgument_ShouldThrowArgument() { Assert.Throws<ArgumentException>("types", () => { new TypeCatalog(new Type[] { null }); }); } [Fact] public void Constructor3_ArrayWithNullAsTypesArgument_ShouldThrowArgument() { Assert.Throws<ArgumentException>("types", () => { new TypeCatalog((IEnumerable<Type>)new Type[] { null }); }); } [Fact] public void Constructor2_EmptyEnumerableAsTypesArgument_ShouldSetPartsPropertyToEmptyEnumerable() { var catalog = new TypeCatalog(Enumerable.Empty<Type>()); Assert.Empty(catalog.Parts); } [Fact] public void Constructor3_EmptyArrayAsTypesArgument_ShouldSetPartsPropertyToEmpty() { var catalog = new TypeCatalog(new Type[0]); Assert.Empty(catalog.Parts); } [Fact] public void Constructor2_ArrayAsTypesArgument_ShouldNotAllowModificationAfterConstruction() { var types = new Type[] { PartFactory.GetAttributedExporterType() }; var catalog = new TypeCatalog(types); types[0] = null; Assert.NotNull(catalog.Parts.First()); } [Fact] public void Constructor3_ArrayAsTypesArgument_ShouldNotAllowModificationAfterConstruction() { var types = new Type[] { PartFactory.GetAttributedExporterType() }; var catalog = new TypeCatalog((IEnumerable<Type>)types); types[0] = null; Assert.NotNull(catalog.Parts.First()); } [Fact] public void Constructor2_ShouldSetOriginToNull() { var catalog = (ICompositionElement)new TypeCatalog(PartFactory.GetAttributedExporterType()); Assert.Null(catalog.Origin); } [Fact] public void Constructor3_ShouldSetOriginToNull() { var catalog = (ICompositionElement)new TypeCatalog((IEnumerable<Type>)new Type[] { PartFactory.GetAttributedExporterType() }); Assert.Null(catalog.Origin); } [Fact] public void DisplayName_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateTypeCatalog(); catalog.Dispose(); var displayName = ((ICompositionElement)catalog).DisplayName; } [Fact] public void Origin_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateTypeCatalog(); catalog.Dispose(); var origin = ((ICompositionElement)catalog).Origin; } [Fact] public void Parts_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateTypeCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { var parts = catalog.Parts; }); } [Fact] public void ToString_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateTypeCatalog(); catalog.Dispose(); catalog.ToString(); } [Fact] public void GetExports_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateTypeCatalog(); catalog.Dispose(); var definition = ImportDefinitionFactory.Create(); ExceptionAssert.ThrowsDisposed(catalog, () => { catalog.GetExports(definition); }); } [Fact] public void GetExports_NullAsConstraintArgument_ShouldThrowArgumentNull() { var catalog = CreateTypeCatalog(); Assert.Throws<ArgumentNullException>("definition", () => { catalog.GetExports((ImportDefinition)null); }); } [Fact] public void Dispose_ShouldNotThrow() { using (var catalog = CreateTypeCatalog()) { } } [Fact] public void Dispose_CanBeCalledMultipleTimes() { var catalog = CreateTypeCatalog(); catalog.Dispose(); catalog.Dispose(); catalog.Dispose(); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void Parts() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); Assert.NotNull(catalog.Parts); Assert.True(catalog.Parts.Count() > 0); } [Fact] public void Parts_ShouldSetDefinitionOriginToCatalogItself() { var catalog = CreateTypeCatalog(); Assert.True(catalog.Parts.Count() > 0); foreach (ICompositionElement definition in catalog.Parts) { Assert.Same(catalog, definition.Origin); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void ICompositionElementDisplayName_SingleTypeAsTypesArgument_ShouldIncludeCatalogTypeNameAndTypeFullName() { var expectations = Expectations.GetAttributedTypes(); foreach (var e in expectations) { var catalog = (ICompositionElement)CreateTypeCatalog(e); string expected = string.Format(SR.TypeCatalog_DisplayNameFormat, typeof(TypeCatalog).Name, AttributedModelServices.GetTypeIdentity(e)); Assert.Equal(expected, catalog.DisplayName); } } [Fact] public void ICompositionElementDisplayName_ValueAsTypesArgument_ShouldIncludeCatalogTypeNameAndTypeFullNames() { var expectations = new ExpectationCollection<Type[], string>(); expectations.Add(new Type[] { typeof(Type) }, GetDisplayName(false, typeof(TypeCatalog))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(ExportValueTypeSingleton) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeSingleton))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(string), typeof(ExportValueTypeSingleton) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeSingleton))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory), typeof(CallbackExecuteCodeDuringCompose) }, GetDisplayName(true, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory))); foreach (var e in expectations) { var catalog = (ICompositionElement)CreateTypeCatalog(e.Input); Assert.Equal(e.Output, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void ICompositionElementDisplayName_ShouldIncludeDerivedCatalogTypeNameAndTypeFullNames() { var expectations = Expectations.GetAttributedTypes(); foreach (var e in expectations) { var catalog = (ICompositionElement)new DerivedTypeCatalog(e); string expected = string.Format(SR.TypeCatalog_DisplayNameFormat, typeof(DerivedTypeCatalog).Name, AttributedModelServices.GetTypeIdentity(e)); Assert.Equal(expected, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void ToString_ShouldReturnICompositionElementDisplayName() { var expectations = Expectations.GetAttributedTypes(); foreach (var e in expectations) { var catalog = (ICompositionElement)CreateTypeCatalog(e); Assert.Equal(catalog.DisplayName, catalog.ToString()); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void GetExports() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); Expression<Func<ExportDefinition, bool>> constraint = (ExportDefinition exportDefinition) => exportDefinition.ContractName == AttributedModelServices.GetContractName(typeof(MyExport)); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() >= 0); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> expectedMatchingExports = catalog.Parts .SelectMany(part => part.ExportDefinitions, (part, export) => new Tuple<ComposablePartDefinition, ExportDefinition>(part, export)) .Where(partAndExport => partAndExport.Item2.ContractName == AttributedModelServices.GetContractName(typeof(MyExport))); Assert.True(matchingExports.SequenceEqual(expectedMatchingExports)); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void TwoTypesWithSameSimpleName() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); NotSoUniqueName unique1 = container.GetExportedValue<NotSoUniqueName>(); Assert.NotNull(unique1); Assert.Equal(23, unique1.MyIntProperty); NotSoUniqueName2.NotSoUniqueName nestedUnique = container.GetExportedValue<NotSoUniqueName2.NotSoUniqueName>(); Assert.NotNull(nestedUnique); Assert.Equal("MyStringProperty", nestedUnique.MyStringProperty); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void GettingFunctionExports() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); ImportDefaultFunctions import = container.GetExportedValue<ImportDefaultFunctions>("ImportDefaultFunctions"); import.VerifyIsBound(); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void AnExportOfAnInstanceThatFailsToCompose() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); // Rejection causes the part in the catalog whose imports cannot be // satisfied to be ignored, resulting in a cardinality mismatch instead of a // composition exception ExceptionAssert.Throws<ImportCardinalityMismatchException>(() => { container.GetExportedValue<string>("ExportMyString"); }); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void SharedPartCreation() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new Int32Exporter(41)); container.Compose(batch); var sharedPart1 = container.GetExportedValue<MySharedPartExport>(); Assert.Equal(41, sharedPart1.Value); var sharedPart2 = container.GetExportedValue<MySharedPartExport>(); Assert.Equal(41, sharedPart2.Value); Assert.Equal(sharedPart1, sharedPart2); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void NonSharedPartCreation() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new Int32Exporter(41)); container.Compose(batch); var nonSharedPart1 = container.GetExportedValue<MyNonSharedPartExport>(); Assert.Equal(41, nonSharedPart1.Value); var nonSharedPart2 = container.GetExportedValue<MyNonSharedPartExport>(); Assert.Equal(41, nonSharedPart2.Value); Assert.NotEqual(nonSharedPart1, nonSharedPart2); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void RecursiveNonSharedPartCreation() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<DirectCycleNonSharedPart>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleNonSharedPart>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleNonSharedPart1>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleNonSharedPart2>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleWithSharedPartAndNonSharedPart>(); }); Assert.NotNull(container.GetExportedValue<CycleSharedPart>()); Assert.NotNull(container.GetExportedValue<CycleSharedPart1>()); Assert.NotNull(container.GetExportedValue<CycleSharedPart2>()); Assert.NotNull(container.GetExportedValue<NoCycleNonSharedPart>()); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void TryToDiscoverExportWithGenericParameter() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); // Should find a type that inherits from an export Assert.NotNull(container.GetExportedValueOrDefault<object>(AttributedModelServices.GetContractName(typeof(ExportWhichInheritsFromGeneric)))); // This should be exported because it is inherited by ExportWhichInheritsFromGeneric Assert.NotNull(container.GetExportedValueOrDefault<object>(AttributedModelServices.GetContractName(typeof(ExportWithGenericParameter<string>)))); } private string GetDisplayName(bool useEllipses, Type catalogType, params Type[] types) { return String.Format(CultureInfo.CurrentCulture, SR.TypeCatalog_DisplayNameFormat, catalogType.Name, this.GetTypesDisplay(useEllipses, types)); } private string GetTypesDisplay(bool useEllipses, Type[] types) { int count = types.Length; if (count == 0) { return SR.TypeCatalog_Empty; } StringBuilder builder = new StringBuilder(); foreach (Type type in types) { if (builder.Length > 0) { builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); builder.Append(" "); } builder.Append(type.FullName); } if (useEllipses) { // Add an elipse to indicate that there // are more types than actually listed builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); builder.Append(" ..."); } return builder.ToString(); } private TypeCatalog CreateTypeCatalog() { var type = PartFactory.GetAttributedExporterType(); return CreateTypeCatalog(type); } private TypeCatalog CreateTypeCatalog(params Type[] types) { return new TypeCatalog(types); } private class DerivedTypeCatalog : TypeCatalog { public DerivedTypeCatalog(params Type[] types) : base(types) { } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; #if !(NET20 || NET35 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; using System.IO; using System.Collections; #if !(NETFX_CORE || DNXCORE50) using System.Web.UI; #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JObjectTests : TestFixtureBase { #if !(NET35 || NET20 || PORTABLE40) [Test] public void EmbedJValueStringInNewJObject() { string s = null; var v = new JValue(s); dynamic o = JObject.FromObject(new { title = v }); string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); Assert.AreEqual(null, v.Value); Assert.IsNull((string)o.title); } #endif [Test] public void ReadWithSupportMultipleContent() { string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }"; IList<JObject> roles = new List<JObject>(); JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.SupportMultipleContent = true; while (true) { JObject role = (JObject)JToken.ReadFrom(reader); roles.Add(role); if (!reader.Read()) break; } Assert.AreEqual(2, roles.Count); Assert.AreEqual("Admin", (string)roles[0]["name"]); Assert.AreEqual("Publisher", (string)roles[1]["name"]); } [Test] public void JObjectWithComments() { string json = @"{ /*comment2*/ ""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/ ""ExpiryDate"": ""\/Date(1230422400000)\/"", ""Price"": 3.99, ""Sizes"": /*comment6*/ [ /*comment7*/ ""Small"", /*comment8*/ ""Medium"" /*comment9*/, /*comment10*/ ""Large"" /*comment11*/ ] /*comment12*/ } /*comment13*/"; JToken o = JToken.Parse(json); Assert.AreEqual("Apple", (string) o["Name"]); } [Test] public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); StringAssert.AreEqual(@"{ ""novalue"": null }", o.ToString()); } [Test] public void Keys() { var o = new JObject(); var d = (IDictionary<string, JToken>)o; Assert.AreEqual(0, d.Keys.Count); o["value"] = true; Assert.AreEqual(1, d.Keys.Count); } [Test] public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); } [Test] public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(JValue.CreateNull(), t)); } [Test] public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); } [Test] public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); } [Test] public void DuplicatePropertyNameShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); }, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericDictionaryAdd() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.AreEqual(2, o.Children().Count()); } [Test] public void GenericCollectionAdd() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(1, (int)o["PropertyNameValue"]); Assert.AreEqual(1, o.Children().Count()); } [Test] public void GenericCollectionClear() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.AreEqual(0, o.Children().Count()); Assert.AreEqual(null, p.Parent); } [Test] public void GenericCollectionContains() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.AreEqual(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.AreEqual(false, contains); } [Test] public void GenericDictionaryContains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); } [Test] public void GenericCollectionCopyTo() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.AreEqual(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]); Assert.AreEqual("PropertyNameValue", a[1].Key); Assert.AreEqual(1, (int)a[1].Value); Assert.AreEqual("PropertyNameValue2", a[2].Key); Assert.AreEqual(2, (int)a[2].Value); Assert.AreEqual("PropertyNameValue3", a[3].Key); Assert.AreEqual(3, (int)a[3].Value); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]); } [Test] public void GenericCollectionCopyToNullArrayShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); }, @"Value cannot be null. Parameter name: array"); } [Test] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); }, @"arrayIndex is less than 0. Parameter name: arrayIndex"); } [Test] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); }, @"arrayIndex is equal to or greater than the length of array."); } [Test] public void GenericCollectionCopyToInsufficientArrayCapacity() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } [Test] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.AreEqual("FirstNameValue", (string)o["first_name"]); Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]); Assert.AreEqual("LastNameValue", (string)o["last_name"]); } [Test] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); } [Test] public void Parse_ShouldThrowOnUnexpectedToken() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"[""prop""]"; JObject.Parse(json); }, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."); } [Test] public void ParseJavaScriptDate() { string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Test] public void GenericValueCast() { string json = @"{""foo"":true}"; JObject o = (JObject)JsonConvert.DeserializeObject(json); bool? value = o.Value<bool?>("foo"); Assert.AreEqual(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.AreEqual(null, value); } [Test] public void Blog() { ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 5."); } [Test] public void RawChildValues() { JObject o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); StringAssert.AreEqual(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Test] public void Iterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.AreEqual("PropertyNameValue" + i, property.Name); Assert.AreEqual(i, (int)property.Value); i++; } } [Test] public void KeyValuePairIterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.AreEqual("PropertyNameValue" + i, pair.Key); Assert.AreEqual(i, (int)pair.Value); i++; } } [Test] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.String, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } [Test] public void Example() { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Assert.AreEqual("Apple", name); Assert.AreEqual("Small", smallest); } [Test] public void DeserializeClassManually() { string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); Assert.AreEqual(0, shortie.Error.Code); Assert.AreEqual("No action taken", shortie.Error.ErrorMessage); } [Test] public void JObjectContainingHtml() { JObject o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>"); StringAssert.AreEqual(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n</div>"" }", o.ToString()); } [Test] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); StringAssert.AreEqual(@"{ ""FirstName"": ""Maurice"", ""LastName"": ""Moss"", ""BirthDate"": ""1977-12-30T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Support"" }", moss.ToString()); JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; StringAssert.AreEqual(@"{ ""FirstName"": ""Jen"", ""LastName"": ""Barber"", ""BirthDate"": ""1978-03-15T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Manager"" }", jen.ToString()); } [Test] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); IList l = o; Assert.AreEqual(p1, l[0]); Assert.AreEqual(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.AreEqual(null, p1.Parent); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); Assert.AreEqual(2, l.Count); Assert.AreEqual(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.AreEqual(null, p2.Parent); Assert.AreEqual(l, p4.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p4, l[1]); } #if !(NET20 || PORTABLE || PORTABLE40) [Test] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; JObject o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject)sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual(null, changing); Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value1", changing); Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changingCount); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual("value2", changing); Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changingCount); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changing); Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); } #endif [Test] public void PropertyChanged() { object changed = null; int changedCount = 0; JObject o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changedCount); } [Test] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void IListAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); }, "Argument is not a JToken."); } [Test] public void IListAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void IListIsReadOnly() { IList l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void IListIsFixedSize() { IList l = new JObject(); Assert.IsFalse(l.IsFixedSize); } [Test] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void IListSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListSetItemInvalid() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); }, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsNotNull(l.SyncRoot); } [Test] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsFalse(l.IsSynchronized); } [Test] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void GenericListJTokenAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void GenericListJTokenSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection); } [Test] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.AreEqual(null, l.SortProperty); } [Test] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.AreEqual(true, l.SupportsChangeNotification); } [Test] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSearching); } [Test] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSorting); } [Test] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowEdit); } [Test] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowNew); } [Test] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowRemove); } [Test] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Test] public void IBindingListApplySort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveSort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.RemoveSort(); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Test] public void IBindingListFind() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.Find(null, null); }, "Specified method is not supported."); } [Test] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.AreEqual(false, l.IsSorted); } [Test] public void IBindingListAddNew() { ExceptionAssert.Throws<JsonException>(() => { IBindingList l = new JObject(); l.AddNew(); }, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'."); } [Test] public void IBindingListAddNewWithEvent() { JObject o = new JObject(); o._addingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.IsNotNull(newObject); JProperty p = (JProperty)newObject; Assert.AreEqual("Property!", p.Name); Assert.AreEqual(o, p.Parent); } [Test] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.AreEqual(string.Empty, l.GetListName(null)); } [Test] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.IsNull(propertyDescriptors); } [Test] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, ListChangedType.ItemAdded); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif #if !(NET20 || NET35 || PORTABLE40) [Test] public void CollectionChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); NotifyCollectionChangedAction? changedType = null; int? index = null; o._collectionChanged += (s, a) => { changedType = a.Action; index = a.NewStartingIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif [Test] public void GetGeocodeAddress() { string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.AreEqual("435 N Mulford Rd", searchAddress); } [Test] public void SetValueWithInvalidPropertyName() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o[0] = new JValue(3); }, "Set JObject values with invalid key value: 0. Object property name expected."); } [Test] public void SetValue() { object key = "TestKey"; JObject o = new JObject(); o[key] = new JValue(3); Assert.AreEqual(3, (int)o[key]); } [Test] public void ParseMultipleProperties() { string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.AreEqual("Name2", value); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } #endif [Test] public void InvalidValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; }, "Can not convert Object to String."); } [Test] public void InvalidPropertyValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); }, "Can not convert Object to String."); } [Test] public void ParseIncomplete() { ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6."); } [Test] public void LoadFromNestedObject() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.IsNotNull(o); StringAssert.AreEqual(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Test] public void LoadFromNestedObjectIncomplete() { ExceptionAssert.Throws<JsonReaderException>(() => { string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15."); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.AreEqual(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.AreEqual("prop1", prop1.Name); Assert.AreEqual(typeof(object), prop1.PropertyType); Assert.AreEqual(typeof(JObject), prop1.ComponentType); Assert.AreEqual(false, prop1.CanResetValue(o)); Assert.AreEqual(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.AreEqual("prop2", prop2.Name); Assert.AreEqual(typeof(object), prop2.PropertyType); Assert.AreEqual(typeof(JObject), prop2.ComponentType); Assert.AreEqual(false, prop2.CanResetValue(o)); Assert.AreEqual(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.AreEqual("prop3", prop3.Name); Assert.AreEqual(typeof(object), prop3.PropertyType); Assert.AreEqual(typeof(JObject), prop3.ComponentType); Assert.AreEqual(false, prop3.CanResetValue(o)); Assert.AreEqual(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.AreEqual("prop4", prop4.Name); Assert.AreEqual(typeof(object), prop4.PropertyType); Assert.AreEqual(typeof(JObject), prop4.ComponentType); Assert.AreEqual(false, prop4.CanResetValue(o)); Assert.AreEqual(false, prop4.ShouldSerializeValue(o)); } #endif [Test] public void ParseEmptyObjectWithComment() { JObject o = JObject.Parse("{ /* A Comment */ }"); Assert.AreEqual(0, o.Count); } [Test] public void FromObjectTimeSpan() { JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1)); Assert.AreEqual(v.Value, TimeSpan.FromDays(1)); Assert.AreEqual("1.00:00:00", v.ToString()); } [Test] public void FromObjectUri() { JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz")); Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz")); Assert.AreEqual("http://www.stuff.co.nz/", v.ToString()); } [Test] public void FromObjectGuid() { JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString()); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }, 987987"; JObject o = JObject.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2."); } [Test] public void DeepEqualsIgnoreOrder() { JObject o1 = new JObject( new JProperty("null", null), new JProperty("integer", 1), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o1)); JObject o2 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o2)); JObject o3 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 2), new JProperty("array", new JArray(1, 2))); Assert.IsFalse(o1.DeepEquals(o3)); JObject o4 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(2, 1))); Assert.IsFalse(o1.DeepEquals(o4)); JObject o5 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1)); Assert.IsFalse(o1.DeepEquals(o5)); Assert.IsFalse(o1.DeepEquals(null)); } [Test] public void ToListOnEmptyObject() { JObject o = JObject.Parse(@"{}"); IList<JToken> l1 = o.ToList<JToken>(); Assert.AreEqual(0, l1.Count); IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(0, l2.Count); o = JObject.Parse(@"{'hi':null}"); l1 = o.ToList<JToken>(); Assert.AreEqual(1, l1.Count); l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(1, l2.Count); } [Test] public void EmptyObjectDeepEquals() { Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject())); JObject a = new JObject(); JObject b = new JObject(); b.Add("hi", "bye"); b.Remove("hi"); Assert.IsTrue(JToken.DeepEquals(a, b)); Assert.IsTrue(JToken.DeepEquals(b, a)); } [Test] public void GetValueBlogExample() { JObject o = JObject.Parse(@"{ 'name': 'Lower', 'NAME': 'Upper' }"); string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase); // Upper string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase); // Lower Assert.AreEqual("Upper", exactMatch); Assert.AreEqual("Lower", ignoreCase); } [Test] public void GetValue() { JObject a = new JObject(); a["Name"] = "Name!"; a["name"] = "name!"; a["title"] = "Title!"; Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue("NAME")); Assert.AreEqual(null, a.GetValue("TITLE")); Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase)); Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null)); JToken v; Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v)); Assert.AreEqual(null, v); Assert.IsFalse(a.TryGetValue("NAME", out v)); Assert.IsFalse(a.TryGetValue("TITLE", out v)); Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v)); Assert.AreEqual("Name!", (string)v); Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v)); Assert.AreEqual("name!", (string)v); Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v)); } public class FooJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var token = JToken.FromObject(value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); if (token.Type == JTokenType.Object) { var o = (JObject)token; o.AddFirst(new JProperty("foo", "bar")); o.WriteTo(writer); } else token.WriteTo(writer); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException("This custom converter only supportes serialization and not deserialization."); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } [Test] public void FromObjectInsideConverterWithCustomSerializer() { var p = new Person { Name = "Daniel Wertheim", }; var settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new FooJsonConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(p, settings); Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json); } } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // 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> //----------------------------------------------------------------------- #endregion using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.WootzJs; namespace System { public abstract class Enum : ValueType { private readonly string name; private readonly object value; private static Dictionary<string, Dictionary<string, Enum>> enumsByTypeAndName = new Dictionary<string, Dictionary<string, Enum>>(); private static Dictionary<string, Dictionary<object, Enum>> enumsByTypeAndValue = new Dictionary<string, Dictionary<object, Enum>>(); private static Dictionary<string, List<Enum>> enumsByType = new Dictionary<string, List<Enum>>(); public Enum(string name, object value) { if (name == null) throw new ArgumentNullException("name"); if (value == null) throw new ArgumentNullException("value"); this.name = name; this.value = value; Dictionary<string, Enum> enumsByName; if (!enumsByTypeAndName.TryGetValue(___type.TypeName, out enumsByName)) { enumsByName = new Dictionary<string, Enum>(); enumsByTypeAndName[___type.TypeName] = enumsByName; } enumsByName[name] = this; Dictionary<object, Enum> enumsByValue; if (!enumsByTypeAndValue.TryGetValue(___type.TypeName, out enumsByValue)) { enumsByValue = new Dictionary<object, Enum>(); enumsByTypeAndValue[___type.TypeName] = enumsByValue; } enumsByValue[value] = this; List<Enum> enums; if (!enumsByType.TryGetValue(___type.TypeName, out enums)) { enums = new List<Enum>(); enumsByType[___type.TypeName] = enums; } enums.Add(this); } public static Array GetEnumValues(Type type) { return enumsByType[type.___type.TypeName].ToArray(); } public object GetValue() { return value; } public override string ToString() { return name; } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. /// </summary> /// /// <returns> /// An object of type <paramref name="enumType"/> whose value is represented by <paramref name="value"/>. /// </returns> /// <param name="enumType">An enumeration type. </param><param name="value">A string containing the name or value to convert. </param><exception cref="T:System.ArgumentNullException"><paramref name="enumType"/> or <paramref name="value"/> is null. </exception><exception cref="T:System.ArgumentException"><paramref name="enumType"/> is not an <see cref="T:System.Enum"/>.-or- <paramref name="value"/> is either an empty string or only contains white space.-or- <paramref name="value"/> is a name, but not one of the named constants defined for the enumeration. </exception><exception cref="T:System.OverflowException"><paramref name="value"/> is outside the range of the underlying type of <paramref name="enumType"/>.</exception><filterpriority>1</filterpriority> public static object Parse(Type enumType, string value) { var dictionary = enumsByTypeAndName[enumType.thisType.TypeName]; Enum result; if (!dictionary.TryGetValue(value, out result)) throw new InvalidOperationException("Enum " + enumType.FullName + " does not contain '" + value + "'"); return dictionary[value]; } /// <summary> /// Converts the specified object with an integer value to an enumeration member. /// </summary> /// /// <returns> /// An enumeration object whose value is <paramref name="value"/>. /// </returns> /// <param name="enumType">The enumeration type to return. </param><param name="value">The value convert to an enumeration member. </param><exception cref="T:System.ArgumentNullException"><paramref name="enumType"/> or <paramref name="value"/> is null. </exception><exception cref="T:System.ArgumentException"><paramref name="enumType"/> is not an <see cref="T:System.Enum"/>.-or- <paramref name="value"/> is not type <see cref="T:System.SByte"/>, <see cref="T:System.Int16"/>, <see cref="T:System.Int32"/>, <see cref="T:System.Int64"/>, <see cref="T:System.Byte"/>, <see cref="T:System.UInt16"/>, <see cref="T:System.UInt32"/>, or <see cref="T:System.UInt64"/>. </exception><filterpriority>1</filterpriority> public static object ToObject(Type enumType, object value) { return enumsByTypeAndValue[enumType.thisType.TypeName][value]; } public static object InternalToObject(JsTypeFunction enumType, object value) { var enumsByValue = enumsByTypeAndValue[enumType.TypeName]; Enum result = enumsByValue.GetOrDefault(value); if (result != null) { return result; } else { // Otherwise it's an enum value that isn't represented by a declared member. In // this case, we need to box the value and then force it to be recognized as the // enum type. result = Jsni.@new(Jsni.reference("Number"), value.As<JsObject>()).As<Enum>(); foreach (var property in enumType.member("prototype")) { result.As<JsObject>()[property] = enumType.member("prototype")[property]; } foreach (var property in Jsni.type<Enum>().member("prototype")) { result.As<JsObject>()[property] = Jsni.type<Enum>().member("prototype")[property]; } result.___type = enumType; result.As<JsObject>().memberset("value", value.As<JsObject>()); enumsByValue[value] = result; return result; } } protected bool Equals(Enum other) { return Equals(value, other.value); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Enum)obj); } public override int GetHashCode() { return (value != null ? value.GetHashCode() : 0); } /// <summary> /// Retrieves an array of the names of the constants in a specified enumeration. /// </summary> /// /// <returns> /// A string array of the names of the constants in <paramref name="enumType"/>. /// </returns> /// <param name="enumType">An enumeration type. </param><exception cref="T:System.ArgumentNullException"><paramref name="enumType"/> is null. </exception><exception cref="T:System.ArgumentException"><paramref name="enumType"/> parameter is not an <see cref="T:System.Enum"/>. </exception><filterpriority>1</filterpriority> public static string[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); enumType.thisType.invoke(); return enumsByType[enumType.thisType.TypeName].Select(x => x.name).ToArray(); } /// <summary> /// Retrieves an array of the values of the constants in a specified enumeration. /// </summary> /// /// <returns> /// An array that contains the values of the constants in <paramref name="enumType"/>. /// </returns> /// <param name="enumType">An enumeration type. </param><exception cref="T:System.ArgumentNullException"><paramref name="enumType"/> is null. </exception><exception cref="T:System.ArgumentException"><paramref name="enumType"/> is not an <see cref="T:System.Enum"/>. </exception><exception cref="T:System.InvalidOperationException">The method is invoked by reflection in a reflection-only context, -or-<paramref name="enumType"/> is a type from an assembly loaded in a reflection-only context.</exception><filterpriority>1</filterpriority> public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); else return enumType.GetEnumValues(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Xunit; namespace System.IO.Tests { public class FileSystemWatcherTests : FileSystemWatcherTest { private static void ValidateDefaults(FileSystemWatcher watcher, string path, string filter) { Assert.Equal(false, watcher.EnableRaisingEvents); Assert.Equal(filter, watcher.Filter); Assert.Equal(false, watcher.IncludeSubdirectories); Assert.Equal(8192, watcher.InternalBufferSize); Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter); Assert.Equal(path, watcher.Path); } [Fact] public void FileSystemWatcher_NewFileInfoAction_TriggersNothing() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { Action action = () => new FileInfo(file.Path); ExpectEvent(watcher, 0, action, expectedPath: file.Path); } } [Fact] public void FileSystemWatcher_FileInfoGetter_TriggersNothing() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { FileAttributes res; Action action = () => res = new FileInfo(file.Path).Attributes; ExpectEvent(watcher, 0, action, expectedPath: file.Path); } } [Fact] public void FileSystemWatcher_EmptyAction_TriggersNothing() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { Action action = () => { }; ExpectEvent(watcher, 0, action, expectedPath: file.Path); } } [Fact] public void FileSystemWatcher_ctor() { string path = String.Empty; string pattern = "*.*"; using (FileSystemWatcher watcher = new FileSystemWatcher()) ValidateDefaults(watcher, path, pattern); } [Fact] public void FileSystemWatcher_ctor_path() { string path = @"."; string pattern = "*.*"; using (FileSystemWatcher watcher = new FileSystemWatcher(path)) ValidateDefaults(watcher, path, pattern); } [Fact] public void FileSystemWatcher_ctor_path_pattern() { string path = @"."; string pattern = "honey.jar"; using (FileSystemWatcher watcher = new FileSystemWatcher(path, pattern)) ValidateDefaults(watcher, path, pattern); } [Fact] public void FileSystemWatcher_ctor_NullStrings() { using (var testDirectory = new TempDirectory(GetTestFilePath())) { // Null filter AssertExtensions.Throws<ArgumentNullException>("filter", () => new FileSystemWatcher(testDirectory.Path, null)); // Null path AssertExtensions.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null)); AssertExtensions.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, "*")); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "On Desktop, these exceptions don't have a parameter")] public void FileSystemWatcher_ctor_InvalidStrings() { using (var testDirectory = new TempDirectory(GetTestFilePath())) { // Empty path AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty)); AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty, "*")); // Invalid directory AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath())); AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath(), "*")); } } [Fact] public void FileSystemWatcher_Changed() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Changed += handler; watcher.Changed -= handler; // shouldn't throw watcher.Changed -= handler; } } [Fact] public void FileSystemWatcher_Created() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Created += handler; watcher.Created -= handler; // shouldn't throw watcher.Created -= handler; } } [Fact] public void FileSystemWatcher_Deleted() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Deleted += handler; watcher.Deleted -= handler; // shouldn't throw watcher.Deleted -= handler; } } [Fact] public void FileSystemWatcher_Disposed() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Dispose(); watcher.Dispose(); // shouldn't throw Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true); } [Fact] public void FileSystemWatcher_EnableRaisingEvents() { using (var testDirectory = new TempDirectory(GetTestFilePath())) { FileSystemWatcher watcher = new FileSystemWatcher(testDirectory.Path); Assert.Equal(false, watcher.EnableRaisingEvents); watcher.EnableRaisingEvents = true; Assert.Equal(true, watcher.EnableRaisingEvents); watcher.EnableRaisingEvents = false; Assert.Equal(false, watcher.EnableRaisingEvents); } } [Fact] public void FileSystemWatcher_Error() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new ErrorEventHandler((o, e) => { }); // add / remove watcher.Error += handler; watcher.Error -= handler; // shouldn't throw watcher.Error -= handler; } } [Fact] public void FileSystemWatcher_Filter() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal("*.*", watcher.Filter); // Null and empty should be mapped to "*.*" watcher.Filter = null; Assert.Equal("*.*", watcher.Filter); watcher.Filter = String.Empty; Assert.Equal("*.*", watcher.Filter); watcher.Filter = " "; Assert.Equal(" ", watcher.Filter); watcher.Filter = "\0"; Assert.Equal("\0", watcher.Filter); watcher.Filter = "\n"; Assert.Equal("\n", watcher.Filter); watcher.Filter = "abc.dll"; Assert.Equal("abc.dll", watcher.Filter); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // expect no change for OrdinalIgnoreCase-equal strings // it's unclear why desktop does this but preserve it for compat watcher.Filter = "ABC.DLL"; Assert.Equal("abc.dll", watcher.Filter); } // We can make this setting by first changing to another value then back. watcher.Filter = null; watcher.Filter = "ABC.DLL"; Assert.Equal("ABC.DLL", watcher.Filter); } [Fact] public void FileSystemWatcher_IncludeSubdirectories() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(false, watcher.IncludeSubdirectories); watcher.IncludeSubdirectories = true; Assert.Equal(true, watcher.IncludeSubdirectories); watcher.IncludeSubdirectories = false; Assert.Equal(false, watcher.IncludeSubdirectories); } [Fact] public void FileSystemWatcher_InternalBufferSize() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(8192, watcher.InternalBufferSize); watcher.InternalBufferSize = 20000; Assert.Equal(20000, watcher.InternalBufferSize); watcher.InternalBufferSize = int.MaxValue; Assert.Equal(int.MaxValue, watcher.InternalBufferSize); // FSW enforces a minimum value of 4096 watcher.InternalBufferSize = 0; Assert.Equal(4096, watcher.InternalBufferSize); watcher.InternalBufferSize = -1; Assert.Equal(4096, watcher.InternalBufferSize); watcher.InternalBufferSize = int.MinValue; Assert.Equal(4096, watcher.InternalBufferSize); watcher.InternalBufferSize = 4095; Assert.Equal(4096, watcher.InternalBufferSize); } [Fact] public void FileSystemWatcher_NotifyFilter() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter); var notifyFilters = Enum.GetValues(typeof(NotifyFilters)).Cast<NotifyFilters>(); foreach (NotifyFilters filterValue in notifyFilters) { watcher.NotifyFilter = filterValue; Assert.Equal(filterValue, watcher.NotifyFilter); } var allFilters = notifyFilters.Aggregate((mask, flag) => mask | flag); watcher.NotifyFilter = allFilters; Assert.Equal(allFilters, watcher.NotifyFilter); // This doesn't make sense, but it is permitted. watcher.NotifyFilter = 0; Assert.Equal((NotifyFilters)0, watcher.NotifyFilter); // These throw InvalidEnumException on desktop, but ArgumentException on K Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)(-1)); Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MinValue); Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MaxValue); Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters + 1); // Simulate a bit added to the flags Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters | (NotifyFilters)((int)notifyFilters.Max() << 1)); } [Fact] public void FileSystemWatcher_OnChanged() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Changed, "directory", "file"); watcher.Changed += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnChanged(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] public void FileSystemWatcher_OnCreated() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Created, "directory", "file"); watcher.Created += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnCreated(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] [PlatformSpecific(TestPlatforms.OSX | TestPlatforms.Windows)] // Casing matters on Linux public void FileSystemWatcher_OnCreatedWithMismatchedCasingGivesExpectedFullPath() { using (var dir = new TempDirectory(GetTestFilePath())) using (var fsw = new FileSystemWatcher(dir.Path)) { AutoResetEvent are = new AutoResetEvent(false); string fullPath = Path.Combine(dir.Path.ToUpper(), "Foo.txt"); fsw.Created += (o, e) => { Assert.True(fullPath.Equals(e.FullPath, StringComparison.OrdinalIgnoreCase)); are.Set(); }; fsw.EnableRaisingEvents = true; using (var file = new TempFile(fullPath)) { ExpectEvent(are, "created"); } } } [Fact] public void FileSystemWatcher_OnDeleted() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Deleted, "directory", "file"); watcher.Deleted += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnDeleted(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] public void FileSystemWatcher_OnError() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; ErrorEventArgs actualArgs = null, expectedArgs = new ErrorEventArgs(new Exception()); watcher.Error += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnError(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] public void FileSystemWatcher_OnRenamed() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; RenamedEventArgs actualArgs = null, expectedArgs = new RenamedEventArgs(WatcherChangeTypes.Renamed, "directory", "file", "oldFile"); watcher.Renamed += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnRenamed(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix FSW don't trigger on a file rename. public void FileSystemWatcher_Windows_OnRenameGivesExpectedFullPath() { using (var dir = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(dir.Path, "file"))) using (var fsw = new FileSystemWatcher(dir.Path)) { AutoResetEvent eventOccurred = WatchRenamed(fsw); string newPath = Path.Combine(dir.Path, "newPath"); fsw.Renamed += (o, e) => { Assert.Equal(e.OldFullPath, file.Path); Assert.Equal(e.FullPath, newPath); }; fsw.EnableRaisingEvents = true; File.Move(file.Path, newPath); ExpectEvent(eventOccurred, "renamed"); } } [Fact] public void FileSystemWatcher_Path() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(String.Empty, watcher.Path); watcher.Path = null; Assert.Equal(String.Empty, watcher.Path); watcher.Path = "."; Assert.Equal(".", watcher.Path); if (!PlatformDetection.IsWinRT) { watcher.Path = ".."; Assert.Equal("..", watcher.Path); } string currentDir = Path.GetFullPath(".").TrimEnd('.', Path.DirectorySeparatorChar); watcher.Path = currentDir; Assert.Equal(currentDir, watcher.Path); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { watcher.Path = currentDir.ToUpperInvariant(); Assert.Equal(currentDir, watcher.Path); watcher.Path = currentDir.ToLowerInvariant(); Assert.Equal(currentDir, watcher.Path); } // expect a change for same "full-path" but different string path, FSW does not normalize string currentDirRelative = currentDir + Path.DirectorySeparatorChar + "." + Path.DirectorySeparatorChar + "." + Path.DirectorySeparatorChar + "." + Path.DirectorySeparatorChar + "."; watcher.Path = currentDirRelative; Assert.Equal(currentDirRelative, watcher.Path); // FSW starts with String.Empty and will ignore setting this if it is already set, // but if you set it after some other valid string has been set it will throw. AssertExtensions.Throws<ArgumentException>(null, () => watcher.Path = String.Empty); // Non-existent path AssertExtensions.Throws<ArgumentException>(null, () => watcher.Path = GetTestFilePath()); // Web path AssertExtensions.Throws<ArgumentException>(null, () => watcher.Path = "http://localhost"); // File protocol AssertExtensions.Throws<ArgumentException>(null, () => watcher.Path = "file:///" + currentDir.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); } [Fact] public void FileSystemWatcher_Renamed() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new RenamedEventHandler((o, e) => { }); // add / remove watcher.Renamed += handler; watcher.Renamed -= handler; // shouldn't throw watcher.Renamed -= handler; } } [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Reads MaxUsersWatches from Linux OS files [OuterLoop("This test has high system resource demands and may cause failures in other concurrent tests")] public void FileSystemWatcher_CreateManyConcurrentWatches() { int maxUserWatches = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_watches")); using (var dir = new TempDirectory(GetTestFilePath())) using (var watcher = new FileSystemWatcher(dir.Path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName }) { Action action = () => { // Create enough directories to exceed the number of allowed watches for (int i = 0; i <= maxUserWatches; i++) { Directory.CreateDirectory(Path.Combine(dir.Path, i.ToString())); } }; Action cleanup = () => { for (int i = 0; i <= maxUserWatches; i++) { Directory.Delete(Path.Combine(dir.Path, i.ToString())); } }; ExpectError(watcher, action, cleanup); // Make sure existing watches still work even after we've had one or more failures Action createAction = () => File.WriteAllText(Path.Combine(dir.Path, Path.GetRandomFileName()), "text"); Action createCleanup = () => File.Delete(Path.Combine(dir.Path, Path.GetRandomFileName())); ExpectEvent(watcher, WatcherChangeTypes.Created, createAction, createCleanup); } } [Fact] public void FileSystemWatcher_StopCalledOnBackgroundThreadDoesNotDeadlock() { // Check the case where Stop or Dispose (they do the same thing) is called from // a FSW event callback and make sure we don't Thread.Join to deadlock using (var dir = new TempDirectory(GetTestFilePath())) { string filePath = Path.Combine(dir.Path, "testfile.txt"); File.Create(filePath).Dispose(); AutoResetEvent are = new AutoResetEvent(false); FileSystemWatcher watcher = new FileSystemWatcher(Path.GetFullPath(dir.Path), "*"); FileSystemEventHandler callback = (sender, arg) => { watcher.Dispose(); are.Set(); }; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; watcher.Changed += callback; watcher.EnableRaisingEvents = true; File.SetLastWriteTime(filePath, File.GetLastWriteTime(filePath).AddDays(1)); Assert.True(are.WaitOne(10000)); Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true); } } [Fact] public void FileSystemWatcher_WatchingAliasedFolderResolvesToRealPathWhenWatching() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir"))) using (var fsw = new FileSystemWatcher(dir.Path)) { AutoResetEvent are = WatchCreated(fsw); fsw.Filter = "*"; fsw.EnableRaisingEvents = true; using (var temp = new TempDirectory(Path.Combine(dir.Path, "foo"))) { ExpectEvent(are, "created"); } } } } }
using System; using System.Collections.Generic; using System.IO; namespace mapgenerator { class mapgenerator { static void WriteFieldMember(TextWriter writer, MapField field) { string type = String.Empty; switch (field.Type) { case FieldType.BOOL: type = "bool"; break; case FieldType.F32: type = "float"; break; case FieldType.F64: type = "double"; break; case FieldType.IPPORT: case FieldType.U16: type = "ushort"; break; case FieldType.IPADDR: case FieldType.U32: type = "uint"; break; case FieldType.LLQuaternion: type = "Quaternion"; break; case FieldType.LLUUID: type = "UUID"; break; case FieldType.LLVector3: type = "Vector3"; break; case FieldType.LLVector3d: type = "Vector3d"; break; case FieldType.LLVector4: type = "Vector4"; break; case FieldType.S16: type = "short"; break; case FieldType.S32: type = "int"; break; case FieldType.S8: type = "sbyte"; break; case FieldType.U64: type = "ulong"; break; case FieldType.U8: type = "byte"; break; case FieldType.Fixed: type = "byte[]"; break; } if (field.Type != FieldType.Variable) { //writer.WriteLine(" /// <summary>" + field.Name + " field</summary>"); writer.WriteLine(" public " + type + " " + field.Name + ";"); } else { writer.WriteLine(" public byte[] " + field.Name + ";"); //writer.WriteLine(" private byte[] _" + field.Name.ToLower() + ";"); ////writer.WriteLine(" /// <summary>" + field.Name + " field</summary>"); //writer.WriteLine(" public byte[] " + field.Name + Environment.NewLine + " {"); //writer.WriteLine(" get { return _" + field.Name.ToLower() + "; }"); //writer.WriteLine(" set" + Environment.NewLine + " {"); //writer.WriteLine(" if (value == null) { _" + // field.Name.ToLower() + " = null; return; }"); //writer.WriteLine(" if (value.Length > " + // ((field.Count == 1) ? "255" : "1100") + ") { throw new OverflowException(" + // "\"Value exceeds " + ((field.Count == 1) ? "255" : "1100") + " characters\"); }"); //writer.WriteLine(" else { _" + field.Name.ToLower() + // " = new byte[value.Length]; Buffer.BlockCopy(value, 0, _" + // field.Name.ToLower() + ", 0, value.Length); }"); //writer.WriteLine(" }" + Environment.NewLine + " }"); } } static void WriteFieldFromBytes(TextWriter writer, MapField field) { switch (field.Type) { case FieldType.BOOL: writer.WriteLine(" " + field.Name + " = (bytes[i++] != 0) ? (bool)true : (bool)false;"); break; case FieldType.F32: writer.WriteLine(" " + field.Name + " = Utils.BytesToFloat(bytes, i); i += 4;"); break; case FieldType.F64: writer.WriteLine(" " + field.Name + " = Utils.BytesToDouble(bytes, i); i += 8;"); break; case FieldType.Fixed: writer.WriteLine(" " + field.Name + " = new byte[" + field.Count + "];"); writer.WriteLine(" Buffer.BlockCopy(bytes, i, " + field.Name + ", 0, " + field.Count + "); i += " + field.Count + ";"); break; case FieldType.IPADDR: case FieldType.U32: writer.WriteLine(" " + field.Name + " = (uint)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));"); break; case FieldType.IPPORT: // IPPORT is big endian while U16/S16 are little endian. Go figure writer.WriteLine(" " + field.Name + " = (ushort)((bytes[i++] << 8) + bytes[i++]);"); break; case FieldType.U16: writer.WriteLine(" " + field.Name + " = (ushort)(bytes[i++] + (bytes[i++] << 8));"); break; case FieldType.LLQuaternion: writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i, true); i += 12;"); break; case FieldType.LLUUID: writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 16;"); break; case FieldType.LLVector3: writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 12;"); break; case FieldType.LLVector3d: writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 24;"); break; case FieldType.LLVector4: writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 16;"); break; case FieldType.S16: writer.WriteLine(" " + field.Name + " = (short)(bytes[i++] + (bytes[i++] << 8));"); break; case FieldType.S32: writer.WriteLine(" " + field.Name + " = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));"); break; case FieldType.S8: writer.WriteLine(" " + field.Name + " = (sbyte)bytes[i++];"); break; case FieldType.U64: writer.WriteLine(" " + field.Name + " = (ulong)((ulong)bytes[i++] + ((ulong)bytes[i++] << 8) + " + "((ulong)bytes[i++] << 16) + ((ulong)bytes[i++] << 24) + " + "((ulong)bytes[i++] << 32) + ((ulong)bytes[i++] << 40) + " + "((ulong)bytes[i++] << 48) + ((ulong)bytes[i++] << 56));"); break; case FieldType.U8: writer.WriteLine(" " + field.Name + " = (byte)bytes[i++];"); break; case FieldType.Variable: if (field.Count == 1) { writer.WriteLine(" length = bytes[i++];"); } else { writer.WriteLine(" length = (bytes[i++] + (bytes[i++] << 8));"); } writer.WriteLine(" " + field.Name + " = new byte[length];"); writer.WriteLine(" Buffer.BlockCopy(bytes, i, " + field.Name + ", 0, length); i += length;"); break; default: writer.WriteLine("!!! ERROR: Unhandled FieldType: " + field.Type.ToString() + " !!!"); break; } } static void WriteFieldToBytes(TextWriter writer, MapField field) { writer.Write(" "); switch (field.Type) { case FieldType.BOOL: writer.WriteLine("bytes[i++] = (byte)((" + field.Name + ") ? 1 : 0);"); break; case FieldType.F32: writer.WriteLine("Utils.FloatToBytes(" + field.Name + ", bytes, i); i += 4;"); break; case FieldType.F64: writer.WriteLine("Utils.DoubleToBytes(" + field.Name + ", bytes, i); i += 8;"); break; case FieldType.Fixed: writer.WriteLine("Buffer.BlockCopy(" + field.Name + ", 0, bytes, i, " + field.Count + ");" + "i += " + field.Count + ";"); break; case FieldType.IPPORT: // IPPORT is big endian while U16/S16 is little endian. Go figure writer.WriteLine("bytes[i++] = (byte)((" + field.Name + " >> 8) % 256);"); writer.WriteLine(" bytes[i++] = (byte)(" + field.Name + " % 256);"); break; case FieldType.U16: case FieldType.S16: writer.WriteLine("bytes[i++] = (byte)(" + field.Name + " % 256);"); writer.WriteLine(" bytes[i++] = (byte)((" + field.Name + " >> 8) % 256);"); break; case FieldType.LLQuaternion: case FieldType.LLVector3: writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 12;"); break; case FieldType.LLUUID: case FieldType.LLVector4: writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 16;"); break; case FieldType.LLVector3d: writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 24;"); break; case FieldType.U8: writer.WriteLine("bytes[i++] = " + field.Name + ";"); break; case FieldType.S8: writer.WriteLine("bytes[i++] = (byte)" + field.Name + ";"); break; case FieldType.IPADDR: case FieldType.U32: writer.WriteLine("Utils.UIntToBytes(" + field.Name + ", bytes, i); i += 4;"); break; case FieldType.S32: writer.WriteLine("Utils.IntToBytes(" + field.Name + ", bytes, i); i += 4;"); break; case FieldType.U64: writer.WriteLine("Utils.UInt64ToBytes(" + field.Name + ", bytes, i); i += 8;"); break; case FieldType.Variable: //writer.WriteLine("if(" + field.Name + " == null) { Console.WriteLine(\"Warning: " + field.Name + " is null, in \" + this.GetType()); }"); //writer.Write(" "); if (field.Count == 1) { writer.WriteLine("bytes[i++] = (byte)" + field.Name + ".Length;"); } else { writer.WriteLine("bytes[i++] = (byte)(" + field.Name + ".Length % 256);"); writer.WriteLine(" bytes[i++] = (byte)((" + field.Name + ".Length >> 8) % 256);"); } writer.WriteLine(" Buffer.BlockCopy(" + field.Name + ", 0, bytes, i, " + field.Name + ".Length); " + "i += " + field.Name + ".Length;"); break; default: writer.WriteLine("!!! ERROR: Unhandled FieldType: " + field.Type.ToString() + " !!!"); break; } } static int GetFieldLength(TextWriter writer, MapField field) { switch (field.Type) { case FieldType.BOOL: case FieldType.U8: case FieldType.S8: return 1; case FieldType.U16: case FieldType.S16: case FieldType.IPPORT: return 2; case FieldType.U32: case FieldType.S32: case FieldType.F32: case FieldType.IPADDR: return 4; case FieldType.U64: case FieldType.F64: return 8; case FieldType.LLVector3: case FieldType.LLQuaternion: return 12; case FieldType.LLUUID: case FieldType.LLVector4: return 16; case FieldType.LLVector3d: return 24; case FieldType.Fixed: return field.Count; case FieldType.Variable: return 0; default: writer.WriteLine("!!! ERROR: Unhandled FieldType " + field.Type.ToString() + " !!!"); return 0; } } static void WriteBlockClass(TextWriter writer, MapBlock block, MapPacket packet) { int variableFieldCountBytes = 0; //writer.WriteLine(" /// <summary>" + block.Name + " block</summary>"); writer.WriteLine(" /// <exclude/>"); writer.WriteLine(" public sealed class " + block.Name + "Block : PacketBlock" + Environment.NewLine + " {"); foreach (MapField field in block.Fields) { WriteFieldMember(writer, field); if (field.Type == FieldType.Variable) { variableFieldCountBytes += field.Count; } } // Length property writer.WriteLine(""); //writer.WriteLine(" /// <summary>Length of this block serialized in bytes</summary>"); writer.WriteLine(" public override int Length" + Environment.NewLine + " {" + Environment.NewLine + " get" + Environment.NewLine + " {"); int length = variableFieldCountBytes; // Figure out the length of this block foreach (MapField field in block.Fields) { length += GetFieldLength(writer, field); } if (variableFieldCountBytes == 0) { writer.WriteLine(" return " + length + ";"); } else { writer.WriteLine(" int length = " + length + ";"); foreach (MapField field in block.Fields) { if (field.Type == FieldType.Variable) { writer.WriteLine(" if (" + field.Name + " != null) { length += " + field.Name + ".Length; }"); } } writer.WriteLine(" return length;"); } writer.WriteLine(" }" + Environment.NewLine + " }" + Environment.NewLine); // Default constructor //writer.WriteLine(" /// <summary>Default constructor</summary>"); writer.WriteLine(" public " + block.Name + "Block() { }"); // Constructor for building the class from bytes //writer.WriteLine(" /// <summary>Constructor for building the block from a byte array</summary>"); writer.WriteLine(" public " + block.Name + "Block(byte[] bytes, ref int i)" + Environment.NewLine + " {" + Environment.NewLine + " FromBytes(bytes, ref i);" + Environment.NewLine + " }" + Environment.NewLine); // Initiates instance variables from a byte message writer.WriteLine(" public override void FromBytes(byte[] bytes, ref int i)" + Environment.NewLine + " {"); // Declare a length variable if we need it for variable fields in this constructor if (variableFieldCountBytes > 0) { writer.WriteLine(" int length;"); } // Start of the try catch block writer.WriteLine(" try" + Environment.NewLine + " {"); foreach (MapField field in block.Fields) { WriteFieldFromBytes(writer, field); } writer.WriteLine(" }" + Environment.NewLine + " catch (Exception)" + Environment.NewLine + " {" + Environment.NewLine + " throw new MalformedDataException();" + Environment.NewLine + " }" + Environment.NewLine + " }" + Environment.NewLine); // ToBytes() function //writer.WriteLine(" /// <summary>Serialize this block to a byte array</summary>"); writer.WriteLine(" public override void ToBytes(byte[] bytes, ref int i)" + Environment.NewLine + " {"); foreach (MapField field in block.Fields) { WriteFieldToBytes(writer, field); } writer.WriteLine(" }" + Environment.NewLine); writer.WriteLine(" }" + Environment.NewLine); } static void WritePacketClass(TextWriter writer, MapPacket packet) { bool hasVariableBlocks = false; string sanitizedName; //writer.WriteLine(" /// <summary>" + packet.Name + " packet</summary>"); writer.WriteLine(" /// <exclude/>"); writer.WriteLine(" public sealed class " + packet.Name + "Packet : Packet" + Environment.NewLine + " {"); // Write out each block class foreach (MapBlock block in packet.Blocks) { WriteBlockClass(writer, block, packet); } // Length member writer.WriteLine(" public override int Length" + Environment.NewLine + " {" + Environment.NewLine + " get" + Environment.NewLine + " {"); int length = 0; if (packet.Frequency == PacketFrequency.Low) { length = 10; } else if (packet.Frequency == PacketFrequency.Medium) { length = 8; } else { length = 7; } foreach (MapBlock block in packet.Blocks) { if (block.Count == -1) { hasVariableBlocks = true; ++length; } } writer.WriteLine(" int length = " + length + ";"); foreach (MapBlock block in packet.Blocks) { if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { // Variable count block writer.WriteLine(" for (int j = 0; j < " + sanitizedName + ".Length; j++)"); writer.WriteLine(" length += " + sanitizedName + "[j].Length;"); } else if (block.Count == 1) { writer.WriteLine(" length += " + sanitizedName + ".Length;"); } else { // Multiple count block writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)"); writer.WriteLine(" length += " + sanitizedName + "[j].Length;"); } } writer.WriteLine(" return length;"); writer.WriteLine(" }" + Environment.NewLine + " }"); // Block members foreach (MapBlock block in packet.Blocks) { // TODO: More thorough name blacklisting if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } //writer.WriteLine(" /// <summary>" + block.Name + " block</summary>"); writer.WriteLine(" public " + block.Name + "Block" + ((block.Count != 1) ? "[]" : "") + " " + sanitizedName + ";"); } writer.WriteLine(""); // Default constructor //writer.WriteLine(" /// <summary>Default constructor</summary>"); writer.WriteLine(" public " + packet.Name + "Packet()" + Environment.NewLine + " {"); writer.WriteLine(" HasVariableBlocks = " + hasVariableBlocks.ToString().ToLowerInvariant() + ";"); writer.WriteLine(" Type = PacketType." + packet.Name + ";"); writer.WriteLine(" Header = new Header();"); writer.WriteLine(" Header.Frequency = PacketFrequency." + packet.Frequency + ";"); writer.WriteLine(" Header.ID = " + packet.ID + ";"); writer.WriteLine(" Header.Reliable = true;"); // Turn the reliable flag on by default if (packet.Encoded) { writer.WriteLine(" Header.Zerocoded = true;"); } foreach (MapBlock block in packet.Blocks) { if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == 1) { // Single count block writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block();"); } else if (block.Count == -1) { // Variable count block writer.WriteLine(" " + sanitizedName + " = null;"); } else { // Multiple count block writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];"); } } writer.WriteLine(" }" + Environment.NewLine); // Constructor that takes a byte array and beginning position only (no prebuilt header) bool seenVariable = false; //writer.WriteLine(" /// <summary>Constructor that takes a byte array and beginning position (no prebuilt header)</summary>"); writer.WriteLine(" public " + packet.Name + "Packet(byte[] bytes, ref int i) : this()" + Environment.NewLine + " {" + Environment.NewLine + " int packetEnd = bytes.Length - 1;" + Environment.NewLine + " FromBytes(bytes, ref i, ref packetEnd, null);" + Environment.NewLine + " }" + Environment.NewLine); writer.WriteLine(" override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer)" + Environment.NewLine + " {"); writer.WriteLine(" Header.FromBytes(bytes, ref i, ref packetEnd);"); writer.WriteLine(" if (Header.Zerocoded && zeroBuffer != null)"); writer.WriteLine(" {"); writer.WriteLine(" packetEnd = Helpers.ZeroDecode(bytes, packetEnd + 1, zeroBuffer) - 1;"); writer.WriteLine(" bytes = zeroBuffer;"); writer.WriteLine(" }"); foreach (MapBlock block in packet.Blocks) { if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == 1) { // Single count block writer.WriteLine(" " + sanitizedName + ".FromBytes(bytes, ref i);"); } else if (block.Count == -1) { // Variable count block if (!seenVariable) { writer.WriteLine(" int count = (int)bytes[i++];"); seenVariable = true; } else { writer.WriteLine(" count = (int)bytes[i++];"); } writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {"); writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[count];"); writer.WriteLine(" for(int j = 0; j < count; j++)"); writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }"); writer.WriteLine(" }"); writer.WriteLine(" for (int j = 0; j < count; j++)"); writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }"); } else { // Multiple count block writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {"); writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];"); writer.WriteLine(" for(int j = 0; j < " + block.Count + "; j++)"); writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }"); writer.WriteLine(" }"); writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)"); writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }"); } } writer.WriteLine(" }" + Environment.NewLine); seenVariable = false; // Constructor that takes a byte array and a prebuilt header //writer.WriteLine(" /// <summary>Constructor that takes a byte array and a prebuilt header</summary>"); writer.WriteLine(" public " + packet.Name + "Packet(Header head, byte[] bytes, ref int i): this()" + Environment.NewLine + " {" + Environment.NewLine + " int packetEnd = bytes.Length - 1;" + Environment.NewLine + " FromBytes(head, bytes, ref i, ref packetEnd);" + Environment.NewLine + " }" + Environment.NewLine); writer.WriteLine(" override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd)" + Environment.NewLine + " {"); writer.WriteLine(" Header = header;"); foreach (MapBlock block in packet.Blocks) { if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == 1) { // Single count block writer.WriteLine(" " + sanitizedName + ".FromBytes(bytes, ref i);"); } else if (block.Count == -1) { // Variable count block if (!seenVariable) { writer.WriteLine(" int count = (int)bytes[i++];"); seenVariable = true; } else { writer.WriteLine(" count = (int)bytes[i++];"); } writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != count) {"); writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[count];"); writer.WriteLine(" for(int j = 0; j < count; j++)"); writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }"); writer.WriteLine(" }"); writer.WriteLine(" for (int j = 0; j < count; j++)"); writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }"); } else { // Multiple count block writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {"); writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];"); writer.WriteLine(" for(int j = 0; j < " + block.Count + "; j++)"); writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }"); writer.WriteLine(" }"); writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)"); writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }"); } } writer.WriteLine(" }" + Environment.NewLine); #region ToBytes() Function //writer.WriteLine(" /// <summary>Serialize this packet to a byte array</summary><returns>A byte array containing the serialized packet</returns>"); writer.WriteLine(" public override byte[] ToBytes()" + Environment.NewLine + " {"); writer.Write(" int length = "); if (packet.Frequency == PacketFrequency.Low) { writer.WriteLine("10;"); } else if (packet.Frequency == PacketFrequency.Medium) { writer.WriteLine("8;"); } else { writer.WriteLine("7;"); } foreach (MapBlock block in packet.Blocks) { if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == 1) { // Single count block writer.WriteLine(" length += " + sanitizedName + ".Length;"); } } foreach (MapBlock block in packet.Blocks) { if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { writer.WriteLine(" length++;"); writer.WriteLine(" for (int j = 0; j < " + sanitizedName + ".Length; j++) { length += " + sanitizedName + "[j].Length; }"); } else if (block.Count > 1) { writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { length += " + sanitizedName + "[j].Length; }"); } } writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) { length += Header.AckList.Length * 4 + 1; }"); writer.WriteLine(" byte[] bytes = new byte[length];"); writer.WriteLine(" int i = 0;"); writer.WriteLine(" Header.ToBytes(bytes, ref i);"); foreach (MapBlock block in packet.Blocks) { if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { // Variable count block writer.WriteLine(" bytes[i++] = (byte)" + sanitizedName + ".Length;"); writer.WriteLine(" for (int j = 0; j < " + sanitizedName + ".Length; j++) { " + sanitizedName + "[j].ToBytes(bytes, ref i); }"); } else if (block.Count == 1) { writer.WriteLine(" " + sanitizedName + ".ToBytes(bytes, ref i);"); } else { // Multiple count block writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { " + sanitizedName + "[j].ToBytes(bytes, ref i); }"); } } writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); }"); writer.WriteLine(" return bytes;" + Environment.NewLine + " }" + Environment.NewLine); #endregion ToBytes() Function WriteToBytesMultiple(writer, packet); writer.WriteLine(" }" + Environment.NewLine); } static void WriteToBytesMultiple(TextWriter writer, MapPacket packet) { writer.WriteLine( " public override byte[][] ToBytesMultiple()" + Environment.NewLine + " {"); // Check if there are any variable blocks bool hasVariable = false; bool cannotSplit = false; foreach (MapBlock block in packet.Blocks) { if (block.Count == -1) { hasVariable = true; } else if (hasVariable) { // A fixed or single block showed up after a variable count block. // Our automatic splitting algorithm won't work for this packet cannotSplit = true; break; } } if (hasVariable && !cannotSplit) { writer.WriteLine( " System.Collections.Generic.List<byte[]> packets = new System.Collections.Generic.List<byte[]>();"); writer.WriteLine( " int i = 0;"); writer.Write( " int fixedLength = "); if (packet.Frequency == PacketFrequency.Low) { writer.WriteLine("10;"); } else if (packet.Frequency == PacketFrequency.Medium) { writer.WriteLine("8;"); } else { writer.WriteLine("7;"); } writer.WriteLine(); // ACK serialization writer.WriteLine(" byte[] ackBytes = null;"); writer.WriteLine(" int acksLength = 0;"); writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) {"); writer.WriteLine(" Header.AppendedAcks = true;"); writer.WriteLine(" ackBytes = new byte[Header.AckList.Length * 4 + 1];"); writer.WriteLine(" Header.AcksToBytes(ackBytes, ref acksLength);"); writer.WriteLine(" }"); writer.WriteLine(); // Count fixed blocks foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == 1) { // Single count block writer.WriteLine(" fixedLength += " + sanitizedName + ".Length;"); } else if (block.Count > 0) { // Fixed count block writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { fixedLength += " + sanitizedName + "[j].Length; }"); } } // Serialize fixed blocks writer.WriteLine( " byte[] fixedBytes = new byte[fixedLength];"); writer.WriteLine( " Header.ToBytes(fixedBytes, ref i);"); foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == 1) { // Single count block writer.WriteLine(" " + sanitizedName + ".ToBytes(fixedBytes, ref i);"); } else if (block.Count > 0) { // Fixed count block writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { " + sanitizedName + "[j].ToBytes(fixedBytes, ref i); }"); } } int variableCountBlock = 0; foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { // Variable count block ++variableCountBlock; } } writer.WriteLine(" fixedLength += " + variableCountBlock + ";"); writer.WriteLine(); foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { // Variable count block writer.WriteLine(" int " + sanitizedName + "Start = 0;"); } } writer.WriteLine(" do"); writer.WriteLine(" {"); // Count how many variable blocks can go in this packet writer.WriteLine(" int variableLength = 0;"); foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { // Variable count block writer.WriteLine(" int " + sanitizedName + "Count = 0;"); } } writer.WriteLine(); foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { // Variable count block writer.WriteLine(" i = " + sanitizedName + "Start;"); writer.WriteLine(" while (fixedLength + variableLength + acksLength < Packet.MTU && i < " + sanitizedName + ".Length) {"); writer.WriteLine(" int blockLength = " + sanitizedName + "[i].Length;"); writer.WriteLine(" if (fixedLength + variableLength + blockLength + acksLength <= MTU || i == " + sanitizedName + "Start) {"); writer.WriteLine(" variableLength += blockLength;"); writer.WriteLine(" ++" + sanitizedName + "Count;"); writer.WriteLine(" }"); writer.WriteLine(" else { break; }"); writer.WriteLine(" ++i;"); writer.WriteLine(" }"); writer.WriteLine(); } } // Create the packet writer.WriteLine(" byte[] packet = new byte[fixedLength + variableLength + acksLength];"); writer.WriteLine(" int length = fixedBytes.Length;"); writer.WriteLine(" Buffer.BlockCopy(fixedBytes, 0, packet, 0, length);"); // Remove the appended ACKs flag from subsequent packets writer.WriteLine(" if (packets.Count > 0) { packet[0] = (byte)(packet[0] & ~0x10); }"); writer.WriteLine(); foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { writer.WriteLine(" packet[length++] = (byte)" + sanitizedName + "Count;"); writer.WriteLine(" for (i = " + sanitizedName + "Start; i < " + sanitizedName + "Start + " + sanitizedName + "Count; i++) { " + sanitizedName + "[i].ToBytes(packet, ref length); }"); writer.WriteLine(" " + sanitizedName + "Start += " + sanitizedName + "Count;"); writer.WriteLine(); } } // ACK appending writer.WriteLine(" if (acksLength > 0) {"); writer.WriteLine(" Buffer.BlockCopy(ackBytes, 0, packet, length, acksLength);"); writer.WriteLine(" acksLength = 0;"); writer.WriteLine(" }"); writer.WriteLine(); writer.WriteLine(" packets.Add(packet);"); writer.WriteLine(" } while ("); bool first = true; foreach (MapBlock block in packet.Blocks) { string sanitizedName; if (block.Name == "Header") { sanitizedName = "_" + block.Name; } else { sanitizedName = block.Name; } if (block.Count == -1) { if (first) first = false; else writer.WriteLine(" ||"); // Variable count block writer.Write(" " + sanitizedName + "Start < " + sanitizedName + ".Length"); } } writer.WriteLine(");"); writer.WriteLine(); writer.WriteLine(" return packets.ToArray();"); writer.WriteLine(" }"); } else { writer.WriteLine(" return new byte[][] { ToBytes() };"); writer.WriteLine(" }"); } } static int Main(string[] args) { ProtocolManager protocol; List<string> unused = new List<string>(); TextWriter writer; try { if (args.Length != 4) { Console.WriteLine("Usage: [message_template.msg] [template.cs] [unusedpackets.txt] [_Packets_.cs]"); return -1; } writer = new StreamWriter(args[3]); protocol = new ProtocolManager(args[0]); // Build a list of unused packets using (StreamReader unusedReader = new StreamReader(args[2])) { while (unusedReader.Peek() >= 0) { unused.Add(unusedReader.ReadLine().Trim()); } } // Read in the template.cs file and write it to our output TextReader reader = new StreamReader(args[1]); writer.WriteLine(reader.ReadToEnd()); reader.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); return -2; } // Prune all of the unused packets out of the protocol int i = 0; foreach (MapPacket packet in protocol.LowMaps) { if (packet != null && unused.Contains(packet.Name)) protocol.LowMaps[i] = null; i++; } i = 0; foreach (MapPacket packet in protocol.MediumMaps) { if (packet != null && unused.Contains(packet.Name)) protocol.MediumMaps[i] = null; i++; } i = 0; foreach (MapPacket packet in protocol.HighMaps) { if (packet != null && unused.Contains(packet.Name)) protocol.HighMaps[i] = null; i++; } // Write the PacketType enum writer.WriteLine(" public enum PacketType" + Environment.NewLine + " {" + Environment.NewLine + " /// <summary>A generic value, not an actual packet type</summary>" + Environment.NewLine + " Default,"); foreach (MapPacket packet in protocol.LowMaps) if (packet != null) writer.WriteLine(" " + packet.Name + " = " + (0x10000 | packet.ID) + ","); foreach (MapPacket packet in protocol.MediumMaps) if (packet != null) writer.WriteLine(" " + packet.Name + " = " + (0x20000 | packet.ID) + ","); foreach (MapPacket packet in protocol.HighMaps) if (packet != null) writer.WriteLine(" " + packet.Name + " = " + (0x30000 | packet.ID) + ","); writer.WriteLine(" }" + Environment.NewLine); // Write the base Packet class writer.WriteLine( " public abstract partial class Packet" + Environment.NewLine + " {" + Environment.NewLine + " public const int MTU = 1200;" + Environment.NewLine + Environment.NewLine + " public Header Header;" + Environment.NewLine + " public bool HasVariableBlocks;" + Environment.NewLine + " public PacketType Type;" + Environment.NewLine + " public abstract int Length { get; }" + Environment.NewLine + " public abstract void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer);" + Environment.NewLine + " public abstract void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd);" + Environment.NewLine + " public abstract byte[] ToBytes();" + Environment.NewLine + " public abstract byte[][] ToBytesMultiple();" ); writer.WriteLine(); // Write the Packet.GetType() function writer.WriteLine( " public static PacketType GetType(ushort id, PacketFrequency frequency)" + Environment.NewLine + " {" + Environment.NewLine + " switch (frequency)" + Environment.NewLine + " {" + Environment.NewLine + " case PacketFrequency.Low:" + Environment.NewLine + " switch (id)" + Environment.NewLine + " {"); foreach (MapPacket packet in protocol.LowMaps) if (packet != null) writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";"); writer.WriteLine(" }" + Environment.NewLine + " break;" + Environment.NewLine + " case PacketFrequency.Medium:" + Environment.NewLine + " switch (id)" + Environment.NewLine + " {"); foreach (MapPacket packet in protocol.MediumMaps) if (packet != null) writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";"); writer.WriteLine(" }" + Environment.NewLine + " break;" + Environment.NewLine + " case PacketFrequency.High:" + Environment.NewLine + " switch (id)" + Environment.NewLine + " {"); foreach (MapPacket packet in protocol.HighMaps) if (packet != null) writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";"); writer.WriteLine(" }" + Environment.NewLine + " break;" + Environment.NewLine + " }" + Environment.NewLine + Environment.NewLine + " return PacketType.Default;" + Environment.NewLine + " }" + Environment.NewLine); // Write the Packet.BuildPacket(PacketType) function writer.WriteLine(" public static Packet BuildPacket(PacketType type)"); writer.WriteLine(" {"); foreach (MapPacket packet in protocol.HighMaps) if (packet != null) writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();"); foreach (MapPacket packet in protocol.MediumMaps) if (packet != null) writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();"); foreach (MapPacket packet in protocol.LowMaps) if (packet != null) writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();"); writer.WriteLine(" return null;" + Environment.NewLine); writer.WriteLine(" }"); // Write the Packet.BuildPacket() function writer.WriteLine(@" public static Packet BuildPacket(byte[] packetBuffer, ref int packetEnd, byte[] zeroBuffer) { byte[] bytes; int i = 0; Header header = Header.BuildHeader(packetBuffer, ref i, ref packetEnd); if (header.Zerocoded) { packetEnd = Helpers.ZeroDecode(packetBuffer, packetEnd + 1, zeroBuffer) - 1; bytes = zeroBuffer; } else { bytes = packetBuffer; } Array.Clear(bytes, packetEnd + 1, bytes.Length - packetEnd - 1); switch (header.Frequency) { case PacketFrequency.Low: switch (header.ID) {"); foreach (MapPacket packet in protocol.LowMaps) if (packet != null) writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);"); writer.WriteLine(@" } break; case PacketFrequency.Medium: switch (header.ID) {"); foreach (MapPacket packet in protocol.MediumMaps) if (packet != null) writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);"); writer.WriteLine(@" } break; case PacketFrequency.High: switch (header.ID) {"); foreach (MapPacket packet in protocol.HighMaps) if (packet != null) writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);"); writer.WriteLine(@" } break; } throw new MalformedDataException(""Unknown packet ID "" + header.Frequency + "" "" + header.ID); } }"); // Write the packet classes foreach (MapPacket packet in protocol.LowMaps) if (packet != null) { WritePacketClass(writer, packet); } foreach (MapPacket packet in protocol.MediumMaps) if (packet != null) { WritePacketClass(writer, packet); } foreach (MapPacket packet in protocol.HighMaps) if (packet != null) { WritePacketClass(writer, packet); } // Finish up writer.WriteLine("}"); writer.Close(); return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Xml.Schema; using Xunit; using Xunit.Abstractions; namespace System.Xml.Tests { // ===================== Constructor ===================== public class TCConstructor : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCConstructor(ITestOutputHelper output): base(output) { _output = output; } [Fact] public void SetXmlNameTableToNull() { XmlSchemaValidator val; try { val = new XmlSchemaValidator(null, new XmlSchemaSet(), new XmlNamespaceManager(new NameTable()), AllFlags); } catch (ArgumentNullException) { return; } _output.WriteLine("ArgumentNullException was not thrown!"); Assert.True(false); } [Theory] [InlineData("empty")] [InlineData("full")] public void SetXmlNameTableTo_Empty_Full(string nameTableStatus) { XmlSchemaValidator val; ObservedNameTable nt = new ObservedNameTable(); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaSet sch = CreateSchemaSetFromXml("<root />"); if (nameTableStatus == "full") { nt.Add("root"); nt.Add("foo"); nt.IsAddCalled = false; nt.IsGetCalled = false; } val = new XmlSchemaValidator(nt, sch, new XmlNamespaceManager(new NameTable()), AllFlags); Assert.NotEqual(val, null); val.Initialize(); val.ValidateElement("root", "", info); Assert.True(nt.IsAddCalled); Assert.Equal(nt.IsGetCalled, false); return; } [Fact] public void SetSchemaSetToNull() { XmlSchemaValidator val; try { val = new XmlSchemaValidator(new NameTable(), null, new XmlNamespaceManager(new NameTable()), AllFlags); } catch (ArgumentNullException) { return; } _output.WriteLine("ArgumentNullException was not thrown!"); Assert.True(false); } [Theory] [InlineData("empty")] [InlineData("notcompiled")] [InlineData("compiled")] public void SetSchemaSetTo_Empty_NotCompiled_Compiled(string schemaSetStatus) { XmlSchemaValidator val; XmlSchemaSet sch = new XmlSchemaSet(); if (schemaSetStatus != "empty") { sch.Add("", Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE)); if (schemaSetStatus == "compiled") sch.Compile(); } val = new XmlSchemaValidator(new NameTable(), sch, new XmlNamespaceManager(new NameTable()), AllFlags); Assert.NotEqual(val, null); val.Initialize(); val.ValidateElement("elem1", "", null); val.SkipToEndElement(null); val.EndValidation(); return; } // BUG 304774 - resolved [Fact] public void SetSchemaSetWithInvalidContent_TypeCollision() { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaSet sch = new XmlSchemaSet(); sch.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:int\" />\n" + "</xs:schema>"))); sch.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:string\" />\n" + "</xs:schema>"))); try { val = new XmlSchemaValidator(new NameTable(), sch, new XmlNamespaceManager(new NameTable()), AllFlags); } catch (XmlSchemaValidationException) { return; } return; } [Fact] public void CustomXmlNameSpaceResolverImplementation() { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaSet sch = new XmlSchemaSet(); ObservedNamespaceManager nsManager = new ObservedNamespaceManager(new NameTable()); nsManager.AddNamespace("n1", "uri:tempuri"); val = new XmlSchemaValidator(new NameTable(), sch, nsManager, AllFlags); val.AddSchema(XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:n1=\"uri:tempuri\"\n" + " targetNamespace=\"uri:tempuri1\">\n" + " <xs:complexType name=\"foo\">\n" + " <xs:sequence>\n" + " <xs:element name=\"bar\" />\n" + " </xs:sequence>\n" + " </xs:complexType>\n" + "</xs:schema>")), null)); val.Initialize(); val.ValidateElement("root", "", info, "n1:foo", null, null, null); Assert.True(nsManager.IsLookupNamespaceCalled); return; } } // ===================== AddSchema ===================== public class TCAddSchema : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCAddSchema(ITestOutputHelper output): base(output) { _output = output; } [Fact] public void PassNull() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); try { val.AddSchema(null); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void CheckDeepCopyOfXmlSchema() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchema s = new XmlSchema(); XmlSchemaElement e1 = new XmlSchemaElement(); XmlSchemaElement e2 = new XmlSchemaElement(); e1.Name = "foo"; e2.Name = "bar"; s.Items.Add(e1); val.AddSchema(s); s.Items.Add(e2); val.Initialize(); try { val.ValidateElement("bar", "", info); } catch (XmlSchemaValidationException) { return; } Assert.True(false); } [Fact] public void AddSameXmlSchemaTwice() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchema s; s = XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" />\n" + "</xs:schema>")), null); val.AddSchema(s); val.AddSchema(s); val.Initialize(); val.ValidateElement("root", "", info); return; } [Fact] public void AddSameXmlSchemaWithTargetNamespaceTwice() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchema s; s = XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:n1=\"uri:tempuri\"\n" + " targetNamespace=\"uri:tempuri\">\n" + " <xs:element name=\"root\" />\n" + "</xs:schema>")), null); val.AddSchema(s); val.AddSchema(s); val.Initialize(); val.ValidateElement("root", "uri:tempuri", info); return; } [Fact] public void AddSchemasWithTypeCollision() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); XmlSchemaInfo info = new XmlSchemaInfo(); val.AddSchema(XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:string\" />\n" + "</xs:schema>")), null)); try { val.AddSchema(XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:boolean\" />\n" + "</xs:schema>")), null)); } catch (XmlSchemaValidationException) { return; } Assert.True(false); } [Fact] public void ValidateThenAddAdditionalSchemas() { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); val = CreateValidator(new XmlSchemaSet()); val.AddSchema(XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " targetNamespace=\"uri:tempuri1\">\n" + " <xs:element name=\"foo\" type=\"xs:string\" />\n" + "</xs:schema>")), null)); val.Initialize(); val.ValidateElement("foo", "uri:tempuri1", info); val.SkipToEndElement(info); val.AddSchema(XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " targetNamespace=\"uri:tempuri2\">\n" + " <xs:element name=\"bar\" type=\"xs:string\" />\n" + "</xs:schema>")), null)); val.ValidateElement("bar", "uri:tempuri2", info); val.SkipToEndElement(info); val.EndValidation(); return; } [Theory] [InlineData(true)] [InlineData(false)] public void ImportAnotherSchemaThat_Is_IsNot_InSchemaSet(bool importTwice) { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); Uri u = new Uri(Uri.UriSchemeFile + Uri.SchemeDelimiter + Path.Combine(Path.GetFullPath(TestData), XSDFILE_TARGET_NAMESPACE)); XmlSchema s1; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.XmlResolver = new XmlUrlResolver(); val = CreateValidator(new XmlSchemaSet()); s1 = XmlSchema.Read(new StringReader("<?xml version=\"1.0\"?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:temp=\"uri:tempuri\">\n" + " <xs:import namespace=\"uri:tempuri\"\n" + " schemaLocation=\"" + u.AbsoluteUri + "\" />\n" + " <xs:element name=\"root\">\n" + " <xs:complexType>\n" + " <xs:sequence>\n" + " <xs:element ref=\"temp:elem1\" />\n" + " </xs:sequence>\n" + " </xs:complexType>\n" + " </xs:element>\n" + "</xs:schema>"), null); schemas.Add(s1); if (importTwice) { foreach (XmlSchema s in schemas.Schemas("uri:tempuri")) val.AddSchema(s); } val.AddSchema(s1); val.Initialize(); val.ValidateElement("root", "", info); val.ValidateEndOfAttributes(null); val.ValidateElement("elem1", "uri:tempuri", info); val.ValidateEndOfAttributes(null); val.ValidateEndElement(info); val.ValidateEndElement(info); val.EndValidation(); return; } //(BUG #306858) [Fact] public void SetIgnoreInlineSchemaFlag_AddSchemaShouldDoNothing() { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); val = CreateValidator(CreateSchemaSetFromXml("<root />"), XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation); val.AddSchema(XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"foo\" type=\"xs:string\" />\n" + "</xs:schema>")), null)); val.Initialize(); try { val.ValidateElement("foo", "", info); throw new Exception("Additional schema was loaded!"); } catch (XmlSchemaValidationException) { return; } } } }
using System.Security; using System; using System.Runtime.InteropServices; using System.Reflection; [SecurityCriticalAttribute] public class CClass { public CClass () { //Console.WriteLine ("c ctor"); } public virtual void Method () { //Console.WriteLine ("c class"); } public static void StaticMethod () { //Console.WriteLine ("c class static"); } } [SecuritySafeCriticalAttribute] public class SCClass { public SCClass () { //Console.WriteLine ("sc ctor"); } public virtual void Method () { //Console.WriteLine ("sc class"); CClass cc = new CClass (); cc.Method (); } } public class SCDevClass : SCClass { public SCDevClass () { Test.error ("safe-critical-derived class instantiated"); } public override void Method () { //base.Method (); Test.error ("safe-critical-derived method called"); } } public class CMethodClass { public CMethodClass () { //Console.WriteLine ("cmethod ctor"); } [SecurityCriticalAttribute] public virtual void Method () { //Console.WriteLine ("cmethod"); } } public class CMethodDevClass : CMethodClass { public CMethodDevClass () { Test.error ("critical-derived constructor called"); } public override void Method () { //base.Method(); Test.error ("critical-derived method called"); } } public interface CMethodInterface { [SecurityCriticalAttribute] void Method (); } public class CInterfaceClass : CMethodInterface { public CInterfaceClass () { } public void Method () { Test.error ("security-critical-interface-derived method called"); } } [SecurityCriticalAttribute] public class CriticalClass { public class NestedClassInsideCritical { static public void Method () { Test.error ("critical inner class method called"); } } } public class TransparentBaseClass { public virtual void TransparentMethod () { } [SecuritySafeCritical] public virtual void SafeCriticalMethod () { } [SecurityCritical] public virtual void CriticalMethod () { } } public class BadTransparentOverrideClass : TransparentBaseClass { [SecurityCritical] public override void TransparentMethod () { Test.error ("this method is critical and cannot override its base (transparent)"); } } public class BadSafeCriticalOverrideClass : TransparentBaseClass { [SecurityCritical] public override void SafeCriticalMethod () { Test.error ("this method is critical and cannot override its base (safe critical)"); } } public class BadCriticalOverrideClass : TransparentBaseClass { public override void CriticalMethod () { Test.error ("this method is NOT critical and cannot override its base (critical)"); } } public delegate void MethodDelegate (); public delegate Object InvokeDelegate (Object obj, Object[] parms); // the 0.1% case from http://blogs.msdn.com/shawnfa/archive/2007/05/11/silverlight-security-iii-inheritance.aspx public class TransparentClassWithSafeCriticalDefaultConstructor { [SecuritySafeCritical] public TransparentClassWithSafeCriticalDefaultConstructor () { } } public class TransparentInheritFromSafeCriticalDefaultConstructor : TransparentClassWithSafeCriticalDefaultConstructor { public TransparentInheritFromSafeCriticalDefaultConstructor () { } } public class SafeInheritFromSafeCriticalDefaultConstructor : TransparentClassWithSafeCriticalDefaultConstructor { [SecuritySafeCritical] public SafeInheritFromSafeCriticalDefaultConstructor () { } } public class Test { static bool haveError = false; public static void error (string text) { Console.WriteLine (text); haveError = true; } [SecurityCriticalAttribute] static void CMethod () { //Console.WriteLine ("c"); } [SecuritySafeCriticalAttribute] static void SCMethod () { //Console.WriteLine ("sc"); CMethod (); } static void doSCDev () { SCDevClass scdev = new SCDevClass (); scdev.Method (); } static void doCMethodDev () { CMethodDevClass cmdev = new CMethodDevClass (); error ("critical-derived object instantiated"); cmdev.Method (); Console.WriteLine ("critical-derived method called"); } static void doSCInterfaceDev () { CMethodInterface mi = new CInterfaceClass (); error ("safe-critical-interface-derived object instantiated"); mi.Method (); error ("safe-critical-interface-derived method called"); } /* static unsafe void unsafeMethod () { byte *p = null; error ("unsafe method called"); } */ static void doBadTransparentOverrideClass () { new BadTransparentOverrideClass (); } static void doBadSafeCriticalOverrideClass () { new BadSafeCriticalOverrideClass (); } static void doBadCriticalOverrideClass () { new BadCriticalOverrideClass (); } public static void TransparentReflectionCMethod () { } [SecurityCriticalAttribute] public static void ReflectionCMethod () { error ("method called via reflection"); } [SecurityCriticalAttribute] public static unsafe void StringTest () { string str = "blabla"; char [] arr = str.ToCharArray (); string r; fixed (char *tarr = arr) { int ss = 1, l = 3; r = new string (tarr, ss, l - ss); } } [SecuritySafeCriticalAttribute] public static void CallStringTest () { StringTest (); } [DllImport ("/lib64/libc.so.6")] static extern int getpid (); static void ArraysCreatedByTransparentCaller () { // Transparent creating an array of a Critical type // using Class[] (rank == 1) throws a TypeLoadException on SL2 - but that looks like a bug // reported as https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=490406 CClass[] c_array = new CClass [0]; // Transparent creating an array of a SafeCritical type SCClass[] sc_array = new SCClass [0]; // Transparent creating a multidimentional array of a Critical type CClass[,] c_multi = new CClass [0,0]; // Transparent creating a multidimentional array of a SafeCritical type SCClass[,] sc_multi = new SCClass [0,0]; // Transparent creating a jagged array of a Critical type CClass[][] c_jagged = new CClass [0][]; // Transparent creating a jagged array of a Critical type SCClass[][] sc_jagged = new SCClass [0][]; } [SecuritySafeCritical] static void ArraysCreatedBySafeCriticalCaller () { // SafeCritical creating an array of a Critical type CClass[] c_array = new CClass [0]; // SafeCritical creating an array of a SafeCritical type SCClass[] sc_array = new SCClass [0]; // SafeCritical creating a multidimentional array of a Critical type CClass[,] c_multi = new CClass [0,0]; // SafeCritical creating a multidimentional array of a SafeCritical type SCClass[,] sc_multi = new SCClass [0,0]; // SafeCritical creating a jagged array of a Critical type CClass[][] c_jagged = new CClass [0][]; // SafeCritical creating a jagged array of a Critical type SCClass[][] sc_jagged = new SCClass [0][]; // Transparent Main could not call a critical method by itself ArraysCreatedByCriticalCaller (); } [SecurityCritical] static void ArraysCreatedByCriticalCaller () { // Critical creating an array of a Critical type CClass[] c_array = new CClass [0]; // Critical creating an array of a SafeCritical type SCClass[] sc_array = new SCClass [0]; // Critical creating a multidimentional array of a Critical type CClass[,] c_multi = new CClass [0,0]; // Critical creating a multidimentional array of a SafeCritical type SCClass[,] sc_multi = new SCClass [0,0]; // Critical creating a jagged array of a Critical type CClass[][] c_jagged = new CClass [0][]; // Critical creating a jagged array of a Critical type SCClass[][] sc_jagged = new SCClass [0][]; } public static int Main () { SCMethod (); try { CMethod (); error ("static critical method called"); } catch (MethodAccessException) { } SCClass sc = new SCClass (); sc.Method (); try { CClass c = new CClass (); // Illegal error ("critical object instantiated"); c.Method (); // Illegal error ("critical method called"); } catch (MethodAccessException) { } try { doSCDev (); error ("security-critical-derived class error"); } catch (TypeLoadException) { } try { doCMethodDev (); } catch (TypeLoadException) { } try { getpid (); error ("pinvoke called"); } catch (MethodAccessException) { } try { MethodDelegate md = new MethodDelegate (CClass.StaticMethod); md (); error ("critical method called via delegate"); } catch (MethodAccessException) { } try { CriticalClass.NestedClassInsideCritical.Method (); } catch (MethodAccessException) { } try { doSCInterfaceDev (); } catch (TypeLoadException) { } /* try { unsafeMethod (); } catch (VerificationException) { } */ try { Type type = Type.GetType ("Test"); MethodInfo method = type.GetMethod ("TransparentReflectionCMethod"); method.Invoke(null, null); } catch (MethodAccessException) { error ("transparent method not called via reflection"); } try { Type type = Type.GetType ("Test"); MethodInfo method = type.GetMethod ("ReflectionCMethod"); method.Invoke(null, null); } catch (MethodAccessException) { } try { Type type = Type.GetType ("Test"); MethodInfo method = type.GetMethod ("TransparentReflectionCMethod"); InvokeDelegate id = new InvokeDelegate (method.Invoke); id (null, null); } catch (MethodAccessException) { error ("transparent method not called via reflection delegate"); } try { Type type = Type.GetType ("Test"); MethodInfo method = type.GetMethod ("ReflectionCMethod"); InvokeDelegate id = new InvokeDelegate (method.Invoke); id (null, null); } catch (MethodAccessException) { } // wrapper 7 try { CallStringTest (); } catch (MethodAccessException) { error ("string test failed"); } try { doBadTransparentOverrideClass (); error ("BadTransparentOverrideClass error"); } catch (TypeLoadException) { } try { doBadSafeCriticalOverrideClass (); error ("BadSafeCriticalOverrideClass error"); } catch (TypeLoadException) { } try { doBadCriticalOverrideClass (); error ("BadCriticalOverrideClass error"); } catch (TypeLoadException) { } new TransparentClassWithSafeCriticalDefaultConstructor (); try { new TransparentInheritFromSafeCriticalDefaultConstructor (); } catch (TypeLoadException) { } new SafeInheritFromSafeCriticalDefaultConstructor (); // arrays creation tests ArraysCreatedByTransparentCaller (); ArraysCreatedBySafeCriticalCaller (); // the above also calls ArraysCreatedBySafeCriticalCaller since (Transparent) Main cannot call it directly if (haveError) return 1; // Console.WriteLine ("ok"); return 0; } }
using System; using System.Collections.Generic; using System.Text; namespace PlayFab { /// <summary> /// Error codes returned by PlayFabAPIs /// </summary> public enum PlayFabErrorCode { Unknown = 1, Success = 0, UnkownError = 500, InvalidParams = 1000, AccountNotFound = 1001, AccountBanned = 1002, InvalidUsernameOrPassword = 1003, InvalidTitleId = 1004, InvalidEmailAddress = 1005, EmailAddressNotAvailable = 1006, InvalidUsername = 1007, InvalidPassword = 1008, UsernameNotAvailable = 1009, InvalidSteamTicket = 1010, AccountAlreadyLinked = 1011, LinkedAccountAlreadyClaimed = 1012, InvalidFacebookToken = 1013, AccountNotLinked = 1014, FailedByPaymentProvider = 1015, CouponCodeNotFound = 1016, InvalidContainerItem = 1017, ContainerNotOwned = 1018, KeyNotOwned = 1019, InvalidItemIdInTable = 1020, InvalidReceipt = 1021, ReceiptAlreadyUsed = 1022, ReceiptCancelled = 1023, GameNotFound = 1024, GameModeNotFound = 1025, InvalidGoogleToken = 1026, UserIsNotPartOfDeveloper = 1027, InvalidTitleForDeveloper = 1028, TitleNameConflicts = 1029, UserisNotValid = 1030, ValueAlreadyExists = 1031, BuildNotFound = 1032, PlayerNotInGame = 1033, InvalidTicket = 1034, InvalidDeveloper = 1035, InvalidOrderInfo = 1036, RegistrationIncomplete = 1037, InvalidPlatform = 1038, UnknownError = 1039, SteamApplicationNotOwned = 1040, WrongSteamAccount = 1041, TitleNotActivated = 1042, RegistrationSessionNotFound = 1043, NoSuchMod = 1044, FileNotFound = 1045, DuplicateEmail = 1046, ItemNotFound = 1047, ItemNotOwned = 1048, ItemNotRecycleable = 1049, ItemNotAffordable = 1050, InvalidVirtualCurrency = 1051, WrongVirtualCurrency = 1052, WrongPrice = 1053, NonPositiveValue = 1054, InvalidRegion = 1055, RegionAtCapacity = 1056, ServerFailedToStart = 1057, NameNotAvailable = 1058, InsufficientFunds = 1059, InvalidDeviceID = 1060, InvalidPushNotificationToken = 1061, NoRemainingUses = 1062, InvalidPaymentProvider = 1063, PurchaseInitializationFailure = 1064, DuplicateUsername = 1065, InvalidBuyerInfo = 1066, NoGameModeParamsSet = 1067, BodyTooLarge = 1068, ReservedWordInBody = 1069, InvalidTypeInBody = 1070, InvalidRequest = 1071, ReservedEventName = 1072, InvalidUserStatistics = 1073, NotAuthenticated = 1074, StreamAlreadyExists = 1075, ErrorCreatingStream = 1076, StreamNotFound = 1077, InvalidAccount = 1078, PurchaseDoesNotExist = 1080, InvalidPurchaseTransactionStatus = 1081, APINotEnabledForGameClientAccess = 1082, NoPushNotificationARNForTitle = 1083, BuildAlreadyExists = 1084, BuildPackageDoesNotExist = 1085, CustomAnalyticsEventsNotEnabledForTitle = 1087, InvalidSharedGroupId = 1088, NotAuthorized = 1089, MissingTitleGoogleProperties = 1090, InvalidItemProperties = 1091, InvalidPSNAuthCode = 1092, InvalidItemId = 1093, PushNotEnabledForAccount = 1094, PushServiceError = 1095, ReceiptDoesNotContainInAppItems = 1096, ReceiptContainsMultipleInAppItems = 1097, InvalidBundleID = 1098, JavascriptException = 1099, InvalidSessionTicket = 1100, UnableToConnectToDatabase = 1101, InternalServerError = 1110, InvalidReportDate = 1111, ReportNotAvailable = 1112, DatabaseThroughputExceeded = 1113, InvalidGameTicket = 1115, ExpiredGameTicket = 1116, GameTicketDoesNotMatchLobby = 1117, LinkedDeviceAlreadyClaimed = 1118, DeviceAlreadyLinked = 1119, DeviceNotLinked = 1120, PartialFailure = 1121, PublisherNotSet = 1122, ServiceUnavailable = 1123, VersionNotFound = 1124, RevisionNotFound = 1125, InvalidPublisherId = 1126, DownstreamServiceUnavailable = 1127, APINotIncludedInTitleUsageTier = 1128, DAULimitExceeded = 1129, APIRequestLimitExceeded = 1130, InvalidAPIEndpoint = 1131, BuildNotAvailable = 1132, ConcurrentEditError = 1133, ContentNotFound = 1134, CharacterNotFound = 1135, CloudScriptNotFound = 1136, ContentQuotaExceeded = 1137, InvalidCharacterStatistics = 1138, PhotonNotEnabledForTitle = 1139, PhotonApplicationNotFound = 1140, PhotonApplicationNotAssociatedWithTitle = 1141, InvalidEmailOrPassword = 1142, FacebookAPIError = 1143, InvalidContentType = 1144, KeyLengthExceeded = 1145, DataLengthExceeded = 1146, TooManyKeys = 1147, FreeTierCannotHaveVirtualCurrency = 1148, MissingAmazonSharedKey = 1149, AmazonValidationError = 1150, InvalidPSNIssuerId = 1151, PSNInaccessible = 1152, ExpiredAuthToken = 1153, FailedToGetEntitlements = 1154, FailedToConsumeEntitlement = 1155, TradeAcceptingUserNotAllowed = 1156, TradeInventoryItemIsAssignedToCharacter = 1157, TradeInventoryItemIsBundle = 1158, TradeStatusNotValidForCancelling = 1159, TradeStatusNotValidForAccepting = 1160, TradeDoesNotExist = 1161, TradeCancelled = 1162, TradeAlreadyFilled = 1163, TradeWaitForStatusTimeout = 1164, TradeInventoryItemExpired = 1165, TradeMissingOfferedAndAcceptedItems = 1166, TradeAcceptedItemIsBundle = 1167, TradeAcceptedItemIsStackable = 1168, TradeInventoryItemInvalidStatus = 1169, TradeAcceptedCatalogItemInvalid = 1170, TradeAllowedUsersInvalid = 1171, TradeInventoryItemDoesNotExist = 1172, TradeInventoryItemIsConsumed = 1173, TradeInventoryItemIsStackable = 1174, TradeAcceptedItemsMismatch = 1175, InvalidKongregateToken = 1176, FeatureNotConfiguredForTitle = 1177, NoMatchingCatalogItemForReceipt = 1178, InvalidCurrencyCode = 1179, NoRealMoneyPriceForCatalogItem = 1180, TradeInventoryItemIsNotTradable = 1181, TradeAcceptedCatalogItemIsNotTradable = 1182, UsersAlreadyFriends = 1183, LinkedIdentifierAlreadyClaimed = 1184, CustomIdNotLinked = 1185, TotalDataSizeExceeded = 1186, DeleteKeyConflict = 1187, InvalidXboxLiveToken = 1188, ExpiredXboxLiveToken = 1189, ResettableStatisticVersionRequired = 1190, NotAuthorizedByTitle = 1191, NoPartnerEnabled = 1192, InvalidPartnerResponse = 1193, APINotEnabledForGameServerAccess = 1194, StatisticNotFound = 1195, StatisticNameConflict = 1196, StatisticVersionClosedForWrites = 1197, StatisticVersionInvalid = 1198, APIClientRequestRateLimitExceeded = 1199, InvalidJSONContent = 1200, InvalidDropTable = 1201, StatisticVersionAlreadyIncrementedForScheduledInterval = 1202, StatisticCountLimitExceeded = 1203, StatisticVersionIncrementRateExceeded = 1204, ContainerKeyInvalid = 1205, CloudScriptExecutionTimeLimitExceeded = 1206, NoWritePermissionsForEvent = 1207, CloudScriptFunctionArgumentSizeExceeded = 1208, CloudScriptAPIRequestCountExceeded = 1209, CloudScriptAPIRequestError = 1210, CloudScriptHTTPRequestError = 1211, InsufficientGuildRole = 1212, GuildNotFound = 1213, OverLimit = 1214, EventNotFound = 1215, InvalidEventField = 1216, InvalidEventName = 1217, CatalogNotConfigured = 1218, OperationNotSupportedForPlatform = 1219, SegmentNotFound = 1220, StoreNotFound = 1221, InvalidStatisticName = 1222, TitleNotQualifiedForLimit = 1223, InvalidServiceLimitLevel = 1224, ServiceLimitLevelInTransition = 1225, CouponAlreadyRedeemed = 1226, GameServerBuildSizeLimitExceeded = 1227, GameServerBuildCountLimitExceeded = 1228, VirtualCurrencyCountLimitExceeded = 1229, VirtualCurrencyCodeExists = 1230, TitleNewsItemCountLimitExceeded = 1231, InvalidTwitchToken = 1232, TwitchResponseError = 1233, ProfaneDisplayName = 1234, UserAlreadyAdded = 1235, InvalidVirtualCurrencyCode = 1236, VirtualCurrencyCannotBeDeleted = 1237, IdentifierAlreadyClaimed = 1238, IdentifierNotLinked = 1239, InvalidContinuationToken = 1240, ExpiredContinuationToken = 1241, InvalidSegment = 1242, InvalidSessionId = 1243, SessionLogNotFound = 1244, InvalidSearchTerm = 1245, TwoFactorAuthenticationTokenRequired = 1246, GameServerHostCountLimitExceeded = 1247, PlayerTagCountLimitExceeded = 1248, RequestAlreadyRunning = 1249, ActionGroupNotFound = 1250, MaximumSegmentBulkActionJobsRunning = 1251, NoActionsOnPlayersInSegmentJob = 1252, DuplicateStatisticName = 1253, ScheduledTaskNameConflict = 1254, ScheduledTaskCreateConflict = 1255, InvalidScheduledTaskName = 1256, InvalidTaskSchedule = 1257, SteamNotEnabledForTitle = 1258, LimitNotAnUpgradeOption = 1259, NoSecretKeyEnabledForCloudScript = 1260, TaskNotFound = 1261, TaskInstanceNotFound = 1262, InvalidIdentityProviderId = 1263, MisconfiguredIdentityProvider = 1264, InvalidScheduledTaskType = 1265, BillingInformationRequired = 1266, LimitedEditionItemUnavailable = 1267, InvalidAdPlacementAndReward = 1268, AllAdPlacementViewsAlreadyConsumed = 1269, GoogleOAuthNotConfiguredForTitle = 1270, GoogleOAuthError = 1271, UserNotFriend = 1272, InvalidSignature = 1273, InvalidPublicKey = 1274, GoogleOAuthNoIdTokenIncludedInResponse = 1275, StatisticUpdateInProgress = 1276, LeaderboardVersionNotAvailable = 1277, StatisticAlreadyHasPrizeTable = 1279, PrizeTableHasOverlappingRanks = 1280, PrizeTableHasMissingRanks = 1281, PrizeTableRankStartsAtZero = 1282, InvalidStatistic = 1283, ExpressionParseFailure = 1284, ExpressionInvokeFailure = 1285, ExpressionTooLong = 1286, DataUpdateRateExceeded = 1287, RestrictedEmailDomain = 1288, EncryptionKeyDisabled = 1289, EncryptionKeyMissing = 1290, EncryptionKeyBroken = 1291, NoSharedSecretKeyConfigured = 1292, SecretKeyNotFound = 1293, PlayerSecretAlreadyConfigured = 1294, APIRequestsDisabledForTitle = 1295, InvalidSharedSecretKey = 1296, PrizeTableHasNoRanks = 1297, ProfileDoesNotExist = 1298, ContentS3OriginBucketNotConfigured = 1299, InvalidEnvironmentForReceipt = 1300, EncryptedRequestNotAllowed = 1301, SignedRequestNotAllowed = 1302, RequestViewConstraintParamsNotAllowed = 1303, BadPartnerConfiguration = 1304, XboxBPCertificateFailure = 1305, XboxXASSExchangeFailure = 1306, InvalidEntityId = 1307, StatisticValueAggregationOverflow = 1308, EmailMessageFromAddressIsMissing = 1309, EmailMessageToAddressIsMissing = 1310, SmtpServerAuthenticationError = 1311, SmtpServerLimitExceeded = 1312, SmtpServerInsufficientStorage = 1313, SmtpServerCommunicationError = 1314, SmtpServerGeneralFailure = 1315, EmailClientTimeout = 1316, EmailClientCanceledTask = 1317, EmailTemplateMissing = 1318, InvalidHostForTitleId = 1319, EmailConfirmationTokenDoesNotExist = 1320, EmailConfirmationTokenExpired = 1321, AccountDeleted = 1322, PlayerSecretNotConfigured = 1323, InvalidSignatureTime = 1324, NoContactEmailAddressFound = 1325, InvalidAuthToken = 1326, AuthTokenDoesNotExist = 1327, AuthTokenExpired = 1328, AuthTokenAlreadyUsedToResetPassword = 1329, MembershipNameTooLong = 1330, MembershipNotFound = 1331, GoogleServiceAccountInvalid = 1332, GoogleServiceAccountParseFailure = 1333, EntityTokenMissing = 1334, EntityTokenInvalid = 1335, EntityTokenExpired = 1336, EntityTokenRevoked = 1337, InvalidProductForSubscription = 1338, XboxInaccessible = 1339, SubscriptionAlreadyTaken = 1340, SmtpAddonNotEnabled = 1341, APIConcurrentRequestLimitExceeded = 1342, XboxRejectedXSTSExchangeRequest = 1343, VariableNotDefined = 1344, TemplateVersionNotDefined = 1345, FileTooLarge = 1346, TitleDeleted = 1347, TitleContainsUserAccounts = 1348, TitleDeletionPlayerCleanupFailure = 1349, EntityFileOperationPending = 1350, NoEntityFileOperationPending = 1351, EntityProfileVersionMismatch = 1352, TemplateVersionTooOld = 1353, MembershipDefinitionInUse = 1354, PaymentPageNotConfigured = 1355, FailedLoginAttemptRateLimitExceeded = 1356, EntityBlockedByGroup = 1357, RoleDoesNotExist = 1358, EntityIsAlreadyMember = 1359, DuplicateRoleId = 1360, GroupInvitationNotFound = 1361, GroupApplicationNotFound = 1362, OutstandingInvitationAcceptedInstead = 1363, OutstandingApplicationAcceptedInstead = 1364, RoleIsGroupDefaultMember = 1365, RoleIsGroupAdmin = 1366, RoleNameNotAvailable = 1367, GroupNameNotAvailable = 1368, EmailReportAlreadySent = 1369, EmailReportRecipientBlacklisted = 1370, EventNamespaceNotAllowed = 1371, EventEntityNotAllowed = 1372, InvalidEntityType = 1373, NullTokenResultFromAad = 1374, InvalidTokenResultFromAad = 1375, NoValidCertificateForAad = 1376, InvalidCertificateForAad = 1377, DuplicateDropTableId = 1378, MultiplayerServerError = 1379, MultiplayerServerTooManyRequests = 1380, MultiplayerServerNoContent = 1381, MultiplayerServerBadRequest = 1382, MultiplayerServerUnauthorized = 1383, MultiplayerServerForbidden = 1384, MultiplayerServerNotFound = 1385, MultiplayerServerConflict = 1386, MultiplayerServerInternalServerError = 1387, MultiplayerServerUnavailable = 1388, ExplicitContentDetected = 1389, PIIContentDetected = 1390, InvalidScheduledTaskParameter = 1391, PerEntityEventRateLimitExceeded = 1392, TitleDefaultLanguageNotSet = 1393, EmailTemplateMissingDefaultVersion = 1394, FacebookInstantGamesIdNotLinked = 1395, InvalidFacebookInstantGamesSignature = 1396, FacebookInstantGamesAuthNotConfiguredForTitle = 1397, EntityProfileConstraintValidationFailed = 1398, TelemetryIngestionKeyPending = 1399, TelemetryIngestionKeyNotFound = 1400, StatisticTagRequired = 1401, StatisticTagInvalid = 1402, DataIntegrityError = 1403, MatchmakingEntityInvalid = 2001, MatchmakingPlayerAttributesInvalid = 2002, MatchmakingCreateRequestMissing = 2003, MatchmakingCreateRequestCreatorMissing = 2004, MatchmakingCreateRequestCreatorIdMissing = 2005, MatchmakingCreateRequestUserListMissing = 2006, MatchmakingCreateRequestGiveUpAfterInvalid = 2007, MatchmakingTicketIdMissing = 2008, MatchmakingMatchIdMissing = 2009, MatchmakingMatchIdIdMissing = 2010, MatchmakingQueueNameMissing = 2011, MatchmakingTitleIdMissing = 2012, MatchmakingTicketIdIdMissing = 2013, MatchmakingPlayerIdMissing = 2014, MatchmakingJoinRequestUserMissing = 2015, MatchmakingQueueConfigNotFound = 2016, MatchmakingMatchNotFound = 2017, MatchmakingTicketNotFound = 2018, MatchmakingCreateTicketServerIdentityInvalid = 2019, MatchmakingCreateTicketClientIdentityInvalid = 2020, MatchmakingGetTicketUserMismatch = 2021, MatchmakingJoinTicketServerIdentityInvalid = 2022, MatchmakingJoinTicketUserIdentityMismatch = 2023, MatchmakingCancelTicketServerIdentityInvalid = 2024, MatchmakingCancelTicketUserIdentityMismatch = 2025, MatchmakingGetMatchIdentityMismatch = 2026, MatchmakingPlayerIdentityMismatch = 2027, MatchmakingAlreadyJoinedTicket = 2028, MatchmakingTicketAlreadyCompleted = 2029, MatchmakingQueueNameInvalid = 2030, MatchmakingQueueConfigInvalid = 2031, MatchmakingMemberProfileInvalid = 2032, WriteAttemptedDuringExport = 2033, NintendoSwitchDeviceIdNotLinked = 2034, MatchmakingNotEnabled = 2035, MatchmakingGetStatisticsIdentityInvalid = 2036, MatchmakingStatisticsIdMissing = 2037, CannotEnableMultiplayerServersForTitle = 2038 } public delegate void ErrorCallback(PlayFabError error); public class PlayFabError { public string ApiEndpoint; public int HttpCode; public string HttpStatus; public PlayFabErrorCode Error; public string ErrorMessage; public Dictionary<string, List<string> > ErrorDetails; public object CustomData; public override string ToString() { var sb = new System.Text.StringBuilder(); if (ErrorDetails != null) { foreach (var kv in ErrorDetails) { sb.Append(kv.Key); sb.Append(": "); sb.Append(string.Join(", ", kv.Value.ToArray())); sb.Append(" | "); } } return string.Format("{0} PlayFabError({1}, {2}, {3} {4}", ApiEndpoint, Error, ErrorMessage, HttpCode, HttpStatus) + (sb.Length > 0 ? " - Details: " + sb.ToString() + ")" : ")"); } [ThreadStatic] private static StringBuilder _tempSb; public string GenerateErrorReport() { if (_tempSb == null) _tempSb = new StringBuilder(); _tempSb.Length = 0; _tempSb.Append(ApiEndpoint).Append(": ").Append(ErrorMessage); if (ErrorDetails != null) foreach (var pair in ErrorDetails) foreach (var msg in pair.Value) _tempSb.Append("\n").Append(pair.Key).Append(": ").Append(msg); return _tempSb.ToString(); } } public class PlayFabException : Exception { public readonly PlayFabExceptionCode Code; public PlayFabException(PlayFabExceptionCode code, string message) : base(message) { Code = code; } } public enum PlayFabExceptionCode { DeveloperKeyNotSet, EntityTokenNotSet, NotLoggedIn, TitleNotSet, } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.5466 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.42. // namespace WebsitePanel.Providers.HeliconZoo { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="HeliconZooSoap", Namespace="http://smbsaas/websitepanel/server/")] public partial class HeliconZoo : Microsoft.Web.Services3.WebServicesClientProtocol { public ServiceProviderSettingsSoapHeader ServiceProviderSettingsSoapHeaderValue; private System.Threading.SendOrPostCallback GetEnginesOperationCompleted; private System.Threading.SendOrPostCallback SetEnginesOperationCompleted; private System.Threading.SendOrPostCallback IsEnginesEnabledOperationCompleted; private System.Threading.SendOrPostCallback SwithEnginesEnabledOperationCompleted; private System.Threading.SendOrPostCallback GetEnabledEnginesForSiteOperationCompleted; private System.Threading.SendOrPostCallback SetEnabledEnginesForSiteOperationCompleted; private System.Threading.SendOrPostCallback IsWebCosoleEnabledOperationCompleted; private System.Threading.SendOrPostCallback SetWebCosoleEnabledOperationCompleted; /// <remarks/> public HeliconZoo() { this.Url = "http://localhost:9003/HeliconZoo.asmx"; } /// <remarks/> public event GetEnginesCompletedEventHandler GetEnginesCompleted; /// <remarks/> public event SetEnginesCompletedEventHandler SetEnginesCompleted; /// <remarks/> public event IsEnginesEnabledCompletedEventHandler IsEnginesEnabledCompleted; /// <remarks/> public event SwithEnginesEnabledCompletedEventHandler SwithEnginesEnabledCompleted; /// <remarks/> public event GetEnabledEnginesForSiteCompletedEventHandler GetEnabledEnginesForSiteCompleted; /// <remarks/> public event SetEnabledEnginesForSiteCompletedEventHandler SetEnabledEnginesForSiteCompleted; /// <remarks/> public event IsWebCosoleEnabledCompletedEventHandler IsWebCosoleEnabledCompleted; /// <remarks/> public event SetWebCosoleEnabledCompletedEventHandler SetWebCosoleEnabledCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetEngines", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public HeliconZooEngine[] GetEngines() { object[] results = this.Invoke("GetEngines", new object[0]); return ((HeliconZooEngine[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetEngines(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetEngines", new object[0], callback, asyncState); } /// <remarks/> public HeliconZooEngine[] EndGetEngines(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((HeliconZooEngine[])(results[0])); } /// <remarks/> public void GetEnginesAsync() { this.GetEnginesAsync(null); } /// <remarks/> public void GetEnginesAsync(object userState) { if ((this.GetEnginesOperationCompleted == null)) { this.GetEnginesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetEnginesOperationCompleted); } this.InvokeAsync("GetEngines", new object[0], this.GetEnginesOperationCompleted, userState); } private void OnGetEnginesOperationCompleted(object arg) { if ((this.GetEnginesCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetEnginesCompleted(this, new GetEnginesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SetEngines", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void SetEngines(HeliconZooEngine[] userEngines) { this.Invoke("SetEngines", new object[] { userEngines}); } /// <remarks/> public System.IAsyncResult BeginSetEngines(HeliconZooEngine[] userEngines, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetEngines", new object[] { userEngines}, callback, asyncState); } /// <remarks/> public void EndSetEngines(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void SetEnginesAsync(HeliconZooEngine[] userEngines) { this.SetEnginesAsync(userEngines, null); } /// <remarks/> public void SetEnginesAsync(HeliconZooEngine[] userEngines, object userState) { if ((this.SetEnginesOperationCompleted == null)) { this.SetEnginesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetEnginesOperationCompleted); } this.InvokeAsync("SetEngines", new object[] { userEngines}, this.SetEnginesOperationCompleted, userState); } private void OnSetEnginesOperationCompleted(object arg) { if ((this.SetEnginesCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SetEnginesCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/IsEnginesEnabled", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool IsEnginesEnabled() { object[] results = this.Invoke("IsEnginesEnabled", new object[0]); return ((bool)(results[0])); } /// <remarks/> public System.IAsyncResult BeginIsEnginesEnabled(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("IsEnginesEnabled", new object[0], callback, asyncState); } /// <remarks/> public bool EndIsEnginesEnabled(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((bool)(results[0])); } /// <remarks/> public void IsEnginesEnabledAsync() { this.IsEnginesEnabledAsync(null); } /// <remarks/> public void IsEnginesEnabledAsync(object userState) { if ((this.IsEnginesEnabledOperationCompleted == null)) { this.IsEnginesEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnIsEnginesEnabledOperationCompleted); } this.InvokeAsync("IsEnginesEnabled", new object[0], this.IsEnginesEnabledOperationCompleted, userState); } private void OnIsEnginesEnabledOperationCompleted(object arg) { if ((this.IsEnginesEnabledCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.IsEnginesEnabledCompleted(this, new IsEnginesEnabledCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SwithEnginesEnabled", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void SwithEnginesEnabled(bool enabled) { this.Invoke("SwithEnginesEnabled", new object[] { enabled}); } /// <remarks/> public System.IAsyncResult BeginSwithEnginesEnabled(bool enabled, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SwithEnginesEnabled", new object[] { enabled}, callback, asyncState); } /// <remarks/> public void EndSwithEnginesEnabled(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void SwithEnginesEnabledAsync(bool enabled) { this.SwithEnginesEnabledAsync(enabled, null); } /// <remarks/> public void SwithEnginesEnabledAsync(bool enabled, object userState) { if ((this.SwithEnginesEnabledOperationCompleted == null)) { this.SwithEnginesEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSwithEnginesEnabledOperationCompleted); } this.InvokeAsync("SwithEnginesEnabled", new object[] { enabled}, this.SwithEnginesEnabledOperationCompleted, userState); } private void OnSwithEnginesEnabledOperationCompleted(object arg) { if ((this.SwithEnginesEnabledCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SwithEnginesEnabledCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetEnabledEnginesForSite", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string[] GetEnabledEnginesForSite(string siteId) { object[] results = this.Invoke("GetEnabledEnginesForSite", new object[] { siteId}); return ((string[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetEnabledEnginesForSite(string siteId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetEnabledEnginesForSite", new object[] { siteId}, callback, asyncState); } /// <remarks/> public string[] EndGetEnabledEnginesForSite(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string[])(results[0])); } /// <remarks/> public void GetEnabledEnginesForSiteAsync(string siteId) { this.GetEnabledEnginesForSiteAsync(siteId, null); } /// <remarks/> public void GetEnabledEnginesForSiteAsync(string siteId, object userState) { if ((this.GetEnabledEnginesForSiteOperationCompleted == null)) { this.GetEnabledEnginesForSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetEnabledEnginesForSiteOperationCompleted); } this.InvokeAsync("GetEnabledEnginesForSite", new object[] { siteId}, this.GetEnabledEnginesForSiteOperationCompleted, userState); } private void OnGetEnabledEnginesForSiteOperationCompleted(object arg) { if ((this.GetEnabledEnginesForSiteCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetEnabledEnginesForSiteCompleted(this, new GetEnabledEnginesForSiteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SetEnabledEnginesForSite", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void SetEnabledEnginesForSite(string siteId, string[] engineNames) { this.Invoke("SetEnabledEnginesForSite", new object[] { siteId, engineNames}); } /// <remarks/> public System.IAsyncResult BeginSetEnabledEnginesForSite(string siteId, string[] engineNames, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetEnabledEnginesForSite", new object[] { siteId, engineNames}, callback, asyncState); } /// <remarks/> public void EndSetEnabledEnginesForSite(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void SetEnabledEnginesForSiteAsync(string siteId, string[] engineNames) { this.SetEnabledEnginesForSiteAsync(siteId, engineNames, null); } /// <remarks/> public void SetEnabledEnginesForSiteAsync(string siteId, string[] engineNames, object userState) { if ((this.SetEnabledEnginesForSiteOperationCompleted == null)) { this.SetEnabledEnginesForSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetEnabledEnginesForSiteOperationCompleted); } this.InvokeAsync("SetEnabledEnginesForSite", new object[] { siteId, engineNames}, this.SetEnabledEnginesForSiteOperationCompleted, userState); } private void OnSetEnabledEnginesForSiteOperationCompleted(object arg) { if ((this.SetEnabledEnginesForSiteCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SetEnabledEnginesForSiteCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/IsWebCosoleEnabled", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool IsWebCosoleEnabled() { object[] results = this.Invoke("IsWebCosoleEnabled", new object[0]); return ((bool)(results[0])); } /// <remarks/> public System.IAsyncResult BeginIsWebCosoleEnabled(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("IsWebCosoleEnabled", new object[0], callback, asyncState); } /// <remarks/> public bool EndIsWebCosoleEnabled(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((bool)(results[0])); } /// <remarks/> public void IsWebCosoleEnabledAsync() { this.IsWebCosoleEnabledAsync(null); } /// <remarks/> public void IsWebCosoleEnabledAsync(object userState) { if ((this.IsWebCosoleEnabledOperationCompleted == null)) { this.IsWebCosoleEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnIsWebCosoleEnabledOperationCompleted); } this.InvokeAsync("IsWebCosoleEnabled", new object[0], this.IsWebCosoleEnabledOperationCompleted, userState); } private void OnIsWebCosoleEnabledOperationCompleted(object arg) { if ((this.IsWebCosoleEnabledCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.IsWebCosoleEnabledCompleted(this, new IsWebCosoleEnabledCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SetWebCosoleEnabled", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void SetWebCosoleEnabled(bool enabled) { this.Invoke("SetWebCosoleEnabled", new object[] { enabled}); } /// <remarks/> public System.IAsyncResult BeginSetWebCosoleEnabled(bool enabled, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetWebCosoleEnabled", new object[] { enabled}, callback, asyncState); } /// <remarks/> public void EndSetWebCosoleEnabled(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void SetWebCosoleEnabledAsync(bool enabled) { this.SetWebCosoleEnabledAsync(enabled, null); } /// <remarks/> public void SetWebCosoleEnabledAsync(bool enabled, object userState) { if ((this.SetWebCosoleEnabledOperationCompleted == null)) { this.SetWebCosoleEnabledOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetWebCosoleEnabledOperationCompleted); } this.InvokeAsync("SetWebCosoleEnabled", new object[] { enabled}, this.SetWebCosoleEnabledOperationCompleted, userState); } private void OnSetWebCosoleEnabledOperationCompleted(object arg) { if ((this.SetWebCosoleEnabledCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SetWebCosoleEnabledCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetEnginesCompletedEventHandler(object sender, GetEnginesCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetEnginesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetEnginesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public HeliconZooEngine[] Result { get { this.RaiseExceptionIfNecessary(); return ((HeliconZooEngine[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void SetEnginesCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void IsEnginesEnabledCompletedEventHandler(object sender, IsEnginesEnabledCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class IsEnginesEnabledCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal IsEnginesEnabledCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public bool Result { get { this.RaiseExceptionIfNecessary(); return ((bool)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void SwithEnginesEnabledCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetEnabledEnginesForSiteCompletedEventHandler(object sender, GetEnabledEnginesForSiteCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetEnabledEnginesForSiteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetEnabledEnginesForSiteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public string[] Result { get { this.RaiseExceptionIfNecessary(); return ((string[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void SetEnabledEnginesForSiteCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void IsWebCosoleEnabledCompletedEventHandler(object sender, IsWebCosoleEnabledCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class IsWebCosoleEnabledCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal IsWebCosoleEnabledCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public bool Result { get { this.RaiseExceptionIfNecessary(); return ((bool)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void SetWebCosoleEnabledCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); }
/* * Copyright (c) 2007-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using System; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; namespace OpenMetaverse.GUI { /// <summary> /// ListView GUI component for viewing a client's nearby avatars list /// </summary> public class AvatarList : ListView { private GridClient _Client; private List<uint> _Avatars = new List<uint>(); private ColumnSorter _ColumnSorter = new ColumnSorter(); public delegate void AvatarDoubleClickCallback(Avatar avatar); /// <summary> /// Triggered when the user double clicks on an avatar in the list /// </summary> public event AvatarDoubleClickCallback OnAvatarDoubleClick; /// <summary> /// Gets or sets the GridClient associated with this control /// </summary> public GridClient Client { get { return _Client; } set { if (value != null) InitializeClient(value); } } /// <summary> /// TreeView control for an unspecified client's nearby avatar list /// </summary> public AvatarList() { ColumnHeader header1 = this.Columns.Add("Name"); header1.Width = this.Width - 20; ColumnHeader header2 = this.Columns.Add(" "); header2.Width = 40; _ColumnSorter.SortColumn = 0; this.DoubleBuffered = true; this.ListViewItemSorter = _ColumnSorter; this.View = View.Details; this.ColumnClick += new ColumnClickEventHandler(AvatarList_ColumnClick); this.DoubleClick += new EventHandler(AvatarList_DoubleClick); } /// <summary> /// TreeView control for the specified client's nearby avatar list /// </summary> /// <param name="client"></param> public AvatarList(GridClient client) : this () { InitializeClient(client); } /// <summary> /// Thread-safe method for clearing the TreeView control /// </summary> public void ClearNodes() { if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { ClearNodes(); }); else this.Items.Clear(); } private void InitializeClient(GridClient client) { _Client = client; _Client.Network.OnCurrentSimChanged += new NetworkManager.CurrentSimChangedCallback(Network_OnCurrentSimChanged); _Client.Objects.OnNewAvatar += new ObjectManager.NewAvatarCallback(Objects_OnNewAvatar); _Client.Objects.OnObjectKilled += new ObjectManager.KillObjectCallback(Objects_OnObjectKilled); _Client.Objects.OnObjectUpdated += new ObjectManager.ObjectUpdatedCallback(Objects_OnObjectUpdated); } private void RemoveAvatar(uint localID) { if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { RemoveAvatar(localID); }); else { lock (_Avatars) { if (_Avatars.Contains(localID)) { _Avatars.Remove(localID); string key = localID.ToString(); int index = this.Items.IndexOfKey(key); if (index > -1) this.Items.RemoveAt(index); } } } } private void UpdateAvatar(Avatar avatar) { if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { UpdateAvatar(avatar); }); else { lock (_Avatars) { ListViewItem item; if (_Avatars.Contains(avatar.LocalID)) { item = this.Items[avatar.LocalID.ToString()]; item.SubItems[1].Text = (int)Vector3.Distance(_Client.Self.SimPosition, avatar.Position) + "m"; } else { _Avatars.Add(avatar.LocalID); string key = avatar.LocalID.ToString(); item = this.Items.Add(key, avatar.Name, null); item.SubItems.Add((int)Vector3.Distance(_Client.Self.SimPosition, avatar.Position) + "m"); } item.Tag = avatar; } } } private void AvatarList_ColumnClick(object sender, ColumnClickEventArgs e) { _ColumnSorter.SortColumn = e.Column; if ((_ColumnSorter.Ascending = (this.Sorting == SortOrder.Ascending))) this.Sorting = SortOrder.Descending; else this.Sorting = SortOrder.Ascending; this.ListViewItemSorter = _ColumnSorter; } private void AvatarList_DoubleClick(object sender, EventArgs e) { if (OnAvatarDoubleClick != null) { ListView list = (ListView)sender; if (list.SelectedItems.Count > 0 && list.SelectedItems[0].Tag is Avatar) { Avatar av = (Avatar)list.SelectedItems[0].Tag; try { OnAvatarDoubleClick(av); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); } } } } private void Network_OnCurrentSimChanged(Simulator PreviousSimulator) { lock (_Avatars) _Avatars.Clear(); ClearNodes(); } private void Objects_OnNewAvatar(Simulator simulator, Avatar avatar, ulong regionHandle, ushort timeDilation) { lock (_Avatars) { if (!_Avatars.Contains(avatar.LocalID)) UpdateAvatar(avatar); } } private void Objects_OnObjectKilled(Simulator simulator, uint objectID) { lock (_Avatars) { if (_Avatars.Contains(objectID)) RemoveAvatar(objectID); } } private void Objects_OnObjectUpdated(Simulator simulator, ObjectUpdate update, ulong regionHandle, ushort timeDilation) { lock (_Avatars) { if (_Avatars.Contains(update.LocalID)) { Avatar av; if (simulator.ObjectsAvatars.TryGetValue(update.LocalID, out av)) UpdateAvatar(av); } } } private class ColumnSorter : IComparer { public bool Ascending = true; public int SortColumn = 0; public int Compare(object a, object b) { ListViewItem itemA = (ListViewItem)a; ListViewItem itemB = (ListViewItem)b; if (SortColumn == 1) { int valueA = itemB.SubItems.Count > 1 ? int.Parse(itemA.SubItems[1].Text.Replace("m", "")) : 0; int valueB = itemB.SubItems.Count > 1 ? int.Parse(itemB.SubItems[1].Text.Replace("m", "")) : 0; if (Ascending) { if (valueA == valueB) return 0; return valueA < valueB ? -1 : 1; } else { if (valueA == valueB) return 0; return valueA < valueB ? 1 : -1; } } else { if (Ascending) return string.Compare(itemA.Text, itemB.Text); else return -string.Compare(itemA.Text, itemB.Text); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] public static class ConstantArgsUInt { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 100000; #endif // Ints feeding math operations. // // Inlining in Bench0xp should enable constant folding // Inlining in Bench0xn will not enable constant folding static uint Five = 5; static uint Ten = 10; static uint Id(uint x) { return x; } static uint F00(uint x) { return x * x; } static bool Bench00p() { uint t = 10; uint f = F00(t); return (f == 100); } static bool Bench00n() { uint t = Ten; uint f = F00(t); return (f == 100); } static bool Bench00p1() { uint t = Id(10); uint f = F00(t); return (f == 100); } static bool Bench00n1() { uint t = Id(Ten); uint f = F00(t); return (f == 100); } static bool Bench00p2() { uint t = Id(10); uint f = F00(Id(t)); return (f == 100); } static bool Bench00n2() { uint t = Id(Ten); uint f = F00(Id(t)); return (f == 100); } static bool Bench00p3() { uint t = 10; uint f = F00(Id(Id(t))); return (f == 100); } static bool Bench00n3() { uint t = Ten; uint f = F00(Id(Id(t))); return (f == 100); } static bool Bench00p4() { uint t = 5; uint f = F00(2 * t); return (f == 100); } static bool Bench00n4() { uint t = Five; uint f = F00(2 * t); return (f == 100); } static uint F01(uint x) { return 1000 / x; } static bool Bench01p() { uint t = 10; uint f = F01(t); return (f == 100); } static bool Bench01n() { uint t = Ten; uint f = F01(t); return (f == 100); } static uint F02(uint x) { return 20 * (x / 2); } static bool Bench02p() { uint t = 10; uint f = F02(t); return (f == 100); } static bool Bench02n() { uint t = Ten; uint f = F02(t); return (f == 100); } static uint F03(uint x) { return 91 + 1009 % x; } static bool Bench03p() { uint t = 10; uint f = F03(t); return (f == 100); } static bool Bench03n() { uint t = Ten; uint f = F03(t); return (f == 100); } static uint F04(uint x) { return 50 * (x % 4); } static bool Bench04p() { uint t = 10; uint f = F04(t); return (f == 100); } static bool Bench04n() { uint t = Ten; uint f = F04(t); return (f == 100); } static uint F06(uint x) { return 110 - x; } static bool Bench06p() { uint t = 10; uint f = F06(t); return (f == 100); } static bool Bench06n() { uint t = Ten; uint f = F06(t); return (f == 100); } static uint F07(uint x) { return ~x + 111; } static bool Bench07p() { uint t = 10; uint f = F07(t); return (f == 100); } static bool Bench07n() { uint t = Ten; uint f = F07(t); return (f == 100); } static uint F071(uint x) { return (x ^ 0xFFFFFFFF) + 111; } static bool Bench07p1() { uint t = 10; uint f = F071(t); return (f == 100); } static bool Bench07n1() { uint t = Ten; uint f = F071(t); return (f == 100); } static uint F08(uint x) { return (x & 0x7) + 98; } static bool Bench08p() { uint t = 10; uint f = F08(t); return (f == 100); } static bool Bench08n() { uint t = Ten; uint f = F08(t); return (f == 100); } static uint F09(uint x) { return (x | 0x7) + 85; } static bool Bench09p() { uint t = 10; uint f = F09(t); return (f == 100); } static bool Bench09n() { uint t = Ten; uint f = F09(t); return (f == 100); } // Uints feeding comparisons. // // Inlining in Bench1xp should enable branch optimization // Inlining in Bench1xn will not enable branch optimization static uint F10(uint x) { return x == 10 ? 100u : 0u; } static bool Bench10p() { uint t = 10; uint f = F10(t); return (f == 100); } static bool Bench10n() { uint t = Ten; uint f = F10(t); return (f == 100); } static uint F101(uint x) { return x != 10 ? 0u : 100u; } static bool Bench10p1() { uint t = 10; uint f = F101(t); return (f == 100); } static bool Bench10n1() { uint t = Ten; uint f = F101(t); return (f == 100); } static uint F102(uint x) { return x >= 10 ? 100u : 0u; } static bool Bench10p2() { uint t = 10; uint f = F102(t); return (f == 100); } static bool Bench10n2() { uint t = Ten; uint f = F102(t); return (f == 100); } static uint F103(uint x) { return x <= 10 ? 100u : 0u; } static bool Bench10p3() { uint t = 10; uint f = F103(t); return (f == 100); } static bool Bench10n3() { uint t = Ten; uint f = F102(t); return (f == 100); } static uint F11(uint x) { if (x == 10) { return 100; } else { return 0; } } static bool Bench11p() { uint t = 10; uint f = F11(t); return (f == 100); } static bool Bench11n() { uint t = Ten; uint f = F11(t); return (f == 100); } static uint F111(uint x) { if (x != 10) { return 0; } else { return 100; } } static bool Bench11p1() { uint t = 10; uint f = F111(t); return (f == 100); } static bool Bench11n1() { uint t = Ten; uint f = F111(t); return (f == 100); } static uint F112(uint x) { if (x > 10) { return 0; } else { return 100; } } static bool Bench11p2() { uint t = 10; uint f = F112(t); return (f == 100); } static bool Bench11n2() { uint t = Ten; uint f = F112(t); return (f == 100); } static uint F113(uint x) { if (x < 10) { return 0; } else { return 100; } } static bool Bench11p3() { uint t = 10; uint f = F113(t); return (f == 100); } static bool Bench11n3() { uint t = Ten; uint f = F113(t); return (f == 100); } // Ununsed (or effectively unused) parameters // // Simple callee analysis may overstate inline benefit static uint F20(uint x) { return 100; } static bool Bench20p() { uint t = 10; uint f = F20(t); return (f == 100); } static bool Bench20p1() { uint t = Ten; uint f = F20(t); return (f == 100); } static uint F21(uint x) { return (uint) -x + 100 + x; } static bool Bench21p() { uint t = 10; uint f = F21(t); return (f == 100); } static bool Bench21n() { uint t = Ten; uint f = F21(t); return (f == 100); } static uint F211(uint x) { return x - x + 100; } static bool Bench21p1() { uint t = 10; uint f = F211(t); return (f == 100); } static bool Bench21n1() { uint t = Ten; uint f = F211(t); return (f == 100); } static uint F22(uint x) { if (x > 0) { return 100; } return 100; } static bool Bench22p() { uint t = 10; uint f = F22(t); return (f == 100); } static bool Bench22p1() { uint t = Ten; uint f = F22(t); return (f == 100); } static uint F23(uint x) { if (x > 0) { return 90 + x; } return 100; } static bool Bench23p() { uint t = 10; uint f = F23(t); return (f == 100); } static bool Bench23n() { uint t = Ten; uint f = F23(t); return (f == 100); } // Multiple parameters static uint F30(uint x, uint y) { return y * y; } static bool Bench30p() { uint t = 10; uint f = F30(t, t); return (f == 100); } static bool Bench30n() { uint t = Ten; uint f = F30(t, t); return (f == 100); } static bool Bench30p1() { uint s = Ten; uint t = 10; uint f = F30(s, t); return (f == 100); } static bool Bench30n1() { uint s = 10; uint t = Ten; uint f = F30(s, t); return (f == 100); } static bool Bench30p2() { uint s = 10; uint t = 10; uint f = F30(s, t); return (f == 100); } static bool Bench30n2() { uint s = Ten; uint t = Ten; uint f = F30(s, t); return (f == 100); } static bool Bench30p3() { uint s = 10; uint t = s; uint f = F30(s, t); return (f == 100); } static bool Bench30n3() { uint s = Ten; uint t = s; uint f = F30(s, t); return (f == 100); } static uint F31(uint x, uint y, uint z) { return z * z; } static bool Bench31p() { uint t = 10; uint f = F31(t, t, t); return (f == 100); } static bool Bench31n() { uint t = Ten; uint f = F31(t, t, t); return (f == 100); } static bool Bench31p1() { uint r = Ten; uint s = Ten; uint t = 10; uint f = F31(r, s, t); return (f == 100); } static bool Bench31n1() { uint r = 10; uint s = 10; uint t = Ten; uint f = F31(r, s, t); return (f == 100); } static bool Bench31p2() { uint r = 10; uint s = 10; uint t = 10; uint f = F31(r, s, t); return (f == 100); } static bool Bench31n2() { uint r = Ten; uint s = Ten; uint t = Ten; uint f = F31(r, s, t); return (f == 100); } static bool Bench31p3() { uint r = 10; uint s = r; uint t = s; uint f = F31(r, s, t); return (f == 100); } static bool Bench31n3() { uint r = Ten; uint s = r; uint t = s; uint f = F31(r, s, t); return (f == 100); } // Two args, both used static uint F40(uint x, uint y) { return x * x + y * y - 100; } static bool Bench40p() { uint t = 10; uint f = F40(t, t); return (f == 100); } static bool Bench40n() { uint t = Ten; uint f = F40(t, t); return (f == 100); } static bool Bench40p1() { uint s = Ten; uint t = 10; uint f = F40(s, t); return (f == 100); } static bool Bench40p2() { uint s = 10; uint t = Ten; uint f = F40(s, t); return (f == 100); } static uint F41(uint x, uint y) { return x * y; } static bool Bench41p() { uint t = 10; uint f = F41(t, t); return (f == 100); } static bool Bench41n() { uint t = Ten; uint f = F41(t, t); return (f == 100); } static bool Bench41p1() { uint s = 10; uint t = Ten; uint f = F41(s, t); return (f == 100); } static bool Bench41p2() { uint s = Ten; uint t = 10; uint f = F41(s, t); return (f == 100); } private static IEnumerable<object[]> MakeArgs(params string[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> TestFuncs = MakeArgs( "Bench00p", "Bench00n", "Bench00p1", "Bench00n1", "Bench00p2", "Bench00n2", "Bench00p3", "Bench00n3", "Bench00p4", "Bench00n4", "Bench01p", "Bench01n", "Bench02p", "Bench02n", "Bench03p", "Bench03n", "Bench04p", "Bench04n", "Bench06p", "Bench06n", "Bench07p", "Bench07n", "Bench07p1", "Bench07n1", "Bench08p", "Bench08n", "Bench09p", "Bench09n", "Bench10p", "Bench10n", "Bench10p1", "Bench10n1", "Bench10p2", "Bench10n2", "Bench10p3", "Bench10n3", "Bench11p", "Bench11n", "Bench11p1", "Bench11n1", "Bench11p2", "Bench11n2", "Bench11p3", "Bench11n3", "Bench20p", "Bench20p1", "Bench21p", "Bench21n", "Bench21p1", "Bench21n1", "Bench22p", "Bench22p1", "Bench23p", "Bench23n", "Bench30p", "Bench30n", "Bench30p1", "Bench30n1", "Bench30p2", "Bench30n2", "Bench30p3", "Bench30n3", "Bench31p", "Bench31n", "Bench31p1", "Bench31n1", "Bench31p2", "Bench31n2", "Bench31p3", "Bench31n3", "Bench40p", "Bench40n", "Bench40p1", "Bench40p2", "Bench41p", "Bench41n", "Bench41p1", "Bench41p2" ); static Func<bool> LookupFunc(object o) { TypeInfo t = typeof(ConstantArgsUInt).GetTypeInfo(); MethodInfo m = t.GetDeclaredMethod((string) o); return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>; } [Benchmark] [MemberData(nameof(TestFuncs))] public static void Test(object funcName) { Func<bool> f = LookupFunc(funcName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { f(); } } } } static bool TestBase(Func<bool> f) { bool result = true; for (int i = 0; i < Iterations; i++) { result &= f(); } return result; } public static int Main() { bool result = true; foreach(object[] o in TestFuncs) { string funcName = (string) o[0]; Func<bool> func = LookupFunc(funcName); bool thisResult = TestBase(func); if (!thisResult) { Console.WriteLine("{0} failed", funcName); } result &= thisResult; } return (result ? 100 : -1); } }
// // ClientTests.cs // // Author: // Scott Peterson <lunchtimemama@gmail.com> // // Copyright (c) 2009 Scott Peterson // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Threading; using NUnit.Framework; using Mono.Upnp.Control; namespace Mono.Upnp.Tests { [TestFixture] public class ClientTests { readonly object mutex = new object (); volatile bool flag; [Test] public void DescriptionCacheTest() { var factory = new DummyDeserializerFactory (); using (var server = new Server (CreateRoot ())) { using (var client = new Client (factory.CreateDeserializer)) { client.Browse (new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (1, 0))); client.Browse (new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (2, 0))); flag = false; client.ServiceAdded += (sender, args) => { lock (mutex) { var service = args.Service.GetService (); Assert.IsNotNull (service); if (flag) { Monitor.Pulse (mutex); } else { flag = true; } } }; lock (mutex) { server.Start (); if (!Monitor.Wait (mutex, TimeSpan.FromSeconds (30))) { Assert.Fail ("The server announcement timed out."); } Assert.AreEqual (1, factory.InstantiationCount); } } } } [Test] public void AnnouncementTest () { using (var server = new Server (CreateRoot ())) { using (var client = new Client ()) { client.DeviceAdded += AnnouncementTestClientDeviceAdded; client.ServiceAdded += AnnouncementTestClientServiceAdded; client.BrowseAll (); lock (mutex) { flag = false; server.Start (); if (!Monitor.Wait (mutex, TimeSpan.FromSeconds (30))) { Assert.Fail ("The UPnP server announcement timed out."); } } } } } void AnnouncementTestClientServiceAdded (object sender, ServiceEventArgs e) { lock (mutex) { Assert.AreEqual (new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (1, 0)), e.Service.Type); Assert.AreEqual ("uuid:d1", e.Service.DeviceUdn); Assert.IsTrue (e.Service.Locations.GetEnumerator ().MoveNext ()); if (flag) { Monitor.Pulse (mutex); } else { flag = true; } } } void AnnouncementTestClientDeviceAdded (object sender, DeviceEventArgs e) { lock (mutex) { Assert.AreEqual (new DeviceType ("schemas-upnp-org", "mono-upnp-test-device", new Version (1, 0)), e.Device.Type); Assert.AreEqual ("uuid:d1", e.Device.Udn); Assert.IsTrue (e.Device.Locations.GetEnumerator ().MoveNext ()); if (flag) { Monitor.Pulse (mutex); } else { flag = true; } } } [Test] public void GetDeviceTest () { using (var server = new Server (CreateRoot ())) { using (var client = new Client ()) { client.BrowseAll (); client.DeviceAdded += (obj, args) => { lock (mutex) { var device = args.Device.GetDevice (); Assert.AreEqual ("uuid:d1", device.Udn); Monitor.Pulse (mutex); } }; lock (mutex) { server.Start (); if (!Monitor.Wait (mutex, TimeSpan.FromSeconds (30))) { Assert.Fail ("The UPnP server announcement timed out."); } } } } } [Test] public void GetServiceTest () { using (var server = new Server (CreateRoot ())) { using (var client = new Client ()) { client.BrowseAll (); client.ServiceAdded += (obj, args) => { lock (mutex) { var service = args.Service.GetService (); Assert.AreEqual ("urn:upnp-org:serviceId:testService1", service.Id); Monitor.Pulse (mutex); } }; lock (mutex) { server.Start (); if (!Monitor.Wait (mutex, TimeSpan.FromSeconds (30))) { Assert.Fail ("The UPnP server announcement timed out."); } } } } } [Test] public void GetServiceControllerTest () { using (var server = new Server (CreateRoot ())) { using (var client = new Client ()) { client.BrowseAll (); client.ServiceAdded += (obj, args) => { lock (mutex) { try { var controller = args.Service.GetService ().GetController (); Assert.IsNotNull (controller); } finally { Monitor.Pulse (mutex); } } }; lock (mutex) { server.Start (); if (!Monitor.Wait (mutex, TimeSpan.FromSeconds (30))) { Assert.Fail ("The UPnP server announcement timed out."); } } } } } class ControlTestClass { [UpnpAction] public string Foo (string bar) { return string.Format ("You said {0}", bar); } } [Test] public void ControlTest () { var root = new Root ( new DeviceType ("schemas-upnp-org", "mono-upnp-test-device", new Version (1, 0)), "uuid:d1", "Mono.Upnp.Tests Device", "Mono Project", "Device", new RootDeviceOptions { Services = new[] { new Service<ControlTestClass> ( new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (1, 0)), "urn:upnp-org:serviceId:testService1", new ControlTestClass () ) } } ); using (var client = new Client ()) { client.Browse (new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (1, 0))); Exception exception = null; client.ServiceAdded += (sender, args) => { lock (mutex) { try { var controller = args.Service.GetService ().GetController (); var arguments = new Dictionary<string, string> (1); arguments["bar"] = "hello world!"; var results = controller.Actions["Foo"].Invoke (arguments); Assert.AreEqual ("You said hello world!", results["result"]); } catch (Exception e) { exception = e; } finally { Monitor.Pulse (mutex); } } }; using (var server = new Server (root)) { lock (mutex) { server.Start (); if (!Monitor.Wait (mutex, TimeSpan.FromSeconds (30))) { Assert.Fail ("The server control timed out."); } else if (exception != null) { throw exception; } } } } } class EventTestClass { [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; string foo; public string Foo { get { return foo; } set { foo = value; if (FooChanged != null) { FooChanged (this, new StateVariableChangedArgs<string> (value)); } } } } class EventTestHelperClass { readonly EventTestClass service; readonly object mutex; public Exception Exception; public EventTestHelperClass (EventTestClass service, object mutex) { this.service = service; this.mutex = mutex; } public void FirstEventHandler (object sender, StateVariableChangedArgs<string> args) { try { Assert.AreEqual ("Hello World!", args.NewValue); var state_variable = (StateVariable)sender; state_variable.ValueChanged -= FirstEventHandler; state_variable.ValueChanged += SecondEventHandler; service.Foo = "Hello Universe!"; } catch (Exception e) { Exception = e; lock (mutex) { Monitor.Pulse (mutex); } } } public void SecondEventHandler (object sender, StateVariableChangedArgs<string> args) { try { Assert.AreEqual ("Hello Universe!", args.NewValue); } catch (Exception e) { Exception = e; } lock (mutex) { Monitor.Pulse (mutex); } } } [Test] public void EventTest () { var service = new EventTestClass (); var root = new Root ( new DeviceType ("schemas-upnp-org", "mono-upnp-test-device", new Version (1, 0)), "uuid:d1", "Mono.Upnp.Tests Device", "Mono Project", "Device", new RootDeviceOptions { Services = new[] { new Service<EventTestClass> ( new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (1, 0)), "urn:upnp-org:serviceId:testService1", service ) } } ); var helper = new EventTestHelperClass (service, mutex); using (var server = new Server (root)) { using (var client = new Client ()) { client.ServiceAdded += (sender, args) => { try { var controller = args.Service.GetService ().GetController (); controller.StateVariables["FooChanged"].ValueChanged += helper.FirstEventHandler; } catch (Exception e) { helper.Exception = e; lock (mutex) { Monitor.Pulse (mutex); } } }; client.Browse (new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (1, 0))); lock (mutex) { server.Start (); service.Foo = "Hello World!"; if (!Monitor.Wait (mutex, TimeSpan.FromSeconds (30))) { Assert.Fail ("The event timed out."); } } } } if (helper.Exception != null) { throw helper.Exception; } } static Root CreateRoot () { return new DummyRoot ( new DeviceType ("schemas-upnp-org", "mono-upnp-test-device", new Version (1, 0)), "uuid:d1", "Mono.Upnp.Tests Device", "Mono Project", "Device", new RootDeviceOptions { Services = new[] { new DummyService ( new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (1, 0)), "urn:upnp-org:serviceId:testService1" ), new DummyService ( new ServiceType ("schemas-upnp-org", "mono-upnp-test-service", new Version (2, 0)), "urn:upnp-org:serviceId:testService2" ) } } ); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075DeserializeCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Deserialize"); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA3075DeserializeBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Deserialize"); #pragma warning restore RS0030 // Do not used banned APIs [Fact] public async Task UseXmlSerializerDeserializeShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml; using System.Xml.Serialization; namespace TestNamespace { public class UseXmlReaderForDeserialize { public void TestMethod(Stream stream) { XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); } } }", GetCA3075DeserializeCSharpResultAt(13, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Xml Imports System.Xml.Serialization Namespace TestNamespace Public Class UseXmlReaderForDeserialize Public Sub TestMethod(stream As Stream) Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) End Sub End Class End Namespace", GetCA3075DeserializeBasicResultAt(10, 13) ); } [Fact] public async Task UseXmlSerializerDeserializeInGetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml.Serialization; public class UseXmlReaderForDeserialize { Stream stream; public XmlSerializer Test { get { XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); return serializer; } } }", GetCA3075DeserializeCSharpResultAt(13, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Xml.Serialization Public Class UseXmlReaderForDeserialize Private stream As Stream Public ReadOnly Property Test() As XmlSerializer Get Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) Return serializer End Get End Property End Class", GetCA3075DeserializeBasicResultAt(10, 13) ); } [Fact] public async Task UseXmlSerializerDeserializeInSetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml.Serialization; public class UseXmlReaderForDeserialize { Stream stream; XmlSerializer privateDoc; public XmlSerializer SetDoc { set { if (value == null) { XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); privateDoc = serializer; } else privateDoc = value; } } }", GetCA3075DeserializeCSharpResultAt(16, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Xml.Serialization Public Class UseXmlReaderForDeserialize Private stream As Stream Private privateDoc As XmlSerializer Public WriteOnly Property SetDoc() As XmlSerializer Set If value Is Nothing Then Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) privateDoc = serializer Else privateDoc = value End If End Set End Property End Class", GetCA3075DeserializeBasicResultAt(12, 17) ); } [Fact] public async Task UseXmlSerializerDeserializeInTryShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml.Serialization; using System; public class UseXmlReaderForDeserialize { Stream stream; private void TestMethod() { try { XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); } catch (Exception) { throw; } finally { } } }", GetCA3075DeserializeCSharpResultAt(14, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.IO Imports System.Xml.Serialization Public Class UseXmlReaderForDeserialize Private stream As Stream Private Sub TestMethod() Try Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075DeserializeBasicResultAt(11, 13) ); } [Fact] public async Task UseXmlSerializerDeserializeInCatchShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml.Serialization; using System; public class UseXmlReaderForDeserialize { Stream stream; private void TestMethod() { try { } catch (Exception) { XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); } finally { } } }", GetCA3075DeserializeCSharpResultAt(14, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.IO Imports System.Xml.Serialization Public Class UseXmlReaderForDeserialize Private stream As Stream Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) Finally End Try End Sub End Class", GetCA3075DeserializeBasicResultAt(12, 13) ); } [Fact] public async Task UseXmlSerializerDeserializeInFinallyShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml.Serialization; using System; public class UseXmlReaderForDeserialize { Stream stream; private void TestMethod() { try { } catch (Exception) { throw; } finally { XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); } } }", GetCA3075DeserializeCSharpResultAt(15, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.IO Imports System.Xml.Serialization Public Class UseXmlReaderForDeserialize Private stream As Stream Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) End Try End Sub End Class", GetCA3075DeserializeBasicResultAt(14, 13) ); } [Fact] public async Task UseXmlSerializerDeserializeInDelegateShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml.Serialization; public class UseXmlReaderForDeserialize { delegate void Del(); Del d = delegate () { Stream stream = null; XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); }; }", GetCA3075DeserializeCSharpResultAt(13, 9) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Xml.Serialization Public Class UseXmlReaderForDeserialize Private Delegate Sub Del() Private d As Del = Sub() Dim stream As Stream = Nothing Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) End Sub End Class", GetCA3075DeserializeBasicResultAt(11, 5) ); } [Fact] public async Task UseXmlSerializerDeserializeInAsyncAwaitShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Threading.Tasks; using System.Xml.Serialization; class UseXmlReaderForDeserialize { private async Task TestMethod(Stream stream) { await Task.Run(() => { XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(stream); }); } private async void TestMethod2() { await TestMethod(null); } }", GetCA3075DeserializeCSharpResultAt(12, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Threading.Tasks Imports System.Xml.Serialization Class UseXmlReaderForDeserialize Private Async Function TestMethod(stream As Stream) As Task Await Task.Run(Function() Dim serializer As New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(stream) End Function) End Function Private Async Sub TestMethod2() Await TestMethod(Nothing) End Sub End Class", GetCA3075DeserializeBasicResultAt(10, 9) ); } [Fact] public async Task UseXmlSerializerDeserializeWithXmlReaderShouldNoGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml; using System.Xml.Serialization; namespace TestNamespace { public class UseXmlReaderForDeserialize { public void TestMethod(XmlTextReader reader) { System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(UseXmlReaderForDeserialize)); serializer.Deserialize(reader); } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Xml Imports System.Xml.Serialization Namespace TestNamespace Public Class UseXmlReaderForDeserialize Public Sub TestMethod(reader As XmlTextReader) Dim serializer As System.Xml.Serialization.XmlSerializer = New XmlSerializer(GetType(UseXmlReaderForDeserialize)) serializer.Deserialize(reader) End Sub End Class End Namespace"); } } }
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 using Microsoft.VisualBasic.PowerPacks; namespace _4PosBackOffice.NET { internal partial class frmPayoutGroup : System.Windows.Forms.Form { private ADODB.Recordset withEventsField_adoPrimaryRS; public ADODB.Recordset adoPrimaryRS { get { return withEventsField_adoPrimaryRS; } set { if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord; } withEventsField_adoPrimaryRS = value; if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord; } } } bool mbChangedByCode; int mvBookMark; bool mbEditFlag; bool mbAddNewFlag; bool mbDataChanged; List<TextBox> txtFields = new List<TextBox>(); List<CheckBox> chkFields = new List<CheckBox>(); int gID; private void buildDataControls() { // doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name" } private void doDataControl(ref System.Windows.Forms.Control dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField) { //Dim rs As ADODB.Recordset //rs = getRS(sql) //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.DataSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.DataSource = rs //UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' //dataControl.DataSource = adoPrimaryRS //UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' //dataControl.DataField = DataField //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.boundColumn = boundColumn //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.listField = listField } public void loadItem(ref int id) { System.Windows.Forms.TextBox oText = null; System.Windows.Forms.CheckBox oCheck = null; // ERROR: Not supported in C#: OnErrorStatement if (id) { adoPrimaryRS = modRecordSet.getRS(ref "select * from PayoutGroup WHERE PayoutGroupID = " + id); } else { adoPrimaryRS = modRecordSet.getRS(ref "select * from PayoutGroup"); adoPrimaryRS.AddNew(); this.Text = this.Text + " [New record]"; mbAddNewFlag = true; } setup(); foreach (TextBox oText_loopVariable in this.txtFields) { oText = oText_loopVariable; oText.DataBindings.Add(adoPrimaryRS); oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize; } foreach (CheckBox oCheck_loopVariable in this.chkFields) { oCheck = oCheck_loopVariable; oCheck.DataBindings.Add(adoPrimaryRS); } buildDataControls(); mbDataChanged = false; ShowDialog(); } private void setup() { } private void frmPayoutGroup_Load(object sender, System.EventArgs e) { txtFields.AddRange(new TextBox[] { _txtFields_0 }); chkFields.AddRange(new CheckBox[] { _chkFields_1 }); } private void frmPayoutGroup_Resize(System.Object eventSender, System.EventArgs eventArgs) { Button cmdLast = new Button(); Button cmdnext = new Button(); Label lblStatus = new Label(); // ERROR: Not supported in C#: OnErrorStatement lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500; cmdnext.Left = lblStatus.Width + 700; cmdLast.Left = cmdnext.Left + 340; } private void frmPayoutGroup_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (mbEditFlag | mbAddNewFlag) goto EventExitSub; switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; adoPrimaryRS.Move(0); cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); cmdClose_Click(cmdClose, new System.EventArgs()); break; } EventExitSub: eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmPayoutGroup_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs) { //UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"' System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This will display the current record position for this recordset } private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This is where you put validation code //This event gets called when the following actions occur bool bCancel = false; switch (adReason) { case ADODB.EventReasonEnum.adRsnAddNew: break; case ADODB.EventReasonEnum.adRsnClose: break; case ADODB.EventReasonEnum.adRsnDelete: break; case ADODB.EventReasonEnum.adRsnFirstChange: break; case ADODB.EventReasonEnum.adRsnMove: break; case ADODB.EventReasonEnum.adRsnRequery: break; case ADODB.EventReasonEnum.adRsnResynch: break; case ADODB.EventReasonEnum.adRsnUndoAddNew: break; case ADODB.EventReasonEnum.adRsnUndoDelete: break; case ADODB.EventReasonEnum.adRsnUndoUpdate: break; case ADODB.EventReasonEnum.adRsnUpdate: break; } if (bCancel) adStatus = ADODB.EventStatusEnum.adStatusCancel; } private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs) { // ERROR: Not supported in C#: OnErrorStatement if (mbAddNewFlag) { this.Close(); } else { mbEditFlag = false; mbAddNewFlag = false; adoPrimaryRS.CancelUpdate(); if (mvBookMark > 0) { adoPrimaryRS.Bookmark = mvBookMark; } else { adoPrimaryRS.MoveFirst(); } mbDataChanged = false; } } //UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"' private bool update_Renamed() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement functionReturnValue = true; adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll); if (mbAddNewFlag) { adoPrimaryRS.MoveLast(); //move to the new record } mbEditFlag = false; mbAddNewFlag = false; mbDataChanged = false; return functionReturnValue; UpdateErr: Interaction.MsgBox(Err().Description); functionReturnValue = false; return functionReturnValue; } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); if (update_Renamed()) { this.Close(); } } private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs) { int Index = 0; modUtilities.MyGotFocus(ref _txtFields_0); } private void txtInteger_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtInteger(Index) } private void txtInteger_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtInteger_MyLostFocus(ref short Index) { // LostFocus txtInteger(Index), 0 } private void txtFloat_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloat(Index) } private void txtFloat_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtFloat_MyLostFocus(ref short Index) { // MyGotFocusNumeric txtFloat(Index), 2 } private void txtFloatNegative_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloatNegative(Index) } private void txtFloatNegative_KeyPress(ref short Index, ref short KeyAscii) { // KeyPressNegative txtFloatNegative(Index), KeyAscii } private void txtFloatNegative_MyLostFocus(ref short Index) { // LostFocus txtFloatNegative(Index), 2 } } }
using System; using System.Collections.Generic; using System.Globalization; using NUnit.Framework; using Org.BouncyCastle.Asn1.Sec; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Security; namespace Org.BouncyCastle.Math.EC.Tests { /** * Test class for {@link org.bouncycastle.math.ec.ECPoint ECPoint}. All * literature values are taken from "Guide to elliptic curve cryptography", * Darrel Hankerson, Alfred J. Menezes, Scott Vanstone, 2004, Springer-Verlag * New York, Inc. */ [TestFixture] public class ECPointTest { /** * Random source used to generate random points */ private readonly SecureRandom _secRand = new SecureRandom(); // private ECPointTest.Fp fp = null; // private ECPointTest.F2m f2m = null; /** * Nested class containing sample literature values for <code>Fp</code>. */ public class Fp { internal static readonly IBigInteger Q = new BigInteger("29"); internal static readonly IBigInteger A = new BigInteger("4"); internal static readonly IBigInteger B = new BigInteger("20"); internal static readonly FPCurve Curve = new FPCurve(Q, A, B); internal static readonly FPPoint Infinity = (FPPoint) Curve.Infinity; internal static readonly int[] PointSource = { 5, 22, 16, 27, 13, 6, 14, 6 }; internal static FPPoint[] P = new FPPoint[PointSource.Length / 2]; /** * Creates the points on the curve with literature values. */ internal static void CreatePoints() { for (var i = 0; i < PointSource.Length / 2; i++) { var x = new FPFieldElement(Q, new BigInteger(PointSource[2 * i].ToString(CultureInfo.InvariantCulture))); var y = new FPFieldElement(Q, new BigInteger(PointSource[2 * i + 1].ToString(CultureInfo.InvariantCulture))); P[i] = new FPPoint(Curve, x, y); } } } /** * Nested class containing sample literature values for <code>F2m</code>. */ public class F2M { // Irreducible polynomial for TPB z^4 + z + 1 internal const int M = 4; internal const int K1 = 1; // a = z^3 internal static readonly F2MFieldElement ATpb = new F2MFieldElement(M, K1, new BigInteger("8", 16)); // b = z^3 + 1 internal static readonly F2MFieldElement BTpb = new F2MFieldElement(M, K1, new BigInteger("9", 16)); internal static readonly F2MCurve Curve = new F2MCurve(M, K1, ATpb .ToBigInteger(), BTpb.ToBigInteger()); internal static readonly F2MPoint Infinity = (F2MPoint) Curve.Infinity; internal static readonly string[] PointSource = { "2", "f", "c", "c", "1", "1", "b", "2" }; internal static F2MPoint[] P = new F2MPoint[PointSource.Length / 2]; /** * Creates the points on the curve with literature values. */ internal static void CreatePoints() { for (var i = 0; i < PointSource.Length / 2; i++) { var x = new F2MFieldElement(M, K1, new BigInteger(PointSource[2 * i], 16)); var y = new F2MFieldElement(M, K1, new BigInteger(PointSource[2 * i + 1], 16)); P[i] = new F2MPoint(Curve, x, y); } } } [SetUp] public void SetUp() { // fp = new ECPointTest.Fp(); Fp.CreatePoints(); // f2m = new ECPointTest.F2m(); F2M.CreatePoints(); } /** * Tests, if inconsistent points can be created, i.e. points with exactly * one null coordinate (not permitted). */ [Test] public void TestPointCreationConsistency() { try { var bad = new FPPoint(Fp.Curve, new FPFieldElement( Fp.Q, new BigInteger("12")), null); Assert.Fail(); } catch (ArgumentException) { // Expected } try { var bad = new FPPoint(Fp.Curve, null, new FPFieldElement(Fp.Q, new BigInteger("12"))); Assert.Fail(); } catch (ArgumentException) { // Expected } try { var bad = new F2MPoint(F2M.Curve, new F2MFieldElement( F2M.M, F2M.K1, new BigInteger("1011")), null); Assert.Fail(); } catch (ArgumentException) { // Expected } try { var bad = new F2MPoint(F2M.Curve, null, new F2MFieldElement(F2M.M, F2M.K1, new BigInteger("1011"))); Assert.Fail(); } catch (ArgumentException) { // Expected } } /** * Tests <code>ECPoint.add()</code> against literature values. * * @param p * The array of literature values. * @param infinity * The point at infinity on the respective curve. */ private static void ImplTestAdd(IList<ECPoint> p, ECPoint infinity) { Assert.AreEqual(p[2], p[0].Add(p[1]), "p0 plus p1 does not equal p2"); Assert.AreEqual(p[2], p[1].Add(p[0]), "p1 plus p0 does not equal p2"); foreach (var t in p) { Assert.AreEqual(t, t.Add(infinity), "Adding infinity failed"); Assert.AreEqual(t, infinity.Add(t), "Adding to infinity failed"); } } /** * Calls <code>implTestAdd()</code> for <code>Fp</code> and * <code>F2m</code>. */ [Test] public void TestAdd() { ImplTestAdd(Fp.P, Fp.Infinity); ImplTestAdd(F2M.P, F2M.Infinity); } /** * Tests <code>ECPoint.twice()</code> against literature values. * * @param p * The array of literature values. */ private static void ImplTestTwice(IList<ECPoint> p) { Assert.AreEqual(p[3], p[0].Twice(), "Twice incorrect"); Assert.AreEqual(p[3], p[0].Add(p[0]), "Add same point incorrect"); } /** * Calls <code>implTestTwice()</code> for <code>Fp</code> and * <code>F2m</code>. */ [Test] public void TestTwice() { ImplTestTwice(Fp.P); ImplTestTwice(F2M.P); } /** * Goes through all points on an elliptic curve and checks, if adding a * point <code>k</code>-times is the same as multiplying the point by * <code>k</code>, for all <code>k</code>. Should be called for points * on very small elliptic curves only. * * @param p * The base point on the elliptic curve. * @param infinity * The point at infinity on the elliptic curve. */ private static void ImplTestAllPoints(ECPoint p, ECPoint infinity) { var adder = infinity; var i = 1; do { adder = adder.Add(p); var multiplier = p.Multiply(new BigInteger(i.ToString(CultureInfo.InvariantCulture))); Assert.AreEqual(adder, multiplier, "Results of add() and multiply() are inconsistent " + i); i++; } while (!(adder.Equals(infinity))); } /** * Calls <code>implTestAllPoints()</code> for the small literature curves, * both for <code>Fp</code> and <code>F2m</code>. */ [Test] public void TestAllPoints() { foreach (var t in Fp.P) { ImplTestAllPoints(t, Fp.Infinity); } foreach (var t in F2M.P) { ImplTestAllPoints(t, F2M.Infinity); } } /** * Simple shift-and-add multiplication. Serves as reference implementation * to verify (possibly faster) implementations in * {@link org.bouncycastle.math.ec.ECPoint ECPoint}. * * @param p * The point to multiply. * @param k * The multiplier. * @return The result of the point multiplication <code>kP</code>. */ private ECPoint multiply(ECPoint p, IBigInteger k) { ECPoint q = p.Curve.Infinity; int t = k.BitLength; for (int i = 0; i < t; i++) { if (k.TestBit(i)) { q = q.Add(p); } p = p.Twice(); } return q; } /** * Checks, if the point multiplication algorithm of the given point yields * the same result as point multiplication done by the reference * implementation given in <code>multiply()</code>. This method chooses a * random number by which the given point <code>p</code> is multiplied. * * @param p * The point to be multiplied. * @param numBits * The bitlength of the random number by which <code>p</code> * is multiplied. */ private void ImplTestMultiply(ECPoint p, int numBits) { var k = new BigInteger(numBits, _secRand); var reff = multiply(p, k); var q = p.Multiply(k); Assert.AreEqual(reff, q, "ECPoint.multiply is incorrect"); } /** * Checks, if the point multiplication algorithm of the given point yields * the same result as point multiplication done by the reference * implementation given in <code>multiply()</code>. This method tests * multiplication of <code>p</code> by every number of bitlength * <code>numBits</code> or less. * * @param p * The point to be multiplied. * @param numBits * Try every multiplier up to this bitlength */ private void ImplTestMultiplyAll(ECPoint p, int numBits) { var bound = BigInteger.Two.Pow(numBits); var k = BigInteger.Zero; do { var reff = multiply(p, k); var q = p.Multiply(k); Assert.AreEqual(reff, q, "ECPoint.multiply is incorrect"); k = k.Add(BigInteger.One); } while (k.CompareTo(bound) < 0); } /** * Tests <code>ECPoint.add()</code> and <code>ECPoint.subtract()</code> * for the given point and the given point at infinity. * * @param p * The point on which the tests are performed. * @param infinity * The point at infinity on the same curve as <code>p</code>. */ private void implTestAddSubtract(ECPoint p, ECPoint infinity) { Assert.AreEqual(p.Twice(), p.Add(p), "Twice and Add inconsistent"); Assert.AreEqual(p, p.Twice().Subtract(p), "Twice p - p is not p"); Assert.AreEqual(infinity, p.Subtract(p), "p - p is not infinity"); Assert.AreEqual(p, p.Add(infinity), "p plus infinity is not p"); Assert.AreEqual(p, infinity.Add(p), "infinity plus p is not p"); Assert.AreEqual(infinity, infinity.Add(infinity), "infinity plus infinity is not infinity "); } /** * Calls <code>implTestAddSubtract()</code> for literature values, both * for <code>Fp</code> and <code>F2m</code>. */ [Test] public void TestAddSubtractMultiplySimple() { for (var iFp = 0; iFp < Fp.PointSource.Length / 2; iFp++) { implTestAddSubtract(Fp.P[iFp], Fp.Infinity); // Could be any numBits, 6 is chosen at will ImplTestMultiplyAll(Fp.P[iFp], 6); ImplTestMultiplyAll(Fp.Infinity, 6); } for (var iF2M = 0; iF2M < F2M.PointSource.Length / 2; iF2M++) { implTestAddSubtract(F2M.P[iF2M], F2M.Infinity); // Could be any numBits, 6 is chosen at will ImplTestMultiplyAll(F2M.P[iF2M], 6); ImplTestMultiplyAll(F2M.Infinity, 6); } } /** * Test encoding with and without point compression. * * @param p * The point to be encoded and decoded. */ private void implTestEncoding(ECPoint p) { // Not Point Compression ECPoint unCompP; // Point compression ECPoint compP; if (p is FPPoint) { unCompP = new FPPoint(p.Curve, p.X, p.Y, false); compP = new FPPoint(p.Curve, p.X, p.Y, true); } else { unCompP = new F2MPoint(p.Curve, p.X, p.Y, false); compP = new F2MPoint(p.Curve, p.X, p.Y, true); } byte[] unCompBarr = unCompP.GetEncoded(); ECPoint decUnComp = p.Curve.DecodePoint(unCompBarr); Assert.AreEqual(p, decUnComp, "Error decoding uncompressed point"); byte[] compBarr = compP.GetEncoded(); ECPoint decComp = p.Curve.DecodePoint(compBarr); Assert.AreEqual(p, decComp, "Error decoding compressed point"); } /** * Calls <code>implTestAddSubtract()</code>, * <code>implTestMultiply</code> and <code>implTestEncoding</code> for * the standard elliptic curves as given in <code>SecNamedCurves</code>. */ [Test] public void TestAddSubtractMultiplyTwiceEncoding() { foreach (string name in SecNamedCurves.Names) { X9ECParameters x9ECParameters = SecNamedCurves.GetByName(name); IBigInteger n = x9ECParameters.N; // The generator is multiplied by random b to get random q IBigInteger b = new BigInteger(n.BitLength, _secRand); ECPoint g = x9ECParameters.G; ECPoint q = g.Multiply(b); // Get point at infinity on the curve ECPoint infinity = x9ECParameters.Curve.Infinity; implTestAddSubtract(q, infinity); ImplTestMultiply(q, n.BitLength); ImplTestMultiply(infinity, n.BitLength); implTestEncoding(q); } } } }
using System; using System.Linq; using Moq; using NuGet.VisualStudio; using NuGet.VisualStudio.Test; using Xunit; using System.Collections.Generic; namespace NuGet.PowerShell.Commands.Test { public class GetPackageVersionCommandTest { [Fact] public void WillWriteThePackageVersionsReturnedFromTheApiCall() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", StubResults = new string[] { "1.0", "2.0" } }; var result = cmdlet.GetResults().Cast<string>(); Assert.Equal("1.0", result.First()); Assert.Equal("2.0", result.ElementAt(1)); } [Fact] public void WillUseTheActivePackageSourceToBuildTheUriWhenNoSourceParameterIsSpecified() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", StubPackageSource = "http://theActivePackageSourceUri" }; cmdlet.GetResults().Cast<string>(); Assert.Equal("http://theactivepackagesourceuri", cmdlet.ActualApiEndpointUri.GetLeftPart(UriPartial.Authority)); } [Fact] public void WillUseTheSourceParameterWhenSpecified() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", Source = "http://theSourceParameterUri" }; cmdlet.GetResults().Cast<string>(); Assert.Equal("http://thesourceparameteruri", cmdlet.ActualApiEndpointUri.GetLeftPart(UriPartial.Authority)); } [Fact] public void WillAppendTheApiPathWithIdToTheApiUri() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId" }; cmdlet.GetResults().Cast<string>(); Assert.Equal("/api/v2/package-versions/theId", cmdlet.ActualApiEndpointUri.PathAndQuery); } [Fact] public void WillIncludeAPrereleaseQueryStringParameterInApiUriWhenPrereleaseParameterIsTrue() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", IncludePrerelease = true }; cmdlet.GetResults().Cast<string>(); Assert.Contains("includePrerelease=true", cmdlet.ActualApiEndpointUri.ToString()); } [Fact] public void WillNotIncludeAPrereleaseQueryStringParameterInApiUriWhenPrereleaseParameterIsFalse() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", IncludePrerelease = false }; cmdlet.GetResults().Cast<string>(); Assert.DoesNotContain("includePrerelease", cmdlet.ActualApiEndpointUri.ToString()); } [Fact] public void WillUseTheRepositoryPackagesWhenTheRepositoryIsNotHttpBased() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", StubPackageSource = "c:\\aPackageDir", StubRepositoryPackages = new IPackage[] { CreateStubPackage("theId", "1.0"), CreateStubPackage("theId", "2.0"), } }; var result = cmdlet.GetResults().Cast<string>(); Assert.Equal("1.0", result.First()); Assert.Equal("2.0", result.ElementAt(1)); } [Fact] public void WillIncludeRepositoryPackagesWithPrereleaseVersionsWhenFlagged() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", IncludePrerelease = true, StubPackageSource = "c:\\aPackageDir", StubRepositoryPackages = new IPackage[] { CreateStubPackage("theId", "1.0"), CreateStubPackage("theId", "2.0-pre"), } }; var result = cmdlet.GetResults().Cast<string>(); Assert.Equal("1.0", result.First()); Assert.Equal("2.0-pre", result.ElementAt(1)); } [Fact] public void WillNotIncludeRepositoryPackagesWithPrereleaseVersionsWhenNotFlagged() { var cmdlet = new TestableGetRemotePackageVersionCommand { Id = "theId", IncludePrerelease = false, StubPackageSource = "c:\\aPackageDir", StubRepositoryPackages = new IPackage[] { CreateStubPackage("theId", "1.0"), CreateStubPackage("theId", "2.0-pre"), } }; var result = cmdlet.GetResults().Cast<string>(); Assert.Equal("1.0", result.First()); Assert.Equal(1, result.Count()); } [Fact] public void WillAggregateResultsWhenThePackageRepositoryIsAnAggregateRepository() { var cmdlet = new TestableGetRemotePackageVersionCommand() { Id = "theId", StubResults = new string[] { "1.0", "2.0-pre" }, StubPackageRepository = new AggregateRepository( new[] { CreateStubPackageRepository( new [] { CreateStubPackage("theId", "1.0"), CreateStubPackage("theId", "2.0-pre"), }, "http://theuri"), CreateStubPackageRepository( new [] { CreateStubPackage("theId", "3.0"), CreateStubPackage("theId", "4.0"), }, "c:\\packages"), }), }; var result = cmdlet.GetResults().Cast<string>(); Assert.Contains("1.0", result); Assert.Contains("2.0-pre", result); Assert.Contains("3.0", result); Assert.Contains("4.0", result); } private static IPackageRepository CreateActiveRepository() { var remotePackages = new[] { NuGet.Test.PackageUtility.CreatePackage("P0", "1.1"), NuGet.Test.PackageUtility.CreatePackage("P1", "1.1"), NuGet.Test.PackageUtility.CreatePackage("P2", "1.2"), NuGet.Test.PackageUtility.CreatePackage("P3") }; var remoteRepo = new Mock<IPackageRepository>(); remoteRepo.Setup(c => c.GetPackages()).Returns(remotePackages.AsQueryable()); return remoteRepo.Object; } private static IVsPackageSourceProvider CreateSourceProvider(string activeSourceName) { Mock<IVsPackageSourceProvider> sourceProvider = new Mock<IVsPackageSourceProvider>(); sourceProvider.Setup(c => c.ActivePackageSource).Returns(new PackageSource(activeSourceName, activeSourceName)); return sourceProvider.Object; } private static IPackage CreateStubPackage(string id, string version = "1.0") { var stubPackage = new Mock<IPackage>(); stubPackage.Setup(stub => stub.Id).Returns(id); stubPackage.Setup(stub => stub.Version).Returns(new SemanticVersion(version)); return stubPackage.Object; } private static IPackageRepository CreateStubPackageRepository(IEnumerable<IPackage> packages, string source) { var stubPackageRepository = new Mock<IPackageRepository>(); stubPackageRepository.Setup(stub => stub.Source).Returns(source ?? "http://aUri"); stubPackageRepository.Setup(stub => stub.GetPackages()).Returns((packages ?? new IPackage[] { }).AsQueryable()); return stubPackageRepository.Object; } private static IVsPackageManager CreateStubPackageManager(IEnumerable<IPackage> localPackages = null) { var fileSystem = new Mock<IFileSystem>(); var localRepo = new Mock<ISharedPackageRepository>(); localPackages = localPackages ?? new[] { NuGet.Test.PackageUtility.CreatePackage("P1", "0.9"), NuGet.Test.PackageUtility.CreatePackage("P2") }; localRepo.Setup(c => c.GetPackages()).Returns(localPackages.AsQueryable()); return new VsPackageManager(TestUtils.GetSolutionManager(), CreateActiveRepository(), new Mock<IFileSystemProvider>().Object, fileSystem.Object, localRepo.Object, new Mock<IDeleteOnRestartManager>().Object, new Mock<VsPackageInstallerEvents>().Object); } private static IVsPackageManagerFactory CreateStubPackageManagerFactory() { var mockFactory = new Mock<IVsPackageManagerFactory>(); mockFactory.Setup(m => m.CreatePackageManager()).Returns(() => CreateStubPackageManager()); return mockFactory.Object; } public class TestableGetRemotePackageVersionCommand : GetRemotePackageVersionCommand { public TestableGetRemotePackageVersionCommand() : base(TestUtils.GetSolutionManager(), CreateStubPackageManagerFactory(), null, null, CreateSourceProvider("http://aUri")) { } public Uri ActualApiEndpointUri { get; private set; } public IPackageRepository StubPackageRepository { get; set; } public string StubPackageSource { get; set; } public IEnumerable<IPackage> StubRepositoryPackages { get; set; } public string[] StubResults { get; set; } protected override IPackageRepository GetPackageRepository() { if (StubPackageRepository != null) return StubPackageRepository; var stubPackageRepository = new Mock<IPackageRepository>(); stubPackageRepository.Setup(stub => stub.Source).Returns(Source ?? StubPackageSource ?? "http://aUri"); stubPackageRepository.Setup(stub => stub.GetPackages()).Returns((StubRepositoryPackages ?? new IPackage[] { }).AsQueryable()); return stubPackageRepository.Object; } protected override IEnumerable<string> GetResults(Uri apiEndpointUri) { ActualApiEndpointUri = apiEndpointUri; return StubResults ?? new string[] { }; } } } }
// 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.Numerics; partial class VectorTest { const int Pass = 100; const int Fail = -1; static Random random; // Arrays to use for creating random Vectors. static Double[] doubles; static Single[] singles; static Int64[] int64s; static UInt64[] uint64s; static Int32[] int32s; static UInt32[] uint32s; static Int16[] int16s; static UInt16[] uint16s; static SByte[] sbytes; static Byte[] bytes; static VectorTest() { doubles = new Double[Vector<Double>.Count]; singles = new Single[Vector<Single>.Count]; int64s = new Int64[Vector<Int64>.Count]; uint64s = new UInt64[Vector<UInt64>.Count]; int32s = new Int32[Vector<Int32>.Count]; uint32s = new UInt32[Vector<UInt32>.Count]; int16s = new Int16[Vector<Int16>.Count]; uint16s = new UInt16[Vector<UInt16>.Count]; sbytes = new SByte[Vector<SByte>.Count]; bytes = new Byte[Vector<Byte>.Count]; random = new Random(1234); } static T getRandomValue<T>() { int sign = (random.Next(0, 2) < 1) ? -1 : 1; if (typeof(T) == typeof(float)) { float floatValue = (float)random.NextDouble() * (float)(Int32.MaxValue) * (float)sign; return (T)(object)floatValue; } if (typeof(T) == typeof(double)) { return (T)(object)(random.NextDouble() * (double)(Int64.MaxValue) * (double)sign); } if (typeof(T) == typeof(Int64)) { return (T)(object)(Int64)(random.NextDouble() * (double)(Int64.MaxValue) * (double)sign); } if (typeof(T) == typeof(UInt64)) { return (T)(object)(UInt64)(random.NextDouble() * (double)(Int64.MaxValue)); } int intValue = (int)(random.NextDouble() * (double)(Int32.MaxValue)); T value = GetValueFromInt<T>(intValue); return value; } static Vector<T> getRandomVector<T>(T[] valueArray) where T : struct { for (int i = 0; i < Vector<T>.Count; i++) { valueArray[i] = getRandomValue<T>(); } return new Vector<T>(valueArray); } class VectorConvertTest { public static int VectorConvertSingleInt(Vector<Single> A) { Vector<Int32> B = Vector.ConvertToInt32(A); Vector<Single> C = Vector.ConvertToSingle(B); int returnVal = Pass; for (int i = 0; i < Vector<Single>.Count; i++) { Int32 int32Val = (Int32)A[i]; Single cvtSglVal = (Single)int32Val; if (B[i] != int32Val) { Console.WriteLine("B[" + i + "] = " + B[i] + ", int32Val = " + int32Val); returnVal = Fail; } if (C[i] != cvtSglVal) { Console.WriteLine("C[" + i + "] = " + C[i] + ", cvtSglVal = " + cvtSglVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertSingleUInt(Vector<Single> A) { Vector<UInt32> B = Vector.ConvertToUInt32(A); Vector<Single> C = Vector.ConvertToSingle(B); int returnVal = Pass; for (int i = 0; i < Vector<Single>.Count; i++) { UInt32 uint32Val = (UInt32)A[i]; Single cvtSglVal = (Single)uint32Val; if (B[i] != uint32Val) { Console.WriteLine("B[" + i + "] = " + B[i] + ", UInt32Val = " + uint32Val); returnVal = Fail; } if (C[i] != cvtSglVal) { Console.WriteLine("C[" + i + "] = " + C[i] + ", cvtSglVal = " + cvtSglVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertDoubleInt64(Vector<Double> A) { Vector<Int64> B = Vector.ConvertToInt64(A); Vector<Double> C = Vector.ConvertToDouble(B); int returnVal = Pass; for (int i = 0; i < Vector<Double>.Count; i++) { Int64 int64Val = (Int64)A[i]; Double cvtDblVal = (Double)int64Val; if (B[i] != int64Val) { Console.WriteLine("B[" + i + "] = " + B[i] + ", int64Val = " + int64Val); returnVal = Fail; } if (C[i] != cvtDblVal) { Console.WriteLine("C[" + i + "] = " + C[i] + ", cvtDblVal = " + cvtDblVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertDoubleUInt64(Vector<Double> A) { Vector<UInt64> B = Vector.ConvertToUInt64(A); Vector<Double> C = Vector.ConvertToDouble(B); int returnVal = Pass; for (int i = 0; i < Vector<Double>.Count; i++) { UInt64 uint64Val = (UInt64)A[i]; Double cvtDblVal = (Double)uint64Val; if (B[i] != uint64Val) { Console.WriteLine("B[" + i + "] = " + B[i] + ", uint64Val = " + uint64Val); returnVal = Fail; } if (C[i] != cvtDblVal) { Console.WriteLine("C[" + i + "] = " + C[i] + ", cvtDblVal = " + cvtDblVal); returnVal = Fail; } } return returnVal; } public static int VectorConvertDoubleSingle(Vector<Double> A1, Vector<Double> A2) { Vector<Single> B = Vector.Narrow(A1, A2); Vector<Double> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Double>.Count; i++) { Single sglVal1 = (Single)A1[i]; Single sglVal2 = (Single)A2[i]; Double dblVal1 = (Double)sglVal1; Double dblVal2 = (Double)sglVal2; if (B[i] != sglVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", sglVal1 = " + sglVal1); returnVal = Fail; } int i2 = i + Vector<Double>.Count; if (B[i2] != sglVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", sglVal2 = " + sglVal2); returnVal = Fail; } if (C1[i] != dblVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", dblVal1 = " + dblVal1); returnVal = Fail; } if (C2[i] != dblVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", dblVal2 = " + dblVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertInt64And32(Vector<Int64> A1, Vector<Int64> A2) { Vector<Int32> B = Vector.Narrow(A1, A2); Vector<Int64> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Int64>.Count; i++) { Int32 smallVal1 = (Int32)A1[i]; Int32 smallVal2 = (Int32)A2[i]; Int64 largeVal1 = (Int64)smallVal1; Int64 largeVal2 = (Int64)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<Int64>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertInt32And16(Vector<Int32> A1, Vector<Int32> A2) { Vector<Int16> B = Vector.Narrow(A1, A2); Vector<Int32> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Int32>.Count; i++) { Int16 smallVal1 = (Int16)A1[i]; Int16 smallVal2 = (Int16)A2[i]; Int32 largeVal1 = (Int32)smallVal1; Int32 largeVal2 = (Int32)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<Int32>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertInt16And8(Vector<Int16> A1, Vector<Int16> A2) { Vector<SByte> B = Vector.Narrow(A1, A2); Vector<Int16> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<Int16>.Count; i++) { SByte smallVal1 = (SByte)A1[i]; SByte smallVal2 = (SByte)A2[i]; Int16 largeVal1 = (Int16)smallVal1; Int16 largeVal2 = (Int16)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<Int16>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertUInt64And32(Vector<UInt64> A1, Vector<UInt64> A2) { Vector<UInt32> B = Vector.Narrow(A1, A2); Vector<UInt64> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<UInt64>.Count; i++) { UInt32 smallVal1 = (UInt32)A1[i]; UInt32 smallVal2 = (UInt32)A2[i]; UInt64 largeVal1 = (UInt64)smallVal1; UInt64 largeVal2 = (UInt64)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<UInt64>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertUInt32And16(Vector<UInt32> A1, Vector<UInt32> A2) { Vector<UInt16> B = Vector.Narrow(A1, A2); Vector<UInt32> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<UInt32>.Count; i++) { UInt16 smallVal1 = (UInt16)A1[i]; UInt16 smallVal2 = (UInt16)A2[i]; UInt32 largeVal1 = (UInt32)smallVal1; UInt32 largeVal2 = (UInt32)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<UInt32>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } public static int VectorConvertUInt16And8(Vector<UInt16> A1, Vector<UInt16> A2) { Vector<Byte> B = Vector.Narrow(A1, A2); Vector<UInt16> C1, C2; Vector.Widen(B, out C1, out C2); int returnVal = Pass; for (int i = 0; i < Vector<UInt16>.Count; i++) { Byte smallVal1 = (Byte)A1[i]; Byte smallVal2 = (Byte)A2[i]; UInt16 largeVal1 = (UInt16)smallVal1; UInt16 largeVal2 = (UInt16)smallVal2; if (B[i] != smallVal1) { Console.WriteLine("B[" + i + "] = " + B[i] + ", smallVal1 = " + smallVal1); returnVal = Fail; } int i2 = i + Vector<UInt16>.Count; if (B[i2] != smallVal2) { Console.WriteLine("B[" + i2 + "] = " + B[i2] + ", smallVal2 = " + smallVal2); returnVal = Fail; } if (C1[i] != largeVal1) { Console.WriteLine("C1[" + i + "] = " + C1[i] + ", largeVal1 = " + largeVal1); returnVal = Fail; } if (C2[i] != largeVal2) { Console.WriteLine("C2[" + i + "] = " + C2[i] + ", largeVal2 = " + largeVal2); returnVal = Fail; } } return returnVal; } } static int Main() { int returnVal = Pass; for (int i = 0; i < 10; i++) { Vector<Single> singleVector = getRandomVector<Single>(singles); if (VectorConvertTest.VectorConvertSingleInt(singleVector) != Pass) { Console.WriteLine("Testing Converts Between Single and Int32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Single> singleVector = getRandomVector<Single>(singles); if (VectorConvertTest.VectorConvertSingleUInt(singleVector) != Pass) { Console.WriteLine("Testing Converts Between Single and UInt32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Double> doubleVector = getRandomVector<Double>(doubles); if (VectorConvertTest.VectorConvertDoubleInt64(doubleVector) != Pass) { Console.WriteLine("Testing Converts between Double and Int64 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Double> doubleVector = getRandomVector<Double>(doubles); if (VectorConvertTest.VectorConvertDoubleUInt64(doubleVector) != Pass) { Console.WriteLine("Testing Converts between Double and UInt64 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Double> doubleVector1 = getRandomVector<Double>(doubles); Vector<Double> doubleVector2 = getRandomVector<Double>(doubles); if (VectorConvertTest.VectorConvertDoubleSingle(doubleVector1, doubleVector2) != Pass) { Console.WriteLine("Testing Converts between Single and Double failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Int64> int64Vector1 = getRandomVector<Int64>(int64s); Vector<Int64> int64Vector2 = getRandomVector<Int64>(int64s); if (VectorConvertTest.VectorConvertInt64And32(int64Vector1, int64Vector2) != Pass) { Console.WriteLine("Testing Converts between Int64 and Int32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Int32> int32Vector1 = getRandomVector<Int32>(int32s); Vector<Int32> int32Vector2 = getRandomVector<Int32>(int32s); if (VectorConvertTest.VectorConvertInt32And16(int32Vector1, int32Vector2) != Pass) { Console.WriteLine("Testing Converts between Int32 and Int16 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<Int16> int16Vector1 = getRandomVector<Int16>(int16s); Vector<Int16> int16Vector2 = getRandomVector<Int16>(int16s); if (VectorConvertTest.VectorConvertInt16And8(int16Vector1, int16Vector2) != Pass) { Console.WriteLine("Testing Converts between Int16 and SByte failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<UInt64> uint64Vector1 = getRandomVector<UInt64>(uint64s); Vector<UInt64> uint64Vector2 = getRandomVector<UInt64>(uint64s); if (VectorConvertTest.VectorConvertUInt64And32(uint64Vector1, uint64Vector2) != Pass) { Console.WriteLine("Testing Converts between UInt64 and UInt32 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<UInt32> uint32Vector1 = getRandomVector<UInt32>(uint32s); Vector<UInt32> uint32Vector2 = getRandomVector<UInt32>(uint32s); if (VectorConvertTest.VectorConvertUInt32And16(uint32Vector1, uint32Vector2) != Pass) { Console.WriteLine("Testing Converts between UInt32 and UInt16 failed"); returnVal = Fail; } } for (int i = 0; i < 10; i++) { Vector<UInt16> uint16Vector1 = getRandomVector<UInt16>(uint16s); Vector<UInt16> uint16Vector2 = getRandomVector<UInt16>(uint16s); if (VectorConvertTest.VectorConvertUInt16And8(uint16Vector1, uint16Vector2) != Pass) { Console.WriteLine("Testing Converts between UInt16 and Byte failed"); returnVal = Fail; } } return returnVal; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using EmergeTk.Model; namespace EmergeTk.Widgets.Svg { public enum ChartType { Bar, Line, Scatter, Pie } public class Chart<T> : Host, IDataSourced where T : AbstractRecord { public AbstractRecord Selected { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public event EventHandler<DelayedMouseEventArgs> OnNodeDelayedMouseOverHandler; public event EventHandler<DelayedMouseEventArgs> OnNodeDelayedMouseOutHandler; public event EventHandler<ClickEventArgs> OnNodeClickedHandler; public event EventHandler<DragAndDropEventArgs> OnXReceiveDropHandler, OnYReceiveDropHandler, OnColorReceiveDropHandler, OnSizeReceiveDropHandler; string propertySource; public string PropertySource { get { return propertySource; } set { propertySource = value; } } private string xSeries; private bool xRequiresBinding = false; /// <summary> /// Property XSources (string) /// </summary> public string XSeries { get { return this.xSeries; } set { this.xSeries = value; xRequiresBinding = true; } } private string ySeries; private bool yRequiresBinding = false; /// <summary> /// Property YSources (string) /// </summary> public string YSeries { get { return this.ySeries; } set { this.ySeries = value; yRequiresBinding = true; } } private string sizeSeries; private bool sizeRequiresBinding = false; public string SizeSeries { get { return sizeSeries; } set { sizeSeries = value; sizeRequiresBinding = true; } } private string colorSeries; private bool colorRequiresBinding = false; public string ColorSeries { get { return colorSeries; } set { colorSeries = value; colorRequiresBinding = true; } } private string yLabel; /// <summary> /// Property YLabel (string) /// </summary> public string YLabel { get { return this.yLabel; } set { this.yLabel = value; } } private string xLabel; /// <summary> /// Property XLabel (string) /// </summary> public string XLabel { get { return this.xLabel; } set { this.xLabel = value; } } private ChartType type; /// <summary> /// Property Type (ChartType) /// </summary> public ChartType Type { get { return this.type; } set { this.type = value; } } private IRecordList<T> dataSource; /// <summary> /// Property DataSource (RecordList) /// </summary> public IRecordList<T> DataSource { get { return this.dataSource; } set { this.dataSource = value; } } private Dictionary<T,Widget> recordToPoints = new Dictionary<T,Widget>(); public Dictionary<T,Widget> RecordToPoints { get { return recordToPoints; } set { recordToPoints = value; } } private Rect background; public Rect Background { get { return background; } } public Chart() { this.ClientClass = "SvgHost"; } private Svg.Group g; float xmin, xmax, xdelta, ymin, ymax, ydelta, colormin, colormax, colordelta, sizemin, sizemax, sizedelta; Type xType, yType; public void DataBind() { if (DataSource == null) { if( propertySource != null && this.Record != null && this.Record[propertySource] is IRecordList<T> ) dataSource = this.Record[propertySource] as IRecordList<T>; else return; } if( dataSource == null || dataSource.Count == 0 ) return; findMinMax(xSeries, out xmin, out xmax, out xdelta); findMinMax(ySeries, out ymin, out ymax, out ydelta); findMinMax(colorSeries, out colormin, out colormax, out colordelta); findMinMax(sizeSeries, out sizemin, out sizemax, out sizedelta); if (!rendered) { setupGradients(); g = RootContext.CreateWidget<Svg.Group>(); g.Scale(1, -1); g.Translate(0, -900); background = g.DrawRect(0, 0, 1000, 1000, "url(#backgroundGradient)"); for (int i = 0; i <= 10; i++) { Line gridX = new Line("xgrid" + i, i * 100, 0, i * 100, 1000, Color.DarkGray); Line gridY = new Line("xgrid" + i, 0, i * 100, 1000, i * 100, Color.DarkGray); g.Add(gridX, gridY); } g.DrawLine(0, 0, 0, 1000, Color.Black); g.DrawLine(0, 0, 1000, 0, Color.Black); Add(g); //drag regions if (OnXReceiveDropHandler != null && OnYReceiveDropHandler != null) { Rect yAxisDropTarget = new Rect("yAxisDropTarget", -50, 0, 50, 1000, "blue"); yAxisDropTarget.ClassName = "dragTarget"; yAxisDropTarget.OnReceiveDrop += OnYReceiveDropHandler; Rect xAxisDropTarget = new Rect("xAxisDropTarget", 0, -50, 1000, 50, "blue"); xAxisDropTarget.ClassName = "dragTarget"; xAxisDropTarget.OnReceiveDrop += OnXReceiveDropHandler; g.Add(xAxisDropTarget, yAxisDropTarget); } } addLegend(); xType = DataSource[0][xSeries].GetType(); yType = DataSource[0][ySeries].GetType(); ViewBox = new Rectangle( -100, -100, 1200, 1100 ); foreach (T r in dataSource) DrawPoint(r); xRequiresBinding = yRequiresBinding = sizeRequiresBinding = colorRequiresBinding = false; setLabels(); dataBound = true; } bool dataBound = false; public bool IsDataBound { get { return dataBound; } set { dataBound = value; } } public void DrawPoint(T r) { float x = coerceValue(r[xSeries]); float y = coerceValue(r[ySeries]); float color = coerceValue(r[colorSeries]); float size = coerceValue(r[sizeSeries]); x = prepareValue(xmin, xdelta, x, 1000); y = prepareValue(ymin, ydelta, y, 1000); size = prepareValue(sizemin, sizedelta, size, 25) + 5; string colorString = colorFromRange(colormin, colormax, colordelta, color); if (!rendered) { Circle c = g.DrawCircle(x, y, size, colorString, "black"); if (OnNodeDelayedMouseOverHandler != null) c.OnDelayedMouseOver += OnNodeDelayedMouseOverHandler; if (OnNodeDelayedMouseOutHandler != null) c.OnDelayedMouseOut += OnNodeDelayedMouseOutHandler; if( OnNodeClickedHandler != null ) c.OnClick += OnNodeClickedHandler; c.Record = r; this.recordToPoints[r] = c; } else { if( ! recordToPoints.ContainsKey(r) ) return; Circle c = recordToPoints[r] as Circle; if (xRequiresBinding || c.X != x) c.X = x; if (yRequiresBinding || c.Y != y) c.Y = y; if (sizeRequiresBinding || c.R != size) c.R = size; if (colorRequiresBinding || c.Fill != colorString) c.Fill = colorString; } } private void setupGradients() { Gradient gr = RootContext.CreateWidget<Gradient>(); gr.Stops = string.Format("0% {0} 100% {1}", colorStart.ToHtmlColor(), colorEnd.ToHtmlColor()); gr.GradientId = "colorSeriesGradient"; gr.Type = GradientType.linearGradient; gr.Direction = new Vector(0, 1, 0); Add(gr); gr = RootContext.CreateWidget<Gradient>(); gr.Stops = "0% #ccd 100% #ffe"; gr.GradientId = "backgroundGradient"; gr.Type = GradientType.linearGradient; gr.Direction = new Vector(1, 1, 0); Add(gr); } private Text colorKeyLabel, sizeKeyLabel, xKeyLabel, yKeyLabel, colorMinLabel, colorMaxLabel, sizeMinLabel, sizeMaxLabel; private Svg.Group xLabelsGroup, yLabelsGroup; private void addLegend() { if (!rendered) { Svg.Group legendValues = RootContext.CreateWidget<Svg.Group>(); legendValues.Id = "legendValues"; legendValues.Scale(1, -1); Rect r = new Rect("colorKey", 1020, 100, 50, 200, "url(#colorSeriesGradient)"); if (OnColorReceiveDropHandler != null) { r.OnReceiveDrop += OnColorReceiveDropHandler; } Path p = RootContext.CreateWidget<Path>(); p.Fill = "Black"; p.D = "m1036,500 l12,0 l20,200 l-50,0z"; g.Add(p); if (OnSizeReceiveDropHandler != null) { p.OnReceiveDrop += OnSizeReceiveDropHandler; } colorMinLabel = legendValues.DrawText(1045, -80, colormin.ToString(), "middle", fontSize); colorMaxLabel = legendValues.DrawText(1045, -320, colormax.ToString(), "middle", fontSize); sizeMinLabel = legendValues.DrawText(1045, -480, sizemin.ToString(), "middle", fontSize); sizeMaxLabel = legendValues.DrawText(1045, -710, sizemax.ToString(), "middle", fontSize); g.Add(r, legendValues); Svg.Group legendLabels = RootContext.CreateWidget<Svg.Group>(); legendLabels.Id = "legendLabels"; legendLabels.Scale(1, -1); legendLabels.Rotate(-90); colorKeyLabel = legendLabels.DrawText(100, 1100, colorSeries, "start", fontSize); sizeKeyLabel = legendLabels.DrawText(500, 1100, sizeSeries, "start", fontSize); g.Add(legendLabels); } else { if (colormin.ToString() != colorMinLabel.InnerText) { colorKeyLabel.InnerText = colorSeries; colorMinLabel.InnerText = colormin.ToString(); colorMaxLabel.InnerText = colormax.ToString(); } if (sizemin.ToString() != sizeMinLabel.InnerText) { sizeKeyLabel.InnerText = sizeSeries; sizeMinLabel.InnerText = sizemin.ToString(); sizeMaxLabel.InnerText = sizemax.ToString(); } } } private float prepareValue(float min, float delta, float current, float newMax) { return ((current - min) / delta) * newMax; } Vector colorStart = new Vector(100, 50, 0); Vector colorEnd = new Vector(255,150,255); private string colorFromRange(float min, float max, float delta, float current) { Vector colorStart = new Vector(100, 50, 0); Vector colorEnd = new Vector(255, 150, 255); Vector colorRange = colorEnd - colorStart; Vector newColor = (colorRange * ((current - min) / delta)) + colorStart; return newColor.ToHtmlColor(); } private void findMinMax(string column, out float min, out float max, out float delta) { Type t = DataSource[0][column].GetType(); min = max = coerceValue(DataSource[0][column]); foreach (T r in dataSource) { float x = coerceValue(r[column]); if( x < min ) min = x; else if (x > max ) max = x; } delta = max - min; min = (float)Math.Floor(min); min = (float)Math.Ceiling(min); if (delta < 10 || t.IsEnum) { min -= 1; max += 1; } else if( t == typeof(DateTime) ) { min *= 0.9999f; max *= 1.0001f; } else { min -= min % 5; max += 5 - min % 5; } delta = max - min; } private float coerceValue(object o) { if (o is DateTime) { DateTime d = (DateTime)o; return (float)d.Ticks; } else if (o is IConvertible) { return Convert.ToSingle(o); } /*if (o.GetType().IsEnum) { return (float)((int)o); }*/ throw new System.ArgumentOutOfRangeException("o", o, "could not convert o to float."); } /* private object originalize(float f, Type t) { int num_quanta = 10; if (t.IsEnum) { f = (float)Math.Round(f); } else if (t.IsSubclassOf(typeof(Record))) { } }*/ List<string> xlabels, ylabels; private void buildLabels(float min, float max, float delta, List<string> labels, Type t) { int numTicks = 10; if (delta < numTicks) numTicks = (int)delta; if (t == typeof(DateTime)) { numTicks = 5; bool inDays = true; DateTime minDate = new DateTime((long)min); TimeSpan ts = new TimeSpan((long)delta); if( ts.Days < 1 ) { inDays = false; } float space = delta / numTicks; for (int i = 0; i < numTicks; i++) { TimeSpan currTimeSpan = new TimeSpan((long)space*i); DateTime currDate = minDate + currTimeSpan; if( inDays ) labels.Add(currDate.ToShortDateString()); else labels.Add(currDate.ToShortTimeString()); } } else if (t.IsEnum) { //enums are buffered by 1 on each side. labels.Add(string.Empty); labels.AddRange(Enum.GetNames(t)); labels.Add(string.Empty); } else { float space = delta / numTicks; for (int i = 0; i < numTicks; i++) { labels.Add((min + (space * i)).ToString("N0")); } } } int fontSize = 25, headerSize = 35; private void setLabels() { xlabels = new List<string>(); ylabels = new List<string>(); buildLabels( xmin, xmax, xdelta, xlabels, xType); buildLabels( ymin, ymax, ydelta, ylabels, yType ); if (!rendered || this.xKeyLabel.InnerText != XSeries) { if (rendered) { xLabelsGroup.Remove(); xKeyLabel.InnerText = XSeries; } xLabelsGroup = RootContext.CreateWidget<Svg.Group>(); xLabelsGroup.Translate(0, (int)(-1.5 * fontSize)); xLabelsGroup.Scale(1, -1); g.Add(xLabelsGroup); xKeyLabel = xLabelsGroup.DrawText(500, 30, xSeries, "middle", headerSize); int quanta_length = 1000 / xlabels.Count; for (int i = 0; i < xlabels.Count; i++) { xLabelsGroup.DrawText(i * quanta_length, 0, xlabels[i], "middle", fontSize); } } if (!rendered || yKeyLabel.InnerText != YSeries) { if (rendered) { yLabelsGroup.Remove(); yKeyLabel.InnerText = YSeries; } yLabelsGroup = RootContext.CreateWidget<Svg.Group>(); yLabelsGroup.Translate((int)(-1.2 * fontSize), 0); yLabelsGroup.Scale(1, -1); yLabelsGroup.Rotate(-90); g.Add(yLabelsGroup); yKeyLabel = yLabelsGroup.DrawText(500, -10, ySeries, "middle", headerSize); int quanta_length = 1000 / ylabels.Count; for (int i = 0; i < ylabels.Count; i++) { yLabelsGroup.DrawText(i * quanta_length, 10, ylabels[i], "middle", fontSize); } } } #region IDataSourced Members IRecordList IDataSourced.DataSource { get { return dataSource as IRecordList; } set { dataSource = value as IRecordList<T>; } } #endregion } }
using FizzWare.NBuilder; using Moq; using NUnit.Framework; using ReMi.Api.Insfrastructure; using ReMi.Api.Insfrastructure.Queries; using ReMi.Api.Insfrastructure.Security; using ReMi.BusinessEntities.Auth; using ReMi.Common.Constants.Auth; using ReMi.Common.Utils; using ReMi.Contracts.Cqrs; using ReMi.Contracts.Cqrs.Queries; using ReMi.TestUtils.UnitTests; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Hosting; namespace ReMi.Api.Tests.Infrastructure.Queries { [TestFixture] public class QueryActionImplementationTests : TestClassFor<QueryActionImplementation<TestRequest, TestResponse>> { private Mock<IHandleQuery<TestRequest, TestResponse>> _handlerMock; private Mock<IValidateRequest<TestRequest>> _validatorMock; private Mock<IAuthorizationManager> _authorizationManagerMock; private Mock<IPermissionChecker> _permissionCheckerMock; private Mock<ISerialization> _serializationMock; private Mock<IClientRequestInfoRetriever> _clientRequestInfoRetrieverMock; private Mock<IApplicationSettings> _applicationSettingsMock; protected override QueryActionImplementation<TestRequest, TestResponse> ConstructSystemUnderTest() { _handlerMock = new Mock<IHandleQuery<TestRequest, TestResponse>>(MockBehavior.Strict); _validatorMock = new Mock<IValidateRequest<TestRequest>>(MockBehavior.Strict); _authorizationManagerMock = new Mock<IAuthorizationManager>(MockBehavior.Strict); _permissionCheckerMock = new Mock<IPermissionChecker>(MockBehavior.Strict); _serializationMock = new Mock<ISerialization>(MockBehavior.Strict); _clientRequestInfoRetrieverMock = new Mock<IClientRequestInfoRetriever>(MockBehavior.Strict); _applicationSettingsMock = new Mock<IApplicationSettings>(MockBehavior.Strict); _applicationSettingsMock.SetupGet(x => x.LogJsonFormatted).Returns(true); _applicationSettingsMock.SetupGet(x => x.LogQueryResponses).Returns(false); return new QueryActionImplementation<TestRequest, TestResponse> { AuthorizationManager = _authorizationManagerMock.Object, Validator = _validatorMock.Object, PermissionChecker = _permissionCheckerMock.Object, Handler = _handlerMock.Object, Serialization = _serializationMock.Object, ClientRequestInfoRetriever = _clientRequestInfoRetrieverMock.Object, ApplicationSettings = _applicationSettingsMock.Object, }; } [Test] public void Handle_ShouldReturnExpectedResponse_WhenRequestSuccessfulyProcessed() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); var account = BuildAccount(); var expectedResponse = new TestResponse(); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)) .Returns(account); _authorizationManagerMock.Setup(x => x.IsAuthorized(It.IsAny<IEnumerable<Role>>())) .Returns(true); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), account)) .Returns(PermissionStatus.Permmited); _permissionCheckerMock.Setup(x => x.CheckRule(account, query)) .Returns(PermissionStatus.Permmited); _validatorMock.Setup(x => x.ValidateRequest(query)).Returns((IEnumerable<ValidationError>)null); _handlerMock.Setup(x => x.Handle(query)) .Returns(expectedResponse); _serializationMock.Setup(x => x.ToJson(query, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>())) .Returns("json data"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostAddress).Returns("host address"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostName).Returns("host name"); var response = Sut.Handle(actionContext, query); _authorizationManagerMock.Verify(x => x.Authenticate(actionContext)); _validatorMock.Verify(x => x.ValidateRequest(query)); _handlerMock.Verify(x => x.Handle(query)); _serializationMock.Verify(x => x.ToJson(It.IsAny<object>(), It.IsAny<IEnumerable<string>>(), It.IsAny<bool>()), Times.Once); Assert.AreEqual(expectedResponse, response); } [Test] public void Handle_ShouldWriteQueryResponse_WhenFeatureTurnedOn() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); var account = BuildAccount(); var expectedResponse = new TestResponse(); _applicationSettingsMock.SetupGet(x => x.LogQueryResponses).Returns(true); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)) .Returns(account); _authorizationManagerMock.Setup(x => x.IsAuthorized(It.IsAny<IEnumerable<Role>>())) .Returns(true); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), account)) .Returns(PermissionStatus.Permmited); _permissionCheckerMock.Setup(x => x.CheckRule(account, query)) .Returns(PermissionStatus.Permmited); _validatorMock.Setup(x => x.ValidateRequest(query)).Returns((IEnumerable<ValidationError>)null); _handlerMock.Setup(x => x.Handle(query)) .Returns(expectedResponse); _serializationMock.Setup(x => x.ToJson(query, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>())) .Returns("json data"); _serializationMock.Setup(x => x.ToJson(It.IsAny<TestResponse>(), It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>())) .Returns("response"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostAddress).Returns("host address"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostName).Returns("host name"); var response = Sut.Handle(actionContext, query); _serializationMock.Verify(x => x.ToJson(It.IsAny<object>(), It.IsAny<IEnumerable<string>>(), It.IsAny<bool>()), Times.Exactly(2)); } [Test] public void Handle_ShouldReturnStatusForbidden_WhenNoSession() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)) .Returns((Account)null); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), null)) .Returns(PermissionStatus.NotAuthenticated); HttpResponseException result = null; try { Sut.Handle(actionContext, query); } catch (HttpResponseException ex) { result = ex; } Assert.IsNotNull(result); Assert.AreEqual(HttpStatusCode.Forbidden, result.Response.StatusCode); } [Test] public void Handle_ShouldReturnStatusUnauthorized_WhenUserDoNotHavePersmissions() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); var account = BuildAccount(); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)) .Returns(account); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), account)) .Returns(PermissionStatus.NotAuthorized); HttpResponseException result = null; try { Sut.Handle(actionContext, query); } catch (HttpResponseException ex) { result = ex; } Assert.IsNotNull(result); Assert.AreEqual(HttpStatusCode.Unauthorized, result.Response.StatusCode); } [Test] public void Handle_ShouldReturnStatusUnauthorized_WhenRuleIsAppliedAndFail() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); var account = BuildAccount(); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)) .Returns(account); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), account)) .Returns(PermissionStatus.Permmited); _permissionCheckerMock.Setup(x => x.CheckRule(account, query)) .Returns(PermissionStatus.NotAuthorized); HttpResponseException result = null; try { Sut.Handle(actionContext, query); } catch (HttpResponseException ex) { result = ex; } Assert.IsNotNull(result); Assert.AreEqual(HttpStatusCode.Unauthorized, result.Response.StatusCode); } [Test] public void Handle_ShouldReturnStatusNotAcceptable_WhenCommandIsInvalid() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); var account = BuildAccount(); var errorMessage = BuildErrorMessageCollection(); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)) .Returns(account); _authorizationManagerMock.Setup(x => x.IsAuthorized(It.IsAny<IEnumerable<Role>>())) .Returns(true); _validatorMock.Setup(x => x.ValidateRequest(query)) .Returns(errorMessage); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), account)) .Returns(PermissionStatus.Permmited); _permissionCheckerMock.Setup(x => x.CheckRule(account, query)) .Returns(PermissionStatus.Permmited); HttpResponseException result = null; try { Sut.Handle(actionContext, query); } catch (HttpResponseException ex) { result = ex; } Assert.IsNotNull(result); Assert.AreEqual(HttpStatusCode.NotAcceptable, result.Response.StatusCode); } [Test] public void Handle_ShouldPopulateContext_WhenProcessed() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); var account = BuildAccount(); var expectedResponse = new TestResponse(); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)) .Returns(account); _authorizationManagerMock.Setup(x => x.IsAuthorized(It.IsAny<IEnumerable<Role>>())) .Returns(true); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), account)) .Returns(PermissionStatus.Permmited); _permissionCheckerMock.Setup(x => x.CheckRule(account, query)) .Returns(PermissionStatus.Permmited); _validatorMock.Setup(x => x.ValidateRequest(query)).Returns((IEnumerable<ValidationError>)null); _handlerMock.Setup(x => x.Handle(query)) .Returns(expectedResponse); _serializationMock.Setup(x => x.ToJson(query, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>())) .Returns("json data"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostAddress).Returns("host address"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostName).Returns("host name"); Sut.Handle(actionContext, query); Assert.AreNotEqual(query.Context.UserId, Guid.Empty); Assert.AreEqual(account.ExternalId, query.Context.UserId); } [Test] public void Handle_ShouldNotPopulateContext_WhenAnonymousQueryProcessed() { var actionContext = BuildHttpActionContext(); var query = BuildQuery(); var account = (Account) null; var expectedResponse = new TestResponse(); _authorizationManagerMock.Setup(x => x.Authenticate(actionContext)).Returns(account); _authorizationManagerMock.Setup(x => x.IsAuthorized(It.IsAny<IEnumerable<Role>>())) .Returns(true); _permissionCheckerMock.Setup(x => x.CheckQueryPermission(typeof(TestRequest), account)) .Returns(PermissionStatus.Permmited); _permissionCheckerMock.Setup(x => x.CheckRule(account, query)) .Returns(PermissionStatus.Permmited); _validatorMock.Setup(x => x.ValidateRequest(query)).Returns((IEnumerable<ValidationError>)null); _handlerMock.Setup(x => x.Handle(query)) .Returns(expectedResponse); _serializationMock.Setup(x => x.ToJson(query, It.Is<IEnumerable<string>>(s => s.First() == "Password"), It.IsAny<bool>())) .Returns("json data"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostAddress).Returns("host address"); _clientRequestInfoRetrieverMock.SetupGet(x => x.UserHostName).Returns("host name"); Sut.Handle(actionContext, query); Assert.AreEqual(query.Context.UserId, Guid.Empty); Assert.AreEqual("host address", query.Context.UserHostAddress); Assert.AreEqual("host name", query.Context.UserHostName); } private static IEnumerable<ValidationError> BuildErrorMessageCollection() { return Builder<ValidationError>.CreateListOfSize(1) .All() .WithConstructor(() => new ValidationError(RandomData.RandomString(5), RandomData.RandomString(5))) .Build(); } private static TestRequest BuildQuery() { return Builder<TestRequest>.CreateNew() .Build(); } private static HttpActionContext BuildHttpActionContext() { var request = new HttpRequestMessage(); request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration()); var actionContext = new HttpActionContext { ControllerContext = new HttpControllerContext { Request = request } }; return actionContext; } private static Account BuildAccount() { return Builder<Account>.CreateNew() .With(x => x.FullName, RandomData.RandomString(5)) .With(x => x.ExternalId, Guid.NewGuid()) .With(x => x.Role, new Role { Name = "Admin" }) .Build(); } } public class TestRequest : IQuery { public QueryContext Context { get; set; } } public class TestResponse { } }
using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using MonoTouch.CoreFoundation; using MonoTouch.UIKit; using MonoTouch.Foundation; using NServiceKit.OrmLite; using NServiceKit.OrmLite.Sqlite; namespace SqliteExpressionsTest.iOS { [Register("UniversalView")] public class UniversalView : UIView { private UIButton runTests; public UniversalView() { Initialize(); } public UniversalView(RectangleF bounds) : base(bounds) { Initialize(); } void Initialize() { //BackgroundColor = UIColor.Red; this.runTests = UIButton.FromType(UIButtonType.RoundedRect); this.runTests.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleMargins; this.runTests.Bounds = new RectangleF(50, 50, 125, 40); this.runTests.SetTitle("Run tests", UIControlState.Normal); this.runTests.SetTitle("Tests running...", UIControlState.Disabled); this.AddSubview(this.runTests); this.runTests.TouchUpInside += async (sender, args) => { this.runTests.Enabled = false; await this.RunAsync(); this.runTests.Enabled = true; }; } /// <summary> /// Run tests asyncronously. /// </summary> /// <returns> /// The <see cref="Task"/>. /// </returns> private async Task RunAsync() { await Task.Factory.StartNew(RunAuthorTests); } /// <summary> /// The run author tests. /// </summary> private static void RunAuthorTests() { //Console.WriteLine("Hello World!"); //Console.WriteLine("Join Test"); //JoinTest.Test(); //Console.WriteLine("Ignored Field Select Test"); //IgnoredFieldSelectTest.Test(); //Console.WriteLine("Count Test"); //CountTest.Test(); OrmLiteConfig.DialectProvider = SqliteOrmLiteDialectProvider.Instance; SqlExpressionVisitor<Author> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>(); using (IDbConnection db = GetFileConnectionString().OpenDbConnection()) { db.DropTable<Author>(); db.CreateTable<Author>(); db.DeleteAll<Author>(); var authors = new List<Author>(); authors.Add(new Author() { Name = "Demis Bellot", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 99.9m, Comments = "CSharp books", Rate = 10, City = "London" }); authors.Add(new Author() { Name = "Angel Colmenares", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 50.0m, Comments = "CSharp books", Rate = 5, City = "Bogota" }); authors.Add(new Author() { Name = "Adam Witco", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 80.0m, Comments = "Math Books", Rate = 9, City = "London" }); authors.Add(new Author() { Name = "Claudia Espinel", Birthday = DateTime.Today.AddYears(-23), Active = true, Earnings = 60.0m, Comments = "Cooking books", Rate = 10, City = "Bogota" }); authors.Add(new Author() { Name = "Libardo Pajaro", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 80.0m, Comments = "CSharp books", Rate = 9, City = "Bogota" }); authors.Add(new Author() { Name = "Jorge Garzon", Birthday = DateTime.Today.AddYears(-28), Active = true, Earnings = 70.0m, Comments = "CSharp books", Rate = 9, City = "Bogota" }); authors.Add(new Author() { Name = "Alejandro Isaza", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 70.0m, Comments = "Java books", Rate = 0, City = "Bogota" }); authors.Add(new Author() { Name = "Wilmer Agamez", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 30.0m, Comments = "Java books", Rate = 0, City = "Cartagena" }); authors.Add(new Author() { Name = "Rodger Contreras", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 90.0m, Comments = "CSharp books", Rate = 8, City = "Cartagena" }); authors.Add(new Author() { Name = "Chuck Benedict", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "CSharp books", Rate = 8, City = "London" }); authors.Add(new Author() { Name = "James Benedict II", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "Java books", Rate = 5, City = "Berlin" }); authors.Add(new Author() { Name = "Ethan Brown", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 45.0m, Comments = "CSharp books", Rate = 5, City = "Madrid" }); authors.Add(new Author() { Name = "Xavi Garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 75.0m, Comments = "CSharp books", Rate = 9, City = "Madrid" }); authors.Add(new Author() { Name = "Luis garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.0m, Comments = "CSharp books", Rate = 10, City = "Mexico" }); db.InsertAll(authors); // lets start ! // select authors born 20 year ago int year = DateTime.Today.AddYears(-20).Year; int expected = 5; ev.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31)); List<Author> result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(qry => qry.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31))); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31)); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors from London, Berlin and Madrid : 6 expected = 6; ev.Where(rn => Sql.In(rn.City, new object[] { "London", "Madrid", "Berlin" })); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => Sql.In(rn.City, new[] { "London", "Madrid", "Berlin" })); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors from Bogota and Cartagena : 7 expected = 7; ev.Where(rn => Sql.In(rn.City, new object[] { "Bogota", "Cartagena" })); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => Sql.In(rn.City, "Bogota", "Cartagena")); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors which name starts with A expected = 3; ev.Where(rn => rn.Name.StartsWith("A")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => rn.Name.StartsWith("A")); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors which name ends with Garzon o GARZON o garzon ( no case sensitive ) expected = 3; ev.Where(rn => rn.Name.ToUpper().EndsWith("GARZON")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => rn.Name.ToUpper().EndsWith("GARZON")); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors which name ends with garzon //A percent symbol ("%") in the LIKE pattern matches any sequence of zero or more characters //in the string. //An underscore ("_") in the LIKE pattern matches any single character in the string. //Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). expected = 3; ev.Where(rn => rn.Name.EndsWith("garzon")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => rn.Name.EndsWith("garzon")); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors which name contains Benedict expected = 2; ev.Where(rn => rn.Name.Contains("Benedict")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => rn.Name.Contains("Benedict")); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors with Earnings <= 50 expected = 3; ev.Where(rn => rn.Earnings <= 50); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => rn.Earnings <= 50); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // select authors with Rate = 10 and city=Mexio expected = 1; ev.Where(rn => rn.Rate == 10 && rn.City == "Mexico"); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); result = db.Select<Author>(rn => rn.Rate == 10 && rn.City == "Mexico"); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // enough selecting, lets update; // set Active=false where rate =0 expected = 2; ev.Where(rn => rn.Rate == 0).Update(rn => rn.Active); var rows = db.UpdateOnly(new Author() { Active = false }, ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected == rows); // insert values only in Id, Name, Birthday, Rate and Active fields expected = 4; //ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>(); //ev.Insert(rn => new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate }); db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Victor Grozny", Birthday = DateTime.Today.AddYears(-18) }, ev); db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Ivan Chorny", Birthday = DateTime.Today.AddYears(-19) }, ev); ev.Where(rn => !rn.Active); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); //update comment for City == null expected = 2; ev.Where(rn => rn.City == null).Update(rn => rn.Comments); rows = db.UpdateOnly(new Author() { Comments = "No comments" }, ev); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected == rows); // delete where City is null expected = 2; rows = db.Delete(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected == rows); // lets select all records ordered by Rate Descending and Name Ascending //expected = 14; //ev.Where().OrderBy(rn => new { at = Sql.Desc(rn.Rate), rn.Name }); // clear where condition //result = db.Select(ev); //Console.WriteLine(ev.WhereExpression); //Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); //Console.WriteLine(ev.OrderByExpression); //var author = result.FirstOrDefault(); //Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel", author.Name, "Claudia Espinel" == author.Name); // select only first 5 rows .... ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>(); expected = 5; ev.Limit(5); // note: order is the same as in the last sentence result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); // and finally lets select only Name and City (name will be "UPPERCASED" ) //ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), "Name"), rn.City }); //Console.WriteLine(ev.SelectExpression); //result = db.Select(ev); //var author = result.FirstOrDefault(); //Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name); //paging : ev.Limit(0, 4);// first page, page size=4; result = db.Select(ev); var author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name); ev.Limit(4, 4);// second page result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon".ToUpper(), author.Name, "Jorge Garzon".ToUpper() == author.Name); ev.Limit(8, 4);// third page result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Rodger Contreras".ToUpper(), author.Name, "Rodger Contreras".ToUpper() == author.Name); // select distinct.. ev.Limit(); // clear limit ev.SelectDistinct(r => r.City); expected = 6; result = db.Select(ev); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count); Console.WriteLine(); // Tests for predicate overloads that make use of the expression visitor Console.WriteLine("First author by name (exists)"); author = db.First<Author>(a => a.Name == "Jorge Garzon"); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon", author.Name, "Jorge Garzon" == author.Name); try { Console.WriteLine("First author by name (does not exist)"); author = db.First<Author>(a => a.Name == "Does not exist"); Console.WriteLine("Expected exception thrown, OK? False"); } catch { Console.WriteLine("Expected exception thrown, OK? True"); } Console.WriteLine("First author or default (does not exist)"); author = db.FirstOrDefault<Author>(a => a.Name == "Does not exist"); Console.WriteLine("Expected:null ; OK? {0}", author == null); Console.WriteLine("First author or default by city (multiple matches)"); author = db.FirstOrDefault<Author>(a => a.City == "Bogota"); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Angel Colmenares", author.Name, "Angel Colmenares" == author.Name); Console.ReadLine(); Console.WriteLine("Press Enter to continue"); } Console.WriteLine("This is The End my friend!"); } /// <summary> /// The get file connection string. /// </summary> /// <returns> /// The <see cref="string"/>. /// </returns> private static string GetFileConnectionString() { var connectionString = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Personal), "db.sqlite"); //var connectionString = "~/db.sqlite".MapAbsolutePath(); if (File.Exists(connectionString)) { File.Delete(connectionString); } return connectionString; } } [Register("MainViewController")] public class MainViewController : UIViewController { public MainViewController() { } public override void DidReceiveMemoryWarning() { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad() { View = new UniversalView(); base.ViewDidLoad(); } } }
// 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.Runtime.InteropServices; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.EcDsaOpenSsl.Tests { public static class EcDsaOpenSslTests { // TODO: Issue #4337. Temporary workaround for tests to pass on CentOS // where secp224r1 appears to be disabled. private static bool ECDsa224Available { get { try { using (ECDsaOpenSsl e = new ECDsaOpenSsl(224)) e.Exercise(); return true; } catch (Exception exc) { return !exc.Message.Contains("unknown group"); } } } [Fact] public static void DefaultCtor() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [ConditionalFact("ECDsa224Available")] // Issue #4337 public static void Ctor224() { int expectedKeySize = 224; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public static void Ctor384() { int expectedKeySize = 384; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public static void Ctor521() { int expectedKeySize = 521; using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [ConditionalFact("ECDsa224Available")] // Issue #4337 public static void CtorHandle224() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp224r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(224, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public static void CtorHandle384() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp384r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(384, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public static void CtorHandle521() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp521r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public static void CtorHandleDuplicate() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByCurveName(NID_secp521r1); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey)) { // Make sure ECDsaOpenSsl did his own ref-count bump. Interop.Crypto.EcKeyDestroy(ecKey); int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [ConditionalFact("ECDsa224Available")] // Issue #4337 public static void KeySizeProp() { using (ECDsaOpenSsl e = new ECDsaOpenSsl()) { e.KeySize = 384; Assert.Equal(384, e.KeySize); e.Exercise(); e.KeySize = 224; Assert.Equal(224, e.KeySize); e.Exercise(); } } [Fact] public static void VerifyDuplicateKey_ValidHandle() { byte[] data = ByteUtils.RepeatByte(0x71, 11); using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { using (ECDsa second = new ECDsaOpenSsl(firstHandle)) { byte[] signed = second.SignData(data, HashAlgorithmName.SHA512); Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512)); } } } [Fact] public static void VerifyDuplicateKey_DistinctHandles() { using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle()) { Assert.NotSame(firstHandle, firstHandle2); } } [Fact] public static void VerifyDuplicateKey_RefCounts() { byte[] data = ByteUtils.RepeatByte(0x74, 11); byte[] signature; ECDsa second; using (ECDsaOpenSsl first = new ECDsaOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) { signature = first.SignData(data, HashAlgorithmName.SHA384); second = new ECDsaOpenSsl(firstHandle); } // Now show that second still works, despite first and firstHandle being Disposed. using (second) { Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384)); } } [Fact] public static void VerifyDuplicateKey_NullHandle() { SafeEvpPKeyHandle pkey = null; Assert.Throws<ArgumentNullException>(() => new RSAOpenSsl(pkey)); } [Fact] public static void VerifyDuplicateKey_InvalidHandle() { using (ECDsaOpenSsl ecdsa = new ECDsaOpenSsl()) { SafeEvpPKeyHandle pkey = ecdsa.DuplicateKeyHandle(); using (pkey) { } Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey)); } } [Fact] public static void VerifyDuplicateKey_NeverValidHandle() { using (SafeEvpPKeyHandle pkey = new SafeEvpPKeyHandle(IntPtr.Zero, false)) { Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey)); } } [Fact] public static void VerifyDuplicateKey_RsaHandle() { using (RSAOpenSsl rsa = new RSAOpenSsl()) using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle()) { Assert.ThrowsAny<CryptographicException>(() => new ECDsaOpenSsl(pkey)); } } private static void Exercise(this ECDsaOpenSsl e) { // Make a few calls on this to ensure we aren't broken due to bad/prematurely released handles. int keySize = e.KeySize; byte[] data = new byte[0x10]; byte[] sig = e.SignData(data, 0, data.Length, HashAlgorithmName.SHA1); bool verified = e.VerifyData(data, sig, HashAlgorithmName.SHA1); Assert.True(verified); sig[sig.Length - 1]++; verified = e.VerifyData(data, sig, HashAlgorithmName.SHA1); Assert.False(verified); } private const int NID_secp224r1 = 713; private const int NID_secp384r1 = 715; private const int NID_secp521r1 = 716; } } internal static partial class Interop { internal static class Crypto { [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByCurveName")] internal static extern IntPtr EcKeyCreateByCurveName(int nid); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyGenerateKey")] internal static extern int EcKeyGenerateKey(IntPtr ecKey); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyDestroy")] internal static extern void EcKeyDestroy(IntPtr r); } }
namespace EwfUtil { partial class Config { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Config)); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.driveCombo = new System.Windows.Forms.ComboBox(); this.memorySpinner = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.pollingCombo = new System.Windows.Forms.ComboBox(); this.startupCombo = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.cancelBtn = new System.Windows.Forms.Button(); this.okBtn = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.memorySpinner)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSize = true; this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.driveCombo, 1, 0); this.tableLayoutPanel1.Controls.Add(this.memorySpinner, 1, 2); this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1); this.tableLayoutPanel1.Controls.Add(this.label3, 0, 2); this.tableLayoutPanel1.Controls.Add(this.pollingCombo, 1, 1); this.tableLayoutPanel1.Controls.Add(this.startupCombo, 1, 3); this.tableLayoutPanel1.Controls.Add(this.label4, 0, 3); this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 12); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 4; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.Size = new System.Drawing.Size(273, 107); this.tableLayoutPanel1.TabIndex = 0; // // label1 // this.label1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(140, 24); this.label1.TabIndex = 0; this.label1.Text = "Drive:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // driveCombo // this.driveCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.driveCombo.FormattingEnabled = true; this.driveCombo.Items.AddRange(new object[] { "C:", "D:", "E:", "F:", "G:", "H:"}); this.driveCombo.Location = new System.Drawing.Point(149, 3); this.driveCombo.Name = "driveCombo"; this.driveCombo.Size = new System.Drawing.Size(121, 21); this.driveCombo.TabIndex = 1; // // memorySpinner // this.memorySpinner.Increment = new decimal(new int[] { 10, 0, 0, 0}); this.memorySpinner.Location = new System.Drawing.Point(149, 57); this.memorySpinner.Maximum = new decimal(new int[] { 500, 0, 0, 0}); this.memorySpinner.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.memorySpinner.Name = "memorySpinner"; this.memorySpinner.Size = new System.Drawing.Size(120, 20); this.memorySpinner.TabIndex = 3; this.memorySpinner.Value = new decimal(new int[] { 10, 0, 0, 0}); // // label2 // this.label2.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(3, 27); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(140, 24); this.label2.TabIndex = 4; this.label2.Text = "Polling Interval:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label3 // this.label3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(3, 54); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(140, 24); this.label3.TabIndex = 5; this.label3.Text = "Memory Threshold:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // pollingCombo // this.pollingCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.pollingCombo.FormattingEnabled = true; this.pollingCombo.Items.AddRange(new object[] { "30", "60", "120", "300", "600", "1800"}); this.pollingCombo.Location = new System.Drawing.Point(149, 30); this.pollingCombo.Name = "pollingCombo"; this.pollingCombo.Size = new System.Drawing.Size(121, 21); this.pollingCombo.TabIndex = 6; // // startupCombo // this.startupCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.startupCombo.FormattingEnabled = true; this.startupCombo.Items.AddRange(new object[] { "Commit", "Discard", "None"}); this.startupCombo.Location = new System.Drawing.Point(149, 83); this.startupCombo.Name = "startupCombo"; this.startupCombo.Size = new System.Drawing.Size(121, 21); this.startupCombo.TabIndex = 8; // // label4 // this.label4.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(3, 80); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(140, 24); this.label4.TabIndex = 9; this.label4.Text = "On Start Set:"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // cancelBtn // this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelBtn.Location = new System.Drawing.Point(3, 3); this.cancelBtn.Name = "cancelBtn"; this.cancelBtn.Size = new System.Drawing.Size(75, 23); this.cancelBtn.TabIndex = 1; this.cancelBtn.Text = "Cancel"; this.cancelBtn.UseVisualStyleBackColor = true; this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click); // // okBtn // this.okBtn.Location = new System.Drawing.Point(84, 3); this.okBtn.Name = "okBtn"; this.okBtn.Size = new System.Drawing.Size(75, 23); this.okBtn.TabIndex = 2; this.okBtn.Text = "Ok"; this.okBtn.UseVisualStyleBackColor = true; this.okBtn.Click += new System.EventHandler(this.okBtn_Click); // // panel1 // this.panel1.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.panel1.AutoSize = true; this.panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.panel1.Controls.Add(this.cancelBtn); this.panel1.Controls.Add(this.okBtn); this.panel1.Location = new System.Drawing.Point(65, 131); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(162, 29); this.panel1.TabIndex = 3; // // Config // this.AcceptButton = this.okBtn; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelBtn; this.ClientSize = new System.Drawing.Size(293, 169); this.Controls.Add(this.panel1); this.Controls.Add(this.tableLayoutPanel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Config"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "EwfUtil Config"; this.Load += new System.EventHandler(this.Form1_Load); this.tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.memorySpinner)).EndInit(); this.panel1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown memorySpinner; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button cancelBtn; private System.Windows.Forms.Button okBtn; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ComboBox driveCombo; private System.Windows.Forms.ComboBox pollingCombo; private System.Windows.Forms.ComboBox startupCombo; private System.Windows.Forms.Label label4; } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections; using System.Collections.Generic; using Axiom.Collections; using Axiom.Core; using Axiom.MathLib; using Axiom.Graphics; namespace Axiom.Graphics { /// <summary> /// Summary description for SimpleRenderable. /// </summary> public abstract class SimpleRenderable : MovableObject, IRenderable { #region Fields protected Matrix4 worldTransform = Matrix4.Identity; protected AxisAlignedBox box; protected string materialName; protected Material material; protected SceneManager sceneMgr; protected Camera camera; static protected long nextAutoGenName; protected VertexData vertexData; protected IndexData indexData; /// <summary> /// Empty light list to use when there is no parent for this renderable. /// </summary> protected List<Light> dummyLightList = new List<Light>(); protected SortedList customParams = new SortedList(); #endregion Fields #region Constructor /// <summary> /// Default constructor. /// </summary> public SimpleRenderable() { materialName = "BaseWhite"; material = MaterialManager.Instance.GetByName("BaseWhite"); name = "SimpleRenderable" + nextAutoGenName++; material.Load(); } #endregion #region MovableObject Implementation /// <summary> /// /// </summary> public override AxisAlignedBox BoundingBox { get { return (AxisAlignedBox)box.Clone(); } } /// <summary> /// /// </summary> /// <param name="camera"></param> public override void NotifyCurrentCamera(Camera camera) { this.camera = camera; } /// <summary> /// /// </summary> /// <param name="queue"></param> public override void UpdateRenderQueue(RenderQueue queue) { // add ourself to the render queue queue.AddRenderable(this); } #endregion MovableObject Implementation /// <summary> /// Gets/Sets the name of the material used for this SimpleRenderable. /// </summary> public string MaterialName { get { return materialName; } set { if (value == null) throw new AxiomException("Cannot set the SimpleRenderable material to be null"); materialName = value; // load the material from the material manager (it should already exist material = MaterialManager.Instance.GetByName(materialName); if (material == null) { LogManager.Instance.Write( "Cannot assign material '{0}' to SimpleRenderable '{1}' because the material doesn't exist.", materialName, this.Name); // give it base white so we can continue material = MaterialManager.Instance.GetByName("BaseWhite"); } // ensure the material is loaded. It will skip it if it already is material.Load(); } } #region IRenderable Members public bool CastsShadows { get { return CastShadows; } } /// <summary> /// /// </summary> public virtual Material Material { get { return material; } set { material = value; } } public Technique Technique { get { return Material.GetBestTechnique(); } } /// <summary> /// /// </summary> /// <param name="op"></param> public abstract void GetRenderOperation(RenderOperation op); /// <summary> /// /// </summary> /// <param name="matrices"></param> public virtual void GetWorldTransforms(Matrix4[] matrices) { matrices[0] = worldTransform * parentNode.FullTransform; } public bool NormalizeNormals { get { return false; } } /// <summary> /// /// </summary> public virtual ushort NumWorldTransforms { get { return 1; } } /// <summary> /// /// </summary> public virtual bool UseIdentityProjection { get { return false; } } /// <summary> /// /// </summary> public virtual bool UseIdentityView { get { return false; } } /// <summary> /// /// </summary> public SceneDetailLevel RenderDetail { get { return SceneDetailLevel.Solid; } } /// <summary> /// /// </summary> /// <param name="camera"></param> /// <returns></returns> public abstract float GetSquaredViewDepth(Camera camera); /// <summary> /// /// </summary> public virtual Quaternion WorldOrientation { get { return parentNode.DerivedOrientation; } } /// <summary> /// /// </summary> public virtual Vector3 WorldPosition { get { return parentNode.DerivedPosition; } } public List<Light> Lights { get { if(parentNode != null) { return parentNode.Lights; } else { return dummyLightList; } } } public Vector4 GetCustomParameter(int index) { if(customParams[index] == null) { throw new Exception("A parameter was not found at the given index"); } else { return (Vector4)customParams[index]; } } public void SetCustomParameter(int index, Vector4 val) { customParams[index] = val; } public void UpdateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry entry, GpuProgramParameters gpuParams) { if(customParams[entry.data] != null) { gpuParams.SetConstant(entry.index, (Vector4)customParams[entry.data]); } } #endregion } }
// // Copyright 2010, Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Class.cs // // Copyright 2009 Novell, Inc // Copyright 2013 Xamarin Inc // using System; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.Foundation; namespace MonoMac.ObjCRuntime { public class Class : INativeObject { public static bool ThrowOnInitFailure = true; static Dictionary <IntPtr, Type> type_map = new Dictionary <IntPtr, Type> (); static Dictionary <Type, Type> custom_types = new Dictionary <Type, Type> (); static List <Delegate> method_wrappers = new List <Delegate> (); static object lock_obj = new object (); internal IntPtr handle; public Class (string name) { this.handle = objc_getClass (name); if (this.handle == IntPtr.Zero) throw new ArgumentException (String.Format ("name {0} is an unknown class", name), "name"); } public Class (Type type) { this.handle = Class.Register (type); } public Class (IntPtr handle) { this.handle = handle; } internal static Class Construct (IntPtr handle) { return new Class (handle); } public IntPtr Handle { get { return this.handle; } } public IntPtr SuperClass { get { return class_getSuperclass (handle); } } public string Name { get { IntPtr ptr = class_getName (this.handle); return Marshal.PtrToStringAuto (ptr); } } internal static string GetName (IntPtr @class) { return Marshal.PtrToStringAuto (class_getName (@class)); } public static IntPtr GetHandle (string name) { return objc_getClass (name); } public static IntPtr GetHandle (Type type) { RegisterAttribute attr = (RegisterAttribute) Attribute.GetCustomAttribute (type, typeof (RegisterAttribute), false); string name = attr == null ? type.FullName : attr.Name ?? type.FullName; bool is_wrapper = attr == null ? false : attr.IsWrapper; var handle = objc_getClass (name); if (handle == IntPtr.Zero) handle = Class.Register (type, name, is_wrapper); return handle; } public static bool IsCustomType (Type type) { lock (lock_obj) return custom_types.ContainsKey (type); } internal static Type Lookup (IntPtr klass) { return Lookup (klass, true); } internal static Type Lookup (IntPtr klass, bool throw_on_error) { // FAST PATH lock (lock_obj) { Type type; if (type_map.TryGetValue (klass, out type)) return type; // TODO: When we type walk we currently populate the type map // from the walk point with the target, we should gather some // stats here, and see how many times there is a intermediate class // and see if we should populate them in the map as well IntPtr orig_klass = klass; do { IntPtr kls = class_getSuperclass (klass); if (type_map.TryGetValue (kls, out type)) { type_map [orig_klass] = type; return type; } if (kls == IntPtr.Zero) { if (!throw_on_error) return null; var message = "Could not find a valid superclass for type " + new Class (orig_klass).Name + ". Did you forget to register the bindings at " + typeof(Class).FullName + ".Register() or call NSApplication.Init()?"; throw new ArgumentException (message); } klass = kls; } while (true); } } internal static IntPtr Register (Type type) { RegisterAttribute attr = (RegisterAttribute) Attribute.GetCustomAttribute (type, typeof (RegisterAttribute), false); string name = attr == null ? type.FullName : attr.Name ?? type.FullName; bool is_wrapper = attr == null ? false : attr.IsWrapper; return Register (type, name, is_wrapper); } static IntPtr Register (Type type, string name, bool is_wrapper) { IntPtr parent = IntPtr.Zero; IntPtr handle = IntPtr.Zero; handle = objc_getClass (name); lock (lock_obj) { if (handle != IntPtr.Zero) { if (!type_map.ContainsKey (handle)) { type_map [handle] = type; } return handle; } if (objc_getProtocol (name) != IntPtr.Zero) throw new ArgumentException ("Attempting to register a class named: " + name + " which is a valid protocol"); if (is_wrapper) return IntPtr.Zero; Type parent_type = type.BaseType; string parent_name = null; while (Attribute.IsDefined (parent_type, typeof (ModelAttribute), false)) parent_type = parent_type.BaseType; RegisterAttribute parent_attr = (RegisterAttribute)Attribute.GetCustomAttribute (parent_type, typeof(RegisterAttribute), false); parent_name = parent_attr == null ? parent_type.FullName : parent_attr.Name ?? parent_type.FullName; parent = objc_getClass (parent_name); if (parent == IntPtr.Zero && parent_type.Assembly != NSObject.MonoMacAssembly) { bool parent_is_wrapper = parent_attr == null ? false : parent_attr.IsWrapper; // Its possible as we scan that we might be derived from a type that isn't reigstered yet. Register (parent_type, parent_name, parent_is_wrapper); parent = objc_getClass (parent_name); } if (parent == IntPtr.Zero) { // This spams mtouch, we need a way to differentiate from mtouch's (ab)use // Console.WriteLine ("CRITICAL WARNING: Falling back to NSObject for type {0} reported as {1}", type, parent_type); parent = objc_getClass ("NSObject"); } handle = objc_allocateClassPair (parent, name, IntPtr.Zero); foreach (PropertyInfo prop in type.GetProperties (BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { ConnectAttribute cattr = (ConnectAttribute)Attribute.GetCustomAttribute (prop, typeof(ConnectAttribute)); if (cattr != null) { string ivar_name = cattr.Name ?? prop.Name; class_addIvar (handle, ivar_name, (IntPtr)Marshal.SizeOf (typeof(IntPtr)), (ushort)Math.Log (Marshal.SizeOf (typeof(IntPtr)), 2), "@"); } RegisterProperty (prop, type, handle); } NSObject.OverrideRetainAndRelease (handle); foreach (MethodInfo minfo in type.GetMethods (BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) RegisterMethod (minfo, type, handle); ConstructorInfo default_ctor = type.GetConstructor (Type.EmptyTypes); if (default_ctor != null) { NativeConstructorBuilder builder = new NativeConstructorBuilder (default_ctor); class_addMethod (handle, builder.Selector, builder.Delegate, builder.Signature); method_wrappers.Add (builder.Delegate); #if DEBUG Console.WriteLine ("[CTOR] Registering {0}[0x{1:x}|{2}] on {3} -> ({4})", "init", (int) builder.Selector, builder.Signature, type, default_ctor); #endif } foreach (ConstructorInfo cinfo in type.GetConstructors (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { ExportAttribute ea = (ExportAttribute)Attribute.GetCustomAttribute (cinfo, typeof(ExportAttribute)); if (ea == null) continue; NativeConstructorBuilder builder = new NativeConstructorBuilder (cinfo); class_addMethod (handle, builder.Selector, builder.Delegate, builder.Signature); method_wrappers.Add (builder.Delegate); #if DEBUG Console.WriteLine ("[CTOR] Registering {0}[0x{1:x}|{2}] on {3} -> ({4})", ea.Selector, (int) builder.Selector, builder.Signature, type, cinfo); #endif } objc_registerClassPair (handle); type_map [handle] = type; custom_types.Add (type, type); return handle; } } // FIXME: This doesn't properly handle virtual properties yet private unsafe static void RegisterProperty (PropertyInfo prop, Type type, IntPtr handle) { ExportAttribute ea = (ExportAttribute) Attribute.GetCustomAttribute (prop, typeof (ExportAttribute)); if (ea == null) return; if (prop.PropertyType.IsGenericType || prop.PropertyType.IsGenericTypeDefinition) throw new ArgumentException (string.Format ("Cannot export the property '{0}.{1}': it is generic.", prop.DeclaringType.FullName, prop.Name)); var m = prop.GetGetMethod (true); if (m != null) RegisterMethod (m, ea.ToGetter (prop), type, handle); m = prop.GetSetMethod (true); if (m != null) RegisterMethod (m, ea.ToSetter (prop), type, handle); // http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html int count = 0; var props = new objc_attribute_prop [3]; props [count++] = new objc_attribute_prop { name = "T", value = TypeConverter.ToNative (prop.PropertyType) }; switch (ea.ArgumentSemantic) { case ArgumentSemantic.Copy: props [count++] = new objc_attribute_prop { name = "C", value = "" }; break; case ArgumentSemantic.Retain: props [count++] = new objc_attribute_prop { name = "&", value = "" }; break; } props [count++] = new objc_attribute_prop { name = "V", value = ea.Selector }; class_addProperty (handle, ea.Selector, props, count); } private unsafe static void RegisterMethod (MethodInfo minfo, Type type, IntPtr handle) { ExportAttribute ea = (ExportAttribute) Attribute.GetCustomAttribute (minfo.GetBaseDefinition (), typeof (ExportAttribute)); if (ea == null || (minfo.IsVirtual && minfo.DeclaringType != type && minfo.DeclaringType.Assembly == NSObject.MonoMacAssembly)) return; RegisterMethod (minfo, ea, type, handle); } static IntPtr memory; static int size_left; static IntPtr AllocExecMemory (int size) { IntPtr result; if (size_left < size) { size_left = 4096; memory = Marshal.AllocHGlobal (size_left); if (memory == IntPtr.Zero) throw new Exception (string.Format ("Could not allocate memory for specialized x86 floating point stret delegate thunk: {0}", Marshal.GetLastWin32Error ())); if (mprotect (memory, size_left, 7 /*MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC*/) != 0) throw new Exception (string.Format ("Could not make allocated memory for specialized x86 floating point stret delegate thunk code executable: {0}", Marshal.GetLastWin32Error ())); } result = memory; size_left -= size; memory = new IntPtr (memory.ToInt32 () + size); return result; } static bool TypeRequiresFloatingPointTrampoline (Type t) { // this is an x86 requirement only if (IntPtr.Size != 4) return false; if (typeof (float) == t || typeof (double) == t) return false; if (!t.IsValueType || t.IsEnum) return false; if (Marshal.SizeOf (t) <= 8) return false; return TypeContainsFloatingPoint (t); } static bool TypeContainsFloatingPoint (Type t) { if (!t.IsValueType || t.IsEnum || t.IsPrimitive) return false; foreach (var field in t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { if (field.FieldType == typeof (double) || field.FieldType == typeof (float)) return true; if (field.FieldType == t) continue; if (TypeContainsFloatingPoint (field.FieldType)) return true; } return false; } [MonoNativeFunctionWrapper] delegate int getFrameLengthDelegate (IntPtr @this, IntPtr sel); static getFrameLengthDelegate getFrameLength = Selector.GetFrameLength; static IntPtr getFrameLengthPtr = Marshal.GetFunctionPointerForDelegate (getFrameLength); static IntPtr GetFunctionPointer (MethodInfo minfo, Delegate @delegate) { IntPtr fptr = Marshal.GetFunctionPointerForDelegate (@delegate); if (!TypeRequiresFloatingPointTrampoline (minfo.ReturnType)) return fptr; var thunk_ptr = AllocExecMemory (83); var rel_Delegate = new IntPtr (fptr.ToInt32 () - thunk_ptr.ToInt32 () - 70); var rel_GetFrameLengthPtr = new IntPtr (getFrameLengthPtr.ToInt32 () - thunk_ptr.ToInt32 () - 27); var delptr = BitConverter.GetBytes (rel_Delegate.ToInt32 ()); var getlen = BitConverter.GetBytes (rel_GetFrameLengthPtr.ToInt32 ()); var thunk = new byte [] { /* # # the problem we are trying to solve here is that the abi apparently requires # us to leave the stack unbalanced upon return (pop off one more value than we get, # this is the "ret $0x4" at the end). # # method definition: # trampoline (void *buffer, id this, SEL sel, ...) # # input stack layout: # %esp+20: ... # %esp+16: second vararg # %esp+12: first vararg # %esp+8: sel # %esp+4: this # %esp: buffer # and %ebp+8 = %esp # # We extend the stack (big enough for all the arguments again), # and copy all the arguments as-is there, before # calling the original delegate with those copied arguments. # # prolog pushl %ebp */ 0x55, /* movl %esp,%ebp */ 0x89, 0xe5, /* pushl %esi */ 0x56, /* pushl %edi */ 0x57, /* pushl %ebx */ 0x53, /* subl $0x3c,%esp */ 0x83, 0xec, 0x3c, /* # get the size of the stack space used by all the arguments # int frame_length = get_frame_length (this, sel) movl 0x10(%ebp),%eax */ 0x8b, 0x45, 0x10, /* movl %eax,0x04(%esp) */ 0x89, 0x44, 0x24, 0x04, /* movl 0x0c(%ebp),%eax */ 0x8b, 0x45, 0x0c, /* movl %eax,(%esp) */ 0x89, 0x04, 0x24, /* calll _get_frame_length */ 0xe8, getlen [0], getlen [1], getlen [2], getlen [3], /* movl %eax,0xf0(%ebp) */ 0x89, 0x45, 0xf0, /* # use eax to extend the stack, but it needs to be aligned to 16 bytes first addl $0x0f,%eax */ 0x83, 0xc0, 0x0f, /* shrl $0x04,%eax */ 0xc1, 0xe8, 0x04, /* shll $0x04,%eax */ 0xc1, 0xe0, 0x04, /* subl %eax,%esp */ 0x29, 0xc4, /* # copy arguments from old location in the stack to new location in the stack # %ecx will hold the amount of bytes left to copy # %esi the current src location # %edi the current dst location # %ecx will already be a multiple of 4, since the abi requires it # (arguments smaller than 4 bytes are extended to 4 bytes according to # http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/LowLevelABI/130-IA-32_Function_Calling_Conventions/IA32.html#//apple_ref/doc/uid/TP40002492-SW4) # Do not use memcpy, it may not work since we can get arguments in registers memcpy is free to clobber (XMM0-XMM3) movl 0xf0(%ebp),%ecx */ 0x8b, 0x4d, 0xf0, /* leal 0x08(%ebp),%esi */ 0x8d, 0x75, 0x08, /* movl %esp,%edi */ 0x89, 0xe7, /* L_start: cmpl $0,%ecx */ 0x83, 0xf9, 0x00, /* je L_end */ 0x74, 0x0b, /* subl $0x04,%ecx */ 0x83, 0xe9, 0x04, /* movl (%esi,%ecx),%eax */ 0x8b, 0x04, 0x0e, /* movl %eax,(%edi,%ecx) */ 0x89, 0x04, 0x0f, /* jmp L_start */ 0xeb, 0xf0, /* L_end: calll delegate */ 0xe8, delptr [0], delptr [1], delptr [2], delptr [3], /* # epilogue: movl 0xf4(%ebp),%ebx */ 0x8b, 0x5d, 0xf4, /* movl 0xf8(%ebp),%edi */ 0x8b, 0x7d, 0xf8, /* movl 0xfc(%ebp),%esi */ 0x8b, 0x75, 0xfc, /* leave */ 0xc9, /* retl $0x4 */ 0xc2, 0x04, 0x00, /* */ }; Marshal.Copy (thunk, 0, thunk_ptr, thunk.Length); // Console.WriteLine ("Adding marshalling thunk for: {0} {1} ({2} params) new fptr: 0x{3} old fptr: 0x{4} thunk size: {5}", minfo.DeclaringType.FullName, minfo.Name, minfo.GetParameters ().Length, thunk_ptr.ToString ("X"), fptr.ToString ("X"), thunk.Length); fptr = thunk_ptr; return fptr; } internal unsafe static void RegisterMethod (MethodInfo minfo, ExportAttribute ea, Type type, IntPtr handle) { NativeMethodBuilder builder = new NativeMethodBuilder (minfo, type, ea); class_addMethod (minfo.IsStatic ? ((objc_class *) handle)->isa : handle, builder.Selector, GetFunctionPointer (minfo, builder.Delegate), builder.Signature); lock (lock_obj) method_wrappers.Add (builder.Delegate); #if DEBUG Console.WriteLine ("[METHOD] Registering {0}[0x{1:x}|{2}] on {3} -> ({4})", ea.Selector, (int) builder.Selector, builder.Signature, type, minfo); #endif } [DllImport ("libc", SetLastError=true)] extern static int mprotect (IntPtr addr, int len, int prot); [DllImport ("libc", SetLastError=true)] static extern IntPtr mmap (IntPtr start, ulong length, int prot, int flags, int fd, long offset); [DllImport ("/usr/lib/libobjc.dylib")] extern static IntPtr objc_allocateClassPair (IntPtr superclass, string name, IntPtr extraBytes); [DllImport ("/usr/lib/libobjc.dylib")] extern static IntPtr objc_getClass (string name); [DllImport ("/usr/lib/libobjc.dylib")] extern static IntPtr objc_getProtocol (string name); [DllImport ("/usr/lib/libobjc.dylib")] extern static void objc_registerClassPair (IntPtr cls); [DllImport ("/usr/lib/libobjc.dylib")] extern static bool class_addIvar (IntPtr cls, string name, IntPtr size, ushort alignment, string types); [DllImport ("/usr/lib/libobjc.dylib")] internal extern static bool class_addMethod (IntPtr cls, IntPtr name, Delegate imp, string types); [DllImport ("/usr/lib/libobjc.dylib")] internal extern static bool class_addMethod (IntPtr cls, IntPtr name, IntPtr imp, string types); [DllImport ("/usr/lib/libobjc.dylib")] extern static IntPtr class_getName (IntPtr cls); [DllImport ("/usr/lib/libobjc.dylib")] internal extern static IntPtr class_getSuperclass (IntPtr cls); [DllImport ("/usr/lib/libobjc.dylib")] internal extern static IntPtr class_getMethodImplementation (IntPtr cls, IntPtr sel); [DllImport ("/usr/lib/libobjc.dylib")] internal extern static IntPtr class_getInstanceVariable (IntPtr cls, string name); [MonoNativeFunctionWrapper] delegate IntPtr addPropertyDelegate (IntPtr cls, string name, objc_attribute_prop [] attributes, int count); static addPropertyDelegate addProperty; static bool addPropertyInitialized; static IntPtr class_addProperty (IntPtr cls, string name, objc_attribute_prop [] attributes, int count) { if (!addPropertyInitialized) { var handle = Dlfcn.dlopen (Constants.ObjectiveCLibrary, 0); try { var fptr = Dlfcn.dlsym (handle, "class_addProperty"); if (fptr != IntPtr.Zero) addProperty = (addPropertyDelegate) Marshal.GetDelegateForFunctionPointer (fptr, typeof (addPropertyDelegate)); } finally { Dlfcn.dlclose (handle); } addPropertyInitialized = true; } if (addProperty == null) return IntPtr.Zero; return addProperty (cls, name, attributes, count); } [StructLayout (LayoutKind.Sequential, CharSet=CharSet.Ansi)] private struct objc_attribute_prop { [MarshalAs (UnmanagedType.LPStr)] internal string name; [MarshalAs (UnmanagedType.LPStr)] internal string value; } internal struct objc_class { internal IntPtr isa; } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudioTools.Project { #region structures [StructLayoutAttribute(LayoutKind.Sequential)] internal struct _DROPFILES { public Int32 pFiles; public Int32 X; public Int32 Y; public Int32 fNC; public Int32 fWide; } #endregion #region enums /// <summary> /// Defines the currect state of a property page. /// </summary> [Flags] public enum PropPageStatus { Dirty = 0x1, Validate = 0x2, Clean = 0x4 } /// <summary> /// Defines the status of the command being queried /// </summary> [Flags] public enum QueryStatusResult { /// <summary> /// The command is not supported. /// </summary> NOTSUPPORTED = 0, /// <summary> /// The command is supported /// </summary> SUPPORTED = 1, /// <summary> /// The command is enabled /// </summary> ENABLED = 2, /// <summary> /// The command is toggled on /// </summary> LATCHED = 4, /// <summary> /// The command is toggled off (the opposite of LATCHED). /// </summary> NINCHED = 8, /// <summary> /// The command is invisible. /// </summary> INVISIBLE = 16 } /// <summary> /// Defines the type of item to be added to the hierarchy. /// </summary> public enum HierarchyAddType { AddNewItem, AddExistingItem } /// <summary> /// Defines the component from which a command was issued. /// </summary> public enum CommandOrigin { UiHierarchy, OleCommandTarget } /// <summary> /// Defines the current status of the build process. /// </summary> public enum MSBuildResult { /// <summary> /// The build is currently suspended. /// </summary> Suspended, /// <summary> /// The build has been restarted. /// </summary> Resumed, /// <summary> /// The build failed. /// </summary> Failed, /// <summary> /// The build was successful. /// </summary> Successful, } /// <summary> /// Defines the type of action to be taken in showing the window frame. /// </summary> public enum WindowFrameShowAction { DoNotShow, Show, ShowNoActivate, Hide, } /// <summary> /// Defines drop types /// </summary> internal enum DropDataType { None, Shell, VsStg, VsRef } /// <summary> /// Used by the hierarchy node to decide which element to redraw. /// </summary> [Flags] public enum UIHierarchyElement { None = 0, /// <summary> /// This will be translated to VSHPROPID_IconIndex /// </summary> Icon = 1, /// <summary> /// This will be translated to VSHPROPID_StateIconIndex /// </summary> SccState = 2, /// <summary> /// This will be translated to VSHPROPID_Caption /// </summary> Caption = 4, /// <summary> /// This will be translated to VSHPROPID_OverlayIconIndex /// </summary> OverlayIcon = 8 } /// <summary> /// Defines the global propeties used by the msbuild project. /// </summary> public enum GlobalProperty { /// <summary> /// Property specifying that we are building inside VS. /// </summary> BuildingInsideVisualStudio, /// <summary> /// The VS installation directory. This is the same as the $(DevEnvDir) macro. /// </summary> DevEnvDir, /// <summary> /// The name of the solution the project is created. This is the same as the $(SolutionName) macro. /// </summary> SolutionName, /// <summary> /// The file name of the solution. This is the same as $(SolutionFileName) macro. /// </summary> SolutionFileName, /// <summary> /// The full path of the solution. This is the same as the $(SolutionPath) macro. /// </summary> SolutionPath, /// <summary> /// The directory of the solution. This is the same as the $(SolutionDir) macro. /// </summary> SolutionDir, /// <summary> /// The extension of teh directory. This is the same as the $(SolutionExt) macro. /// </summary> SolutionExt, /// <summary> /// The fxcop installation directory. /// </summary> FxCopDir, /// <summary> /// The ResolvedNonMSBuildProjectOutputs msbuild property /// </summary> VSIDEResolvedNonMSBuildProjectOutputs, /// <summary> /// The Configuartion property. /// </summary> Configuration, /// <summary> /// The platform property. /// </summary> Platform, /// <summary> /// The RunCodeAnalysisOnce property /// </summary> RunCodeAnalysisOnce, /// <summary> /// The VisualStudioStyleErrors property /// </summary> VisualStudioStyleErrors, } #endregion public class AfterProjectFileOpenedEventArgs : EventArgs { } public class BeforeProjectFileClosedEventArgs : EventArgs { #region fields private bool _removed; private IVsHierarchy _hierarchy; #endregion #region properties /// <summary> /// true if the project was removed from the solution before the solution was closed. false if the project was removed from the solution while the solution was being closed. /// </summary> internal bool Removed { get { return _removed; } } internal IVsHierarchy Hierarchy { get { return _hierarchy; } } #endregion #region ctor internal BeforeProjectFileClosedEventArgs(IVsHierarchy hierarchy, bool removed) { this._removed = removed; _hierarchy = hierarchy; } #endregion } /// <summary> /// Argument of the event raised when a project property is changed. /// </summary> public class ProjectPropertyChangedArgs : EventArgs { private string propertyName; private string oldValue; private string newValue; internal ProjectPropertyChangedArgs(string propertyName, string oldValue, string newValue) { this.propertyName = propertyName; this.oldValue = oldValue; this.newValue = newValue; } public string NewValue { get { return newValue; } } public string OldValue { get { return oldValue; } } public string PropertyName { get { return propertyName; } } } /// <summary> /// This class is used for the events raised by a HierarchyNode object. /// </summary> internal class HierarchyNodeEventArgs : EventArgs { private HierarchyNode child; internal HierarchyNodeEventArgs(HierarchyNode child) { this.child = child; } public HierarchyNode Child { get { return this.child; } } } /// <summary> /// Event args class for triggering file change event arguments. /// </summary> public class FileChangedOnDiskEventArgs : EventArgs { #region Private fields /// <summary> /// File name that was changed on disk. /// </summary> private string fileName; /// <summary> /// The item ide of the file that has changed. /// </summary> private uint itemID; /// <summary> /// The reason the file has changed on disk. /// </summary> private _VSFILECHANGEFLAGS fileChangeFlag; #endregion /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">File name that was changed on disk.</param> /// <param name="id">The item id of the file that was changed on disk.</param> internal FileChangedOnDiskEventArgs(string fileName, uint id, _VSFILECHANGEFLAGS flag) { this.fileName = fileName; this.itemID = id; this.fileChangeFlag = flag; } /// <summary> /// Gets the file name that was changed on disk. /// </summary> /// <value>The file that was changed on disk.</value> public string FileName { get { return this.fileName; } } /// <summary> /// Gets item id of the file that has changed /// </summary> /// <value>The file that was changed on disk.</value> internal uint ItemID { get { return this.itemID; } } /// <summary> /// The reason while the file has chnaged on disk. /// </summary> /// <value>The reason while the file has chnaged on disk.</value> public _VSFILECHANGEFLAGS FileChangeFlag { get { return this.fileChangeFlag; } } } }
#region License // // NodeReader.cs July 2006 // // Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net> // // 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 #region Using directives using System.Text; using System; #endregion namespace SimpleFramework.Xml.Stream { /// <summary> /// The <c>NodeReader</c> object is used to read elements from /// the specified XML event reader. This reads input node objects /// that represent elements within the source XML document. This will /// allow details to be read using input node objects, as long as /// the end elements for those input nodes have not been ended. /// <p> /// For example, if an input node represented the root element of a /// document then that input node could read all elements within the /// document. However, if the input node represented a child element /// then it would only be able to read its children. /// </summary> class NodeReader { /// <summary> /// Represents the XML event reader used to read all elements. /// </summary> private readonly EventReader reader; /// <summary> /// This stack enables the reader to keep track of elements. /// </summary> private readonly InputStack stack; /// <summary> /// Constructor for the <c>NodeReader</c> object. This is used /// to read XML events a input node objects from the event reader. /// </summary> /// <param name="reader"> /// This is the event reader for the XML document. /// </param> public NodeReader(EventReader reader) { this.stack = new InputStack(); this.reader = reader; } /// <summary> /// Returns the root input node for the document. This is returned /// only if no other elements have been read. Once the root element /// has been read from the event reader this will return null. /// </summary> /// <returns> /// This returns the root input node for the document. /// </returns> public InputNode ReadRoot() { if(stack.IsEmpty()) { return ReadElement(null); } return null; } /// <summary> /// This method is used to determine if this node is the root /// node for the XML document. The root node is the first node /// in the document and has no sibling nodes. This is false /// if the node has a parent node or a sibling node. /// </summary> /// <returns> /// True if this is the root node within the document. /// </returns> public bool IsRoot(InputNode node) { return stack.Bottom() == node; } /// <summary> /// Returns the next input node from the XML document, if it is a /// child element of the specified input node. This essentially /// determines whether the end tag has been read for the specified /// node, if so then null is returned. If however the specified /// node has not had its end tag read then this returns the next /// element, if that element is a child of the that node. /// </summary> /// <param name="from"> /// This is the input node to read with. /// </param> /// <returns> /// This returns the next input node from the document. /// </returns> public InputNode ReadElement(InputNode from) { if(!stack.IsRelevant(from)) { return null; } EventNode node = reader.Next(); while(node != null) { if(node.IsEnd()) { if(stack.Pop() == from) { return null; } } else if(node.IsStart()) { return ReadStart(from, node); } node = reader.Next(); } return null; } /// <summary> /// Returns the next input node from the XML document, if it is a /// child element of the specified input node. This essentially /// the same as the <c>ReadElement(InputNode)</c> object /// except that this will not read the element if it does not have /// the name specified. This essentially acts as a peak function. /// </summary> /// <param name="from"> /// This is the input node to read with. /// </param> /// <param name="name"> /// This is the name expected from the next element. /// </param> /// <returns> /// This returns the next input node from the document. /// </returns> public InputNode ReadElement(InputNode from, String name) { if(!stack.IsRelevant(from)) { return null; } EventNode node = reader.Peek(); while(node != null) { if(node.IsEnd()) { if(stack.Top() == from) { return null; } else { stack.Pop(); } } else if(node.IsStart()) { if(IsName(node, name)) { return ReadElement(from); } break; } node = reader.Next(); node = reader.Peek(); } return null; } /// <summary> /// This is used to convert the start element to an input node. /// This will push the created input node on to the stack. The /// input node created contains a reference to this reader. so /// that it can be used to read child elements and values. /// </summary> /// <param name="from"> /// This is the parent element for the start event. /// </param> /// <param name="event"> /// This is the start element to be wrapped. /// </param> /// <returns> /// This returns an input node for the given element. /// </returns> public InputNode ReadStart(InputNode from, EventNode node) { InputElement input = new InputElement(from, this, node); if(node.IsStart()) { return stack.Push(input); } return input; } /// <summary> /// This is used to determine the name of the node specified. The /// name of the node is determined to be the name of the element /// if that element is converts to a valid StAX start element. /// </summary> /// <param name="node"> /// This is the StAX node to acquire the name from. /// </param> /// <param name="name"> /// This is the name of the node to check against. /// </param> /// <returns> /// True if the specified node has the given local name. /// </returns> public bool IsName(EventNode node, String name) { String local = node.Name; if(local == null) { return false; } return local.Equals(name); } /// <summary> /// Read the contents of the characters between the specified XML /// element tags, if the read is currently at that element. This /// allows characters associated with the element to be used. If /// the specified node is not the current node, null is returned. /// </summary> /// <param name="from"> /// This is the input node to read the value from. /// </param> /// <returns> /// This returns the characters from the specified node. /// </returns> public String ReadValue(InputNode from) { StringBuilder value = new StringBuilder(); while(stack.Top() == from) { EventNode node = reader.Peek(); if(!node.IsText()) { if(value.Length == 0) { return null; } return value.ToString(); } String data = node.Value; value.Append(data); reader.Next(); } return null; } /// <summary> /// This is used to determine if this input node is empty. An /// empty node is one with no attributes or children. This can /// be used to determine if a given node represents an empty /// entity, with which no extra data can be extracted. /// </summary> /// <param name="from"> /// This is the input node to read the value from. /// </param> /// <returns> /// This returns true if the node is an empty element. /// </returns> public bool IsEmpty(InputNode from) { if(stack.Top() == from) { EventNode node = reader.Peek(); if(node.IsEnd()) { return true; } } return false; } /// <summary> /// This method is used to skip an element within the XML document. /// This will simply read each element from the document until /// the specified element is at the top of the stack. When the /// specified element is at the top of the stack this returns. /// </summary> /// <param name="from"> /// this is the element to skip from the XML document /// </param> public void SkipElement(InputNode from) { while(ReadElement(from) != null); } } }
// 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.PrivateUri.Tests { public static class UriTests { public static IEnumerable<object[]> Uri_TestData { get { if (PlatformDetection.IsWindows) { yield return new object[] { @"file:///path1\path2/path3\path4", @"/path1/path2/path3/path4", @"/path1/path2/path3/path4", @"file:///path1/path2/path3/path4", "" }; yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1/path2/path3", @"/path1/path2/path3", @"file:///path1/path2/path3", ""}; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", @"/path1/path2/path3/path4/", @"\\localhost\path1\path2\path3\path4\", @"file://localhost/path1/path2/path3/path4/", "localhost"}; yield return new object[] { @"file://randomhost/path1%5Cpath2\path3", @"/path1/path2/path3", @"\\randomhost\path1\path2\path3", @"file://randomhost/path1/path2/path3", "randomhost"}; } else { yield return new object[] { @"file:///path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", @"/path1\path2/path3\path4", @"file:///path1%5Cpath2/path3%5Cpath4", "" }; yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", @"/path1\path2\path3", @"file:///path1%5Cpath2%5Cpath3", ""}; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", @"\\localhost\path1\path2\path3\path4\", @"file://localhost/path1%5Cpath2/path3%5Cpath4%5C", "localhost"}; yield return new object[] { @"file://randomhost/path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", @"\\randomhost\path1\path2\path3", @"file://randomhost/path1%5Cpath2%5Cpath3", "randomhost"}; } } } [Theory] [MemberData(nameof(Uri_TestData))] public static void TestCtor_BackwardSlashInPath(string uri, string expectedAbsolutePath, string expectedLocalPath, string expectedAbsoluteUri, string expectedHost) { Uri actualUri = new Uri(uri); Assert.Equal(expectedAbsolutePath, actualUri.AbsolutePath); Assert.Equal(expectedLocalPath, actualUri.LocalPath); Assert.Equal(expectedAbsoluteUri, actualUri.AbsoluteUri); Assert.Equal(expectedHost, actualUri.Host); } [Fact] public static void TestCtor_String() { Uri uri = new Uri(@"http://foo/bar/baz#frag"); int i; String s; bool b; UriHostNameType uriHostNameType; String[] ss; s = uri.ToString(); Assert.Equal(s, @"http://foo/bar/baz#frag"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/bar/baz"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://foo/bar/baz#frag"); s = uri.Authority; Assert.Equal<String>(s, @"foo"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"foo"); s = uri.Fragment; Assert.Equal<String>(s, @"#frag"); s = uri.Host; Assert.Equal<String>(s, @"foo"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/bar/baz"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://foo/bar/baz#frag"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/bar/baz"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @""); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"bar/"); Assert.Equal<String>(ss[2], @"baz"); b = uri.UserEscaped; Assert.False(b); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [Fact] public static void TestCtor_Uri_String() { Uri uri; uri = new Uri(@"http://www.contoso.com/"); uri = new Uri(uri, "catalog/shownew.htm?date=today"); int i; String s; bool b; UriHostNameType uriHostNameType; String[] ss; s = uri.ToString(); Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.Authority; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.Fragment; Assert.Equal<String>(s, @""); s = uri.Host; Assert.Equal<String>(s, @"www.contoso.com"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @"?date=today"); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"catalog/"); Assert.Equal<String>(ss[2], @"shownew.htm"); b = uri.UserEscaped; Assert.False(b); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [Fact] public static void TestCtor_String_UriKind() { Uri uri = new Uri("catalog/shownew.htm?date=today", UriKind.Relative); String s; bool b; s = uri.ToString(); Assert.Equal(s, @"catalog/shownew.htm?date=today"); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsolutePath; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsoluteUri; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Authority; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.DnsSafeHost; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Fragment; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Host; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.HostNameType; }); Assert.False(uri.IsAbsoluteUri); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsDefaultPort; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsFile; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsLoopback; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsUnc; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.LocalPath; }); s = uri.OriginalString; Assert.Equal<String>(s, @"catalog/shownew.htm?date=today"); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.PathAndQuery; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Port; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Query; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Scheme; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Segments; }); b = uri.UserEscaped; Assert.False(b); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.UserInfo; }); } [Fact] public static void TestCtor_Uri_Uri() { Uri absoluteUri = new Uri("http://www.contoso.com/"); // Create a relative Uri from a string. allowRelative = true to allow for // creating a relative Uri. Uri relativeUri = new Uri("/catalog/shownew.htm?date=today", UriKind.Relative); // Create a new Uri from an absolute Uri and a relative Uri. Uri uri = new Uri(absoluteUri, relativeUri); int i; String s; bool b; UriHostNameType uriHostNameType; String[] ss; s = uri.ToString(); Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.Authority; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.Fragment; Assert.Equal<String>(s, @""); s = uri.Host; Assert.Equal<String>(s, @"www.contoso.com"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @"?date=today"); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"catalog/"); Assert.Equal<String>(ss[2], @"shownew.htm"); b = uri.UserEscaped; Assert.False(b); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [Fact] public static void TestTryCreate_String_UriKind() { Uri uri; bool b = Uri.TryCreate("http://www.contoso.com/catalog/shownew.htm?date=today", UriKind.Absolute, out uri); Assert.True(b); int i; String s; UriHostNameType uriHostNameType; String[] ss; s = uri.ToString(); Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.Authority; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.Fragment; Assert.Equal<String>(s, @""); s = uri.Host; Assert.Equal<String>(s, @"www.contoso.com"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @"?date=today"); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"catalog/"); Assert.Equal<String>(ss[2], @"shownew.htm"); b = uri.UserEscaped; Assert.False(b); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [Fact] public static void TestTryCreate_Uri_String() { Uri uri; Uri baseUri = new Uri("http://www.contoso.com/", UriKind.Absolute); bool b = Uri.TryCreate(baseUri, "catalog/shownew.htm?date=today", out uri); Assert.True(b); int i; String s; UriHostNameType uriHostNameType; String[] ss; s = uri.ToString(); Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.Authority; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.Fragment; Assert.Equal<String>(s, @""); s = uri.Host; Assert.Equal<String>(s, @"www.contoso.com"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @"?date=today"); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"catalog/"); Assert.Equal<String>(ss[2], @"shownew.htm"); b = uri.UserEscaped; Assert.False(b); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [Fact] public static void TestTryCreate_Uri_Uri() { Uri uri; Uri baseUri = new Uri("http://www.contoso.com/", UriKind.Absolute); Uri relativeUri = new Uri("catalog/shownew.htm?date=today", UriKind.Relative); bool b = Uri.TryCreate(baseUri, relativeUri, out uri); Assert.True(b); int i; String s; UriHostNameType uriHostNameType; String[] ss; s = uri.ToString(); Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.AbsolutePath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.AbsoluteUri; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.Authority; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.DnsSafeHost; Assert.Equal<String>(s, @"www.contoso.com"); s = uri.Fragment; Assert.Equal<String>(s, @""); s = uri.Host; Assert.Equal<String>(s, @"www.contoso.com"); uriHostNameType = uri.HostNameType; Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns); b = uri.IsAbsoluteUri; Assert.True(b); b = uri.IsDefaultPort; Assert.True(b); b = uri.IsFile; Assert.False(b); b = uri.IsLoopback; Assert.False(b); b = uri.IsUnc; Assert.False(b); s = uri.LocalPath; Assert.Equal<String>(s, @"/catalog/shownew.htm"); s = uri.OriginalString; Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today"); s = uri.PathAndQuery; Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today"); i = uri.Port; Assert.Equal<int>(i, 80); s = uri.Query; Assert.Equal<String>(s, @"?date=today"); s = uri.Scheme; Assert.Equal<String>(s, @"http"); ss = uri.Segments; Assert.Equal<int>(ss.Length, 3); Assert.Equal<String>(ss[0], @"/"); Assert.Equal<String>(ss[1], @"catalog/"); Assert.Equal<String>(ss[2], @"shownew.htm"); b = uri.UserEscaped; Assert.False(b); s = uri.UserInfo; Assert.Equal<String>(s, @""); } [Fact] public static void TestMakeRelative() { // Create a base Uri. Uri address1 = new Uri("http://www.contoso.com/"); // Create a new Uri from a string. Uri address2 = new Uri("http://www.contoso.com/index.htm?date=today"); // Determine the relative Uri. Uri uri = address1.MakeRelativeUri(address2); String s; bool b; s = uri.ToString(); Assert.Equal(s, @"index.htm?date=today"); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsolutePath; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsoluteUri; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Authority; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.DnsSafeHost; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Fragment; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Host; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.HostNameType; }); b = uri.IsAbsoluteUri; Assert.False(b); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsDefaultPort; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsFile; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsLoopback; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsUnc; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.LocalPath; }); s = uri.OriginalString; Assert.Equal<String>(s, @"index.htm?date=today"); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.PathAndQuery; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Port; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Query; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Scheme; }); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Segments; }); b = uri.UserEscaped; Assert.False(b); Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.UserInfo; }); } [Fact] public static void TestCheckHostName() { UriHostNameType u; u = Uri.CheckHostName("www.contoso.com"); Assert.Equal(u, UriHostNameType.Dns); u = Uri.CheckHostName("1.2.3.4"); Assert.Equal(u, UriHostNameType.IPv4); u = Uri.CheckHostName(null); Assert.Equal(u, UriHostNameType.Unknown); u = Uri.CheckHostName("!@*(@#&*#$&*#"); Assert.Equal(u, UriHostNameType.Unknown); } [Fact] public static void TestCheckSchemeName() { bool b; b = Uri.CheckSchemeName("http"); Assert.True(b); b = Uri.CheckSchemeName(null); Assert.False(b); b = Uri.CheckSchemeName("!"); Assert.False(b); } [Fact] public static void TestIsBaseOf() { bool b; Uri uri, uri2; uri = new Uri("http://host/path/path/file?query"); uri2 = new Uri(@"http://host/path/path/file/"); b = uri.IsBaseOf(uri2); Assert.True(b); uri2 = new Uri(@"http://host/path/path/#fragment"); b = uri.IsBaseOf(uri2); Assert.True(b); uri2 = new Uri("http://host/path/path/MoreDir/\""); b = uri.IsBaseOf(uri2); Assert.True(b); uri2 = new Uri(@"http://host/path/path/OtherFile?Query"); b = uri.IsBaseOf(uri2); Assert.True(b); uri2 = new Uri(@"http://host/path/path/"); b = uri.IsBaseOf(uri2); Assert.True(b); uri2 = new Uri(@"http://host/path/path/file"); b = uri.IsBaseOf(uri2); Assert.True(b); uri2 = new Uri(@"http://host/path/path"); b = uri.IsBaseOf(uri2); Assert.False(b); uri2 = new Uri(@"http://host/path/path?query"); b = uri.IsBaseOf(uri2); Assert.False(b); uri2 = new Uri(@"http://host/path/path#Fragment"); b = uri.IsBaseOf(uri2); Assert.False(b); uri2 = new Uri(@"http://host/path/path2/"); b = uri.IsBaseOf(uri2); Assert.False(b); uri2 = new Uri(@"http://host/path/path2/MoreDir"); b = uri.IsBaseOf(uri2); Assert.False(b); uri2 = new Uri(@"http://host/path/File"); b = uri.IsBaseOf(uri2); Assert.False(b); } [Fact] public static void TestIsWellFormedOriginalString() { Uri uri; bool b; uri = new Uri("http://www.contoso.com/path?name"); b = uri.IsWellFormedOriginalString(); Assert.True(b); uri = new Uri("http://www.contoso.com/path???/file name"); b = uri.IsWellFormedOriginalString(); Assert.False(b); uri = new Uri(@"c:\\directory\filename"); b = uri.IsWellFormedOriginalString(); Assert.False(b); uri = new Uri(@"file://c:/directory/filename"); b = uri.IsWellFormedOriginalString(); Assert.False(b); uri = new Uri(@"http:\\host/path/file"); b = uri.IsWellFormedOriginalString(); Assert.False(b); } [Fact] public static void TestIsWellFormedUriString() { bool b; b = Uri.IsWellFormedUriString("http://www.contoso.com/path?name", UriKind.RelativeOrAbsolute); Assert.True(b); b = Uri.IsWellFormedUriString("http://www.contoso.com/path???/file name", UriKind.RelativeOrAbsolute); Assert.False(b); b = Uri.IsWellFormedUriString(@"c:\\directory\filename", UriKind.RelativeOrAbsolute); Assert.False(b); b = Uri.IsWellFormedUriString(@"file://c:/directory/filename", UriKind.RelativeOrAbsolute); Assert.False(b); b = Uri.IsWellFormedUriString(@"http:\\host/path/file", UriKind.RelativeOrAbsolute); Assert.False(b); } [Fact] public static void TestCompare() { Uri uri1 = new Uri("http://www.contoso.com/path?name#frag"); Uri uri2 = new Uri("http://www.contosooo.com/path?name#slag"); Uri uri2a = new Uri("http://www.contosooo.com/path?name#slag"); int i; i = Uri.Compare(uri1, uri2, UriComponents.AbsoluteUri, UriFormat.UriEscaped, StringComparison.CurrentCulture); Assert.Equal(i, -1); i = Uri.Compare(uri1, uri2, UriComponents.Query, UriFormat.UriEscaped, StringComparison.CurrentCulture); Assert.Equal(i, 0); i = Uri.Compare(uri1, uri2, UriComponents.Query | UriComponents.Fragment, UriFormat.UriEscaped, StringComparison.CurrentCulture); Assert.Equal(i, -1); bool b; b = uri1.Equals(uri2); Assert.False(b); b = uri1 == uri2; Assert.False(b); b = uri1 != uri2; Assert.True(b); b = uri2.Equals(uri2a); Assert.True(b); b = uri2 == uri2a; Assert.True(b); b = uri2 != uri2a; Assert.False(b); int h2 = uri2.GetHashCode(); int h2a = uri2a.GetHashCode(); Assert.Equal(h2, h2a); } [Fact] public static void TestEscapeDataString() { String s; s = Uri.EscapeDataString("Hello"); Assert.Equal(s, "Hello"); s = Uri.EscapeDataString(@"He\l/lo"); Assert.Equal(s, "He%5Cl%2Flo"); } [Fact] public static void TestUnescapeDataString() { String s; s = Uri.UnescapeDataString("Hello"); Assert.Equal(s, "Hello"); s = Uri.UnescapeDataString("He%5Cl%2Flo"); Assert.Equal(s, @"He\l/lo"); } [Fact] public static void TestEscapeUriString() { String s; s = Uri.EscapeUriString("Hello"); Assert.Equal(s, "Hello"); s = Uri.EscapeUriString(@"He\l/lo"); Assert.Equal(s, @"He%5Cl/lo"); } [Fact] public static void TestGetComponentParts() { Uri uri = new Uri("http://www.contoso.com/path?name#frag"); String s; s = uri.GetComponents(UriComponents.Fragment, UriFormat.UriEscaped); Assert.Equal(s, "frag"); s = uri.GetComponents(UriComponents.Host, UriFormat.UriEscaped); Assert.Equal(s, "www.contoso.com"); } } }
// Copyright(c) 2016, Michal Skalsky // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using UnityEngine; using System.Collections; using UnityEngine.Rendering; using System; using System.Text; [RequireComponent(typeof(Camera))] public class AtmosphericScattering : MonoBehaviour { public enum RenderMode { Reference, Optimized } public enum LightShaftsQuality { High, Medium } public RenderMode RenderingMode = RenderMode.Optimized; public LightShaftsQuality LightShaftQuality = LightShaftsQuality.Medium; public ComputeShader ScatteringComputeShader; public Light Sun; private RenderTexture _particleDensityLUT = null; private Texture2D _randomVectorsLUT = null; private RenderTexture _lightColorTexture; private Texture2D _lightColorTextureTemp; private Vector3 _skyboxLUTSize = new Vector3(32, 128, 32); private RenderTexture _skyboxLUT; private RenderTexture _skyboxLUT2; private Vector3 _inscatteringLUTSize = new Vector3(8, 8, 64); private RenderTexture _inscatteringLUT; private RenderTexture _extinctionLUT; private const int LightLUTSize = 128; [ColorUsage(false, true, 0, 15, 0, 15)] private Color[] _directionalLightLUT; [ColorUsage(false, true, 0, 10, 0, 10)] private Color[] _ambientLightLUT; private Material _material; private Material _lightShaftMaterial; private Camera _camera; private Color _sunColor; private Texture2D _ditheringTexture; private CommandBuffer _lightShaftsCommandBuffer; private CommandBuffer _cascadeShadowCommandBuffer; private ReflectionProbe _reflectionProbe; [Range(1, 64)] public int SampleCount = 16; public float MaxRayLength = 400; [ColorUsage(false, true, 0, 10, 0, 10)] public Color IncomingLight = new Color(4, 4, 4, 4); [Range(0, 10.0f)] public float RayleighScatterCoef = 1; [Range(0, 10.0f)] public float RayleighExtinctionCoef = 1; [Range(0, 10.0f)] public float MieScatterCoef = 1; [Range(0, 10.0f)] public float MieExtinctionCoef = 1; [Range(0.0f, 0.999f)] public float MieG = 0.76f; public float DistanceScale = 1; public bool UpdateLightColor = true; [Range(0.5f, 3.0f)] public float LightColorIntensity = 1.0f; public bool UpdateAmbientColor = true; [Range(0.5f, 3.0f)] public float AmbientColorIntensity = 1.0f; public bool RenderSun = true; public float SunIntensity = 1; public bool RenderLightShafts = false; public bool RenderAtmosphericFog = true; public bool ReflectionProbe = true; public int ReflectionProbeResolution = 128; #if UNITY_EDITOR public bool GeneralSettingsFoldout = true; public bool ScatteringFoldout = true; public bool SunFoldout = false; public bool LightShaftsFoldout = true; public bool AmbientFoldout = false; public bool DirLightFoldout = false; public bool ReflectionProbeFoldout = false; private StringBuilder _stringBuilder = new StringBuilder(); #endif private const float AtmosphereHeight = 80000.0f; private const float PlanetRadius = 6371000.0f; private readonly Vector4 DensityScale = new Vector4(7994.0f, 1200.0f, 0, 0); private readonly Vector4 RayleighSct = new Vector4(5.8f, 13.5f, 33.1f, 0.0f) * 0.000001f; private readonly Vector4 MieSct = new Vector4(2.0f, 2.0f, 2.0f, 0.0f) * 0.00001f; private Vector4[] _FrustumCorners = new Vector4[4]; /// <summary> /// /// </summary> void Start() { Shader shader = Shader.Find("Hidden/AtmosphericScattering"); if (shader == null) throw new Exception("Critical Error: \"Hidden/AtmosphericScattering\" shader is missing. Make sure it is included in \"Always Included Shaders\" in ProjectSettings/Graphics."); _material = new Material(shader); shader = Shader.Find("Hidden/AtmosphericScattering/LightShafts"); if (shader == null) throw new Exception("Critical Error: \"Hidden/AtmosphericScattering/LightShafts\" shader is missing. Make sure it is included in \"Always Included Shaders\" in ProjectSettings/Graphics."); _lightShaftMaterial = new Material(shader); _camera = GetComponent<Camera>(); UpdateMaterialParameters(_material); //if (_particleDensityLUT == null) { InitialzieRandomVectorsLUT(); PrecomputeParticleDensity(); CalculateLightLUTs(); } InitializeInscatteringLUT(); GenerateDitherTexture(); if (RenderLightShafts) { InitializeLightShafts(); EnableLightShafts(); } if (ReflectionProbe) InitializeReflectionProbe(); } /// <summary> /// /// </summary> public bool IsInitialized() { return _material == null ? false : true; } /// <summary> /// /// </summary> public void EnableLightShafts() { if (_lightShaftsCommandBuffer == null) InitializeLightShafts(); Sun.RemoveCommandBuffer(LightEvent.AfterShadowMap, _cascadeShadowCommandBuffer); Sun.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _lightShaftsCommandBuffer); Sun.AddCommandBuffer(LightEvent.AfterShadowMap, _cascadeShadowCommandBuffer); Sun.AddCommandBuffer(LightEvent.BeforeScreenspaceMask, _lightShaftsCommandBuffer); } /// <summary> /// /// </summary> public void DisableLightShafts() { Sun.RemoveCommandBuffer(LightEvent.AfterShadowMap, _cascadeShadowCommandBuffer); Sun.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _lightShaftsCommandBuffer); } /// <summary> /// /// </summary> public void EnableReflectionProbe() { if (_reflectionProbe == null) InitializeReflectionProbe(); _reflectionProbe.gameObject.SetActive(true); } /// <summary> /// /// </summary> public void DisableReflectionProbe() { if (_reflectionProbe != null) _reflectionProbe.gameObject.SetActive(false); } /// <summary> /// /// </summary> public void ChangeReflectionProbeResolution() { if (_reflectionProbe != null) _reflectionProbe.resolution = ReflectionProbeResolution; } #if UNITY_EDITOR /// <summary> /// /// </summary> public string Validate() { _stringBuilder.Length = 0; if (RenderSettings.skybox == null) _stringBuilder.AppendLine("! RenderSettings.skybox is null"); else if (RenderSettings.skybox.shader.name != "Skybox/AtmosphericScattering") _stringBuilder.AppendLine("! RenderSettings.skybox material is using wrong shader"); if (ScatteringComputeShader == null) _stringBuilder.AppendLine("! Atmospheric Scattering compute shader is missing (General Settings)"); if (Sun == null) _stringBuilder.AppendLine("! Sun (main directional light) isn't set (General Settings)"); else if (RenderLightShafts && Sun.shadows == LightShadows.None) _stringBuilder.AppendLine("! Light shafts are enabled but sun light doesn't cast shadows"); if (RenderLightShafts == true && RenderAtmosphericFog == false) _stringBuilder.AppendLine("! Light shafts are enabled but atm. fog isn't"); return _stringBuilder.ToString(); } #endif /// <summary> /// /// </summary> private void InitializeReflectionProbe() { if (_reflectionProbe != null) return; GameObject go = new GameObject("ReflectionProbe"); go.transform.parent = _camera.transform; go.transform.position = new Vector3(0, 0, 0); _reflectionProbe = go.AddComponent<ReflectionProbe>(); _reflectionProbe.clearFlags = ReflectionProbeClearFlags.Skybox; _reflectionProbe.cullingMask = 0; _reflectionProbe.hdr = true; _reflectionProbe.mode = ReflectionProbeMode.Realtime; _reflectionProbe.refreshMode = ReflectionProbeRefreshMode.EveryFrame; _reflectionProbe.timeSlicingMode = ReflectionProbeTimeSlicingMode.IndividualFaces; _reflectionProbe.resolution = 128; _reflectionProbe.size = new Vector3(100000, 100000, 100000); } /// <summary> /// /// </summary> public void InitializeLightShafts() { if (_cascadeShadowCommandBuffer == null) { _cascadeShadowCommandBuffer = new CommandBuffer(); _cascadeShadowCommandBuffer.name = "CascadeShadowCommandBuffer"; _cascadeShadowCommandBuffer.SetGlobalTexture("_CascadeShadowMapTexture", new UnityEngine.Rendering.RenderTargetIdentifier(UnityEngine.Rendering.BuiltinRenderTextureType.CurrentActive)); } if (_lightShaftsCommandBuffer == null) { _lightShaftsCommandBuffer = new CommandBuffer(); _lightShaftsCommandBuffer.name = "LightShaftsCommandBuffer"; } else { _lightShaftsCommandBuffer.Clear(); } int lightShaftsRT1 = Shader.PropertyToID("_LightShaft1"); int lightShaftsRT2 = Shader.PropertyToID("_LightShaft2"); int halfDepthBuffer = Shader.PropertyToID("_HalfResDepthBuffer"); int halfShaftsRT1 = Shader.PropertyToID("_HalfResColor"); int halfShaftsRT2 = Shader.PropertyToID("_HalfResColorTemp"); Texture nullTexture = null; if (LightShaftQuality == LightShaftsQuality.High) { _lightShaftsCommandBuffer.GetTemporaryRT(lightShaftsRT1, _camera.pixelWidth, _camera.pixelHeight, 0, FilterMode.Bilinear, RenderTextureFormat.RHalf); _lightShaftsCommandBuffer.Blit(nullTexture, new RenderTargetIdentifier(lightShaftsRT1), _lightShaftMaterial, 10); _lightShaftsCommandBuffer.GetTemporaryRT(lightShaftsRT2, _camera.pixelWidth, _camera.pixelHeight, 0, FilterMode.Bilinear, RenderTextureFormat.RHalf); // horizontal bilateral blur _lightShaftsCommandBuffer.Blit(new RenderTargetIdentifier(lightShaftsRT1), new RenderTargetIdentifier(lightShaftsRT2), _lightShaftMaterial, 0); // vertical bilateral blur _lightShaftsCommandBuffer.Blit(new RenderTargetIdentifier(lightShaftsRT2), new RenderTargetIdentifier(lightShaftsRT1), _lightShaftMaterial, 1); } else if (LightShaftQuality == LightShaftsQuality.Medium) { _lightShaftsCommandBuffer.GetTemporaryRT(lightShaftsRT1, _camera.pixelWidth, _camera.pixelHeight, 0, FilterMode.Bilinear, RenderTextureFormat.RHalf); _lightShaftsCommandBuffer.GetTemporaryRT(halfDepthBuffer, _camera.pixelWidth / 2, _camera.pixelHeight / 2, 0, FilterMode.Point, RenderTextureFormat.RFloat); _lightShaftsCommandBuffer.GetTemporaryRT(halfShaftsRT1, _camera.pixelWidth / 2, _camera.pixelHeight / 2, 0, FilterMode.Bilinear, RenderTextureFormat.RHalf); _lightShaftsCommandBuffer.GetTemporaryRT(halfShaftsRT2, _camera.pixelWidth / 2, _camera.pixelHeight / 2, 0, FilterMode.Bilinear, RenderTextureFormat.RHalf); // down sample depth to half res _lightShaftsCommandBuffer.Blit(nullTexture, new RenderTargetIdentifier(halfDepthBuffer), _lightShaftMaterial, 4); _lightShaftsCommandBuffer.Blit(nullTexture, new RenderTargetIdentifier(halfShaftsRT1), _lightShaftMaterial, 10); // horizontal bilateral blur at full res _lightShaftsCommandBuffer.Blit(new RenderTargetIdentifier(halfShaftsRT1), new RenderTargetIdentifier(halfShaftsRT2), _lightShaftMaterial, 2); // vertical bilateral blur at full res _lightShaftsCommandBuffer.Blit(new RenderTargetIdentifier(halfShaftsRT2), new RenderTargetIdentifier(halfShaftsRT1), _lightShaftMaterial, 3); // upscale to full res _lightShaftsCommandBuffer.Blit(new RenderTargetIdentifier(halfShaftsRT1), new RenderTargetIdentifier(lightShaftsRT1), _lightShaftMaterial, 5); } } /// <summary> /// /// </summary> private void InitializeInscatteringLUT() { _inscatteringLUT = new RenderTexture((int)_inscatteringLUTSize.x, (int)_inscatteringLUTSize.y, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); _inscatteringLUT.volumeDepth = (int)_inscatteringLUTSize.z; _inscatteringLUT.isVolume = true; _inscatteringLUT.enableRandomWrite = true; _inscatteringLUT.name = "InscatteringLUT"; _inscatteringLUT.Create(); _extinctionLUT = new RenderTexture((int)_inscatteringLUTSize.x, (int)_inscatteringLUTSize.y, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); _extinctionLUT.volumeDepth = (int)_inscatteringLUTSize.z; _extinctionLUT.isVolume = true; _extinctionLUT.enableRandomWrite = true; _extinctionLUT.name = "ExtinctionLUT"; _extinctionLUT.Create(); } /// <summary> /// /// </summary> private void PrecomputeSkyboxLUT() { if (_skyboxLUT == null) { _skyboxLUT = new RenderTexture((int)_skyboxLUTSize.x, (int)_skyboxLUTSize.y, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); _skyboxLUT.volumeDepth = (int)_skyboxLUTSize.z; _skyboxLUT.isVolume = true; _skyboxLUT.enableRandomWrite = true; _skyboxLUT.name = "SkyboxLUT"; _skyboxLUT.Create(); } #if HIGH_QUALITY if (_skyboxLUT2 == null) { _skyboxLUT2 = new RenderTexture((int)_skyboxLUTSize.x, (int)_skyboxLUTSize.y, 0, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear); _skyboxLUT2.volumeDepth = (int)_skyboxLUTSize.z; _skyboxLUT2.isVolume = true; _skyboxLUT2.enableRandomWrite = true; _skyboxLUT2.name = "SkyboxLUT2"; _skyboxLUT2.Create(); } #endif int kernel = ScatteringComputeShader.FindKernel("SkyboxLUT"); ScatteringComputeShader.SetTexture(kernel, "_SkyboxLUT", _skyboxLUT); #if HIGH_QUALITY ScatteringComputeShader.SetTexture(kernel, "_SkyboxLUT2", _skyboxLUT2); #endif UpdateCommonComputeShaderParameters(kernel); ScatteringComputeShader.Dispatch(kernel, (int)_skyboxLUTSize.x, (int)_skyboxLUTSize.y, (int)_skyboxLUTSize.z); } /// <summary> /// /// </summary> private void UpdateCommonComputeShaderParameters(int kernel) { ScatteringComputeShader.SetTexture(kernel, "_ParticleDensityLUT", _particleDensityLUT); ScatteringComputeShader.SetFloat("_AtmosphereHeight", AtmosphereHeight); ScatteringComputeShader.SetFloat("_PlanetRadius", PlanetRadius); ScatteringComputeShader.SetVector("_DensityScaleHeight", DensityScale); ScatteringComputeShader.SetVector("_ScatteringR", RayleighSct * RayleighScatterCoef); ScatteringComputeShader.SetVector("_ScatteringM", MieSct * MieScatterCoef); ScatteringComputeShader.SetVector("_ExtinctionR", RayleighSct * RayleighExtinctionCoef); ScatteringComputeShader.SetVector("_ExtinctionM", MieSct * MieExtinctionCoef); ScatteringComputeShader.SetVector("_IncomingLight", IncomingLight); ScatteringComputeShader.SetFloat("_MieG", MieG); } /// <summary> /// /// </summary> private void UpdateInscatteringLUT() { int kernel = ScatteringComputeShader.FindKernel("InscatteringLUT"); ScatteringComputeShader.SetTexture(kernel, "_InscatteringLUT", _inscatteringLUT); ScatteringComputeShader.SetTexture(kernel, "_ExtinctionLUT", _extinctionLUT); ScatteringComputeShader.SetVector("_InscatteringLUTSize", _inscatteringLUTSize); ScatteringComputeShader.SetVector("_BottomLeftCorner", _FrustumCorners[0]); ScatteringComputeShader.SetVector("_TopLeftCorner", _FrustumCorners[1]); ScatteringComputeShader.SetVector("_TopRightCorner", _FrustumCorners[2]); ScatteringComputeShader.SetVector("_BottomRightCorner", _FrustumCorners[3]); ScatteringComputeShader.SetVector("_CameraPos", transform.position); ScatteringComputeShader.SetVector("_LightDir", Sun.transform.forward); ScatteringComputeShader.SetFloat("_DistanceScale", DistanceScale); UpdateCommonComputeShaderParameters(kernel); ScatteringComputeShader.Dispatch(kernel, (int)_inscatteringLUTSize.x, (int)_inscatteringLUTSize.y, 1); } /// <summary> /// /// </summary> public void OnDestroy() { Destroy(_material); Destroy(_lightShaftMaterial); } /// <summary> /// /// </summary> private void UpdateMaterialParameters(Material material) { material.SetFloat("_AtmosphereHeight", AtmosphereHeight); material.SetFloat("_PlanetRadius", PlanetRadius); material.SetVector("_DensityScaleHeight", DensityScale); Vector4 scatteringR = new Vector4(5.8f, 13.5f, 33.1f, 0.0f) * 0.000001f; Vector4 scatteringM = new Vector4(2.0f, 2.0f, 2.0f, 0.0f) * 0.00001f; material.SetVector("_ScatteringR", RayleighSct * RayleighScatterCoef); material.SetVector("_ScatteringM", MieSct * MieScatterCoef); material.SetVector("_ExtinctionR", RayleighSct * RayleighExtinctionCoef); material.SetVector("_ExtinctionM", MieSct * MieExtinctionCoef); material.SetColor("_IncomingLight", IncomingLight); material.SetFloat("_MieG", MieG); material.SetFloat("_DistanceScale", DistanceScale); material.SetColor("_SunColor", _sunColor); //--------------------------------------------------- material.SetVector("_LightDir", new Vector4(Sun.transform.forward.x, Sun.transform.forward.y, Sun.transform.forward.z, 1.0f / (Sun.range * Sun.range))); material.SetVector("_LightColor", Sun.color * Sun.intensity); material.SetTexture("_ParticleDensityLUT", _particleDensityLUT); material.SetTexture("_SkyboxLUT", _skyboxLUT); material.SetTexture("_SkyboxLUT2", _skyboxLUT2); } /// <summary> /// /// </summary> public void CalculateLightLUTs() { if (_lightColorTexture == null) { _lightColorTexture = new RenderTexture(LightLUTSize, 1, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); _lightColorTexture.name = "LightColorTexture"; _lightColorTexture.Create(); } if (_lightColorTextureTemp == null) { _lightColorTextureTemp = new Texture2D(LightLUTSize, 1, TextureFormat.RGBAHalf, false, true); _lightColorTextureTemp.name = "LightColorTextureTemp"; _lightColorTextureTemp.Apply(); } // ambient LUT Texture nullTexture = null; _material.SetTexture("_RandomVectors", _randomVectorsLUT); Graphics.Blit(nullTexture, _lightColorTexture, _material, 1); _lightColorTextureTemp.ReadPixels(new Rect(0, 0, LightLUTSize, 1), 0, 0); _ambientLightLUT = _lightColorTextureTemp.GetPixels(0, 0, LightLUTSize, 1); // directional LUT Graphics.Blit(nullTexture, _lightColorTexture, _material, 2); _lightColorTextureTemp.ReadPixels(new Rect(0, 0, LightLUTSize, 1), 0, 0); _directionalLightLUT = _lightColorTextureTemp.GetPixels(0, 0, LightLUTSize, 1); PrecomputeSkyboxLUT(); } /// <summary> /// /// </summary> private void InitialzieRandomVectorsLUT() { _randomVectorsLUT = new Texture2D(256, 1, TextureFormat.RGBAHalf, false, true); _randomVectorsLUT.name = "RandomVectorsLUT"; Color[] colors = new Color[256]; UnityEngine.Random.seed = 1234567890; for (int i = 0; i < colors.Length; ++i) { Vector3 vector = UnityEngine.Random.onUnitSphere; colors[i] = new Color(vector.x, vector.y, vector.z, 1); } _randomVectorsLUT.SetPixels(colors); _randomVectorsLUT.Apply(); } /// <summary> /// /// </summary> private void PrecomputeParticleDensity() { if (_particleDensityLUT == null) { _particleDensityLUT = new RenderTexture(1024, 1024, 0, RenderTextureFormat.RGFloat, RenderTextureReadWrite.Linear); _particleDensityLUT.name = "ParticleDensityLUT"; _particleDensityLUT.filterMode = FilterMode.Bilinear; _particleDensityLUT.Create(); } Texture nullTexture = null; Graphics.Blit(nullTexture, _particleDensityLUT, _material, 0); _material.SetTexture("_ParticleDensityLUT", _particleDensityLUT); } /// <summary> /// /// </summary> private Color ComputeLightColor() { float cosAngle = Vector3.Dot(Vector3.up, -Sun.transform.forward); float u = (cosAngle + 0.1f) / 1.1f;// * 0.5f + 0.5f; u = u * LightLUTSize; int index0 = Mathf.FloorToInt(u); float weight1 = u - index0; int index1 = index0 + 1; float weight0 = 1 - weight1; index0 = Mathf.Clamp(index0, 0, LightLUTSize - 1); index1 = Mathf.Clamp(index1, 0, LightLUTSize - 1); Color c = _directionalLightLUT[index0] * weight0 + _directionalLightLUT[index1] * weight1; return c.gamma; } /// <summary> /// /// </summary> private void UpdateDirectionalLightColor(Color c) { Vector3 color = new Vector3(c.r, c.g, c.b); float length = color.magnitude; color /= length; Sun.color = new Color(Mathf.Max(color.x, 0.01f), Mathf.Max(color.y, 0.01f), Mathf.Max(color.z, 0.01f), 1); Sun.intensity = Mathf.Max(length, 0.01f) * LightColorIntensity; // make sure unity doesn't disable this light } /// <summary> /// /// </summary> private Color ComputeAmbientColor() { float cosAngle = Vector3.Dot(Vector3.up, -Sun.transform.forward); float u = (cosAngle + 0.1f) / 1.1f;// * 0.5f + 0.5f; u = u * LightLUTSize; int index0 = Mathf.FloorToInt(u); float weight1 = u - index0; int index1 = index0 + 1; float weight0 = 1 - weight1; index0 = Mathf.Clamp(index0, 0, LightLUTSize - 1); index1 = Mathf.Clamp(index1, 0, LightLUTSize - 1); Color c = _ambientLightLUT[index0] * weight0 + _ambientLightLUT[index1] * weight1; return c.gamma; } /// <summary> /// /// </summary> private void UpdateAmbientLightColor(Color c) { #if UNITY_5_4_OR_NEWER RenderSettings.ambientLight = c * AmbientColorIntensity; #else Vector3 color = new Vector3(c.r, c.g, c.b); float length = color.magnitude; color /= length; RenderSettings.ambientLight = new Color(color.x, color.y, color.z, 1); RenderSettings.ambientIntensity = Mathf.Max(length, 0.01f) * AmbientColorIntensity; #endif } /// <summary> /// /// </summary> void Update() { _sunColor = ComputeLightColor(); if (UpdateLightColor) UpdateDirectionalLightColor(_sunColor); if (UpdateAmbientColor) UpdateAmbientLightColor(ComputeAmbientColor()); } /// <summary> /// /// </summary> private void UpdateSkyBoxParameters() { if (RenderSettings.skybox != null) { RenderSettings.skybox.SetVector("_CameraPos", _camera.transform.position); UpdateMaterialParameters(RenderSettings.skybox); if (RenderingMode == RenderMode.Reference) RenderSettings.skybox.EnableKeyword("ATMOSPHERE_REFERENCE"); else RenderSettings.skybox.DisableKeyword("ATMOSPHERE_REFERENCE"); RenderSettings.skybox.SetFloat("_SunIntensity", SunIntensity); if (RenderSun) RenderSettings.skybox.EnableKeyword("RENDER_SUN"); else RenderSettings.skybox.DisableKeyword("RENDER_SUN"); //RenderSettings.skybox.EnableKeyword("HIGH_QUALITY"); } } /// <summary> /// /// </summary> private void UpdateLightShaftsParameters() { #if UNITY_5_4_OR_NEWER _lightShaftMaterial.SetVectorArray("_FrustumCorners", _FrustumCorners); #else _lightShaftMaterial.SetVector("_FrustumCorners0", _FrustumCorners[0]); _lightShaftMaterial.SetVector("_FrustumCorners1", _FrustumCorners[1]); _lightShaftMaterial.SetVector("_FrustumCorners2", _FrustumCorners[2]); _lightShaftMaterial.SetVector("_FrustumCorners3", _FrustumCorners[3]); #endif _lightShaftMaterial.SetInt("_SampleCount", SampleCount); _lightShaftMaterial.SetTexture("_DitherTexture", _ditheringTexture); _lightShaftMaterial.SetVector("_FullResTexelSize", new Vector4(1.0f / _camera.pixelWidth, 1.0f / _camera.pixelHeight, 0, 0)); _lightShaftMaterial.SetVector("_HalfResTexelSize", new Vector4(1.0f / (_camera.pixelWidth * 0.5f), 1.0f / (_camera.pixelHeight * 0.5f), 0, 0)); } /// <summary> /// /// </summary> private void UpdateLightScatteringParameters() { UpdateMaterialParameters(_material); #if UNITY_5_4_OR_NEWER _material.SetVectorArray("_FrustumCorners", _FrustumCorners); #else _material.SetVector("_FrustumCorners0", _FrustumCorners[0]); _material.SetVector("_FrustumCorners1", _FrustumCorners[1]); _material.SetVector("_FrustumCorners2", _FrustumCorners[2]); _material.SetVector("_FrustumCorners3", _FrustumCorners[3]); #endif _material.SetFloat("_SunIntensity", SunIntensity); _material.SetTexture("_InscatteringLUT", _inscatteringLUT); _material.SetTexture("_ExtinctionLUT", _extinctionLUT); if (RenderingMode == RenderMode.Reference) _material.EnableKeyword("ATMOSPHERE_REFERENCE"); else _material.DisableKeyword("ATMOSPHERE_REFERENCE"); if (RenderLightShafts) _material.EnableKeyword("LIGHT_SHAFTS"); else _material.DisableKeyword("LIGHT_SHAFTS"); } /// <summary> /// /// </summary> public void OnPreRender() { // get four corners of camera frustom in world space // bottom left _FrustumCorners[0] = _camera.ViewportToWorldPoint(new Vector3(0, 0, _camera.farClipPlane)); // top left _FrustumCorners[1] = _camera.ViewportToWorldPoint(new Vector3(0, 1, _camera.farClipPlane)); // top right _FrustumCorners[2] = _camera.ViewportToWorldPoint(new Vector3(1, 1, _camera.farClipPlane)); // bottom right _FrustumCorners[3] = _camera.ViewportToWorldPoint(new Vector3(1, 0, _camera.farClipPlane)); // update parameters UpdateSkyBoxParameters(); UpdateLightScatteringParameters(); UpdateLightShaftsParameters(); UpdateInscatteringLUT(); } /// <summary> /// /// </summary> [ImageEffectOpaque] public void OnRenderImage(RenderTexture source, RenderTexture destination) { if (!RenderAtmosphericFog) { Graphics.Blit(source, destination); return; } //Graphics.SetRenderTarget(destination); //_material.SetPass(3); _material.SetTexture("_Background", source); //Graphics.DrawMeshNow(_mesh, Matrix4x4.identity); Texture nullTexture = null; Graphics.Blit(nullTexture, destination, _material, 3); } /// <summary> /// /// </summary> private void GenerateDitherTexture() { if (_ditheringTexture != null) { return; } int size = 8; #if DITHER_4_4 size = 4; #endif // again, I couldn't make it work with Alpha8 _ditheringTexture = new Texture2D(size, size, TextureFormat.Alpha8, false, true); _ditheringTexture.filterMode = FilterMode.Point; Color32[] c = new Color32[size * size]; byte b; #if DITHER_4_4 b = (byte)(0.0f / 16.0f * 255); c[0] = new Color32(b, b, b, b); b = (byte)(8.0f / 16.0f * 255); c[1] = new Color32(b, b, b, b); b = (byte)(2.0f / 16.0f * 255); c[2] = new Color32(b, b, b, b); b = (byte)(10.0f / 16.0f * 255); c[3] = new Color32(b, b, b, b); b = (byte)(12.0f / 16.0f * 255); c[4] = new Color32(b, b, b, b); b = (byte)(4.0f / 16.0f * 255); c[5] = new Color32(b, b, b, b); b = (byte)(14.0f / 16.0f * 255); c[6] = new Color32(b, b, b, b); b = (byte)(6.0f / 16.0f * 255); c[7] = new Color32(b, b, b, b); b = (byte)(3.0f / 16.0f * 255); c[8] = new Color32(b, b, b, b); b = (byte)(11.0f / 16.0f * 255); c[9] = new Color32(b, b, b, b); b = (byte)(1.0f / 16.0f * 255); c[10] = new Color32(b, b, b, b); b = (byte)(9.0f / 16.0f * 255); c[11] = new Color32(b, b, b, b); b = (byte)(15.0f / 16.0f * 255); c[12] = new Color32(b, b, b, b); b = (byte)(7.0f / 16.0f * 255); c[13] = new Color32(b, b, b, b); b = (byte)(13.0f / 16.0f * 255); c[14] = new Color32(b, b, b, b); b = (byte)(5.0f / 16.0f * 255); c[15] = new Color32(b, b, b, b); #else int i = 0; b = (byte)(1.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(49.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(13.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(61.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(4.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(52.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(16.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(64.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(33.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(17.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(45.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(29.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(36.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(20.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(48.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(32.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(9.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(57.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(5.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(53.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(12.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(60.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(8.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(56.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(41.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(25.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(37.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(21.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(44.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(28.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(40.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(24.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(3.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(51.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(15.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(63.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(2.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(50.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(14.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(62.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(35.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(19.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(47.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(31.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(34.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(18.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(46.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(30.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(11.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(59.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(7.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(55.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(10.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(58.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(6.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(54.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(43.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(27.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(39.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(23.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(42.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(26.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(38.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); b = (byte)(22.0f / 65.0f * 255); c[i++] = new Color32(b, b, b, b); #endif _ditheringTexture.SetPixels32(c); _ditheringTexture.Apply(); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] public class tk2dSpriteColliderIsland { public bool connected = true; public Vector2[] points; public bool IsValid() { if (connected) { return points.Length >= 3; } else { return points.Length >= 2; } } public void CopyFrom(tk2dSpriteColliderIsland src) { connected = src.connected; points = new Vector2[src.points.Length]; for (int i = 0; i < points.Length; ++i) points[i] = src.points[i]; } public bool CompareTo(tk2dSpriteColliderIsland src) { if (connected != src.connected) return false; if (points.Length != src.points.Length) return false; for (int i = 0; i < points.Length; ++i) if (points[i] != src.points[i]) return false; return true; } } [System.Serializable] public class tk2dLinkedSpriteCollection { public string name = ""; // name is the same as the find criteria public tk2dSpriteCollection spriteCollection = null; } [System.Serializable] public class tk2dSpriteCollectionDefinition { public enum Anchor { UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight, Custom } public enum Pad { Default, BlackZeroAlpha, Extend, TileXY, TileX, TileY, } public enum ColliderType { UserDefined, // don't try to create or destroy anything ForceNone, // nothing will be created, if something exists, it will be destroyed BoxTrimmed, // box, trimmed to cover visible region BoxCustom, // box, with custom values provided by user Polygon, // polygon, can be concave Advanced, // advanced colliders - set up multiple oriented boxes } public enum PolygonColliderCap { None, FrontAndBack, Front, Back, } public enum ColliderColor { Default, // default unity color scheme Red, White, Black } public enum Source { Sprite, SpriteSheet, Font } public enum DiceFilter { Complete, SolidOnly, TransparentOnly, } [System.Serializable] public class ColliderData { public enum Type { Box, Circle, } public string name = ""; public Type type = Type.Box; public Vector2 origin = Vector3.zero; public Vector2 size = Vector3.zero; public float angle = 0; public void CopyFrom(ColliderData src) { name = src.name; type = src.type; origin = src.origin; size = src.size; angle = src.angle; } public bool CompareTo(ColliderData src) { return (name == src.name && type == src.type && origin == src.origin && size == src.size && angle == src.angle); } } public string name = ""; public bool disableTrimming = false; public bool additive = false; public Vector3 scale = new Vector3(1,1,1); public Texture2D texture = null; [System.NonSerialized] public Texture2D thumbnailTexture; public int materialId = 0; public Anchor anchor = Anchor.MiddleCenter; public float anchorX, anchorY; public Object overrideMesh; public bool doubleSidedSprite = false; public bool customSpriteGeometry = false; public tk2dSpriteColliderIsland[] geometryIslands = new tk2dSpriteColliderIsland[0]; public bool dice = false; public int diceUnitX = 64; public int diceUnitY = 64; public DiceFilter diceFilter = DiceFilter.Complete; public Pad pad = Pad.Default; public int extraPadding = 0; // default public Source source = Source.Sprite; public bool fromSpriteSheet = false; public bool hasSpriteSheetId = false; public int spriteSheetId = 0; public int spriteSheetX = 0, spriteSheetY = 0; public bool extractRegion = false; public int regionX, regionY, regionW, regionH; public int regionId; public ColliderType colliderType = ColliderType.UserDefined; public List<ColliderData> colliderData = new List<ColliderData>(); public Vector2 boxColliderMin, boxColliderMax; public tk2dSpriteColliderIsland[] polyColliderIslands; public PolygonColliderCap polyColliderCap = PolygonColliderCap.FrontAndBack; public bool colliderConvex = false; public bool colliderSmoothSphereCollisions = false; public ColliderColor colliderColor = ColliderColor.Default; public List<tk2dSpriteDefinition.AttachPoint> attachPoints = new List<tk2dSpriteDefinition.AttachPoint>(); public void CopyFrom(tk2dSpriteCollectionDefinition src) { name = src.name; disableTrimming = src.disableTrimming; additive = src.additive; scale = src.scale; texture = src.texture; materialId = src.materialId; anchor = src.anchor; anchorX = src.anchorX; anchorY = src.anchorY; overrideMesh = src.overrideMesh; doubleSidedSprite = src.doubleSidedSprite; customSpriteGeometry = src.customSpriteGeometry; geometryIslands = src.geometryIslands; dice = src.dice; diceUnitX = src.diceUnitX; diceUnitY = src.diceUnitY; diceFilter = src.diceFilter; pad = src.pad; source = src.source; fromSpriteSheet = src.fromSpriteSheet; hasSpriteSheetId = src.hasSpriteSheetId; spriteSheetX = src.spriteSheetX; spriteSheetY = src.spriteSheetY; spriteSheetId = src.spriteSheetId; extractRegion = src.extractRegion; regionX = src.regionX; regionY = src.regionY; regionW = src.regionW; regionH = src.regionH; regionId = src.regionId; colliderType = src.colliderType; boxColliderMin = src.boxColliderMin; boxColliderMax = src.boxColliderMax; polyColliderCap = src.polyColliderCap; colliderColor = src.colliderColor; colliderConvex = src.colliderConvex; colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; extraPadding = src.extraPadding; colliderData = new List<ColliderData>( src.colliderData.Count ); foreach ( ColliderData srcCollider in src.colliderData ) { ColliderData data = new ColliderData(); data.CopyFrom(srcCollider); colliderData.Add(data); } if (src.polyColliderIslands != null) { polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < polyColliderIslands.Length; ++i) { polyColliderIslands[i] = new tk2dSpriteColliderIsland(); polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { polyColliderIslands = new tk2dSpriteColliderIsland[0]; } if (src.geometryIslands != null) { geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length]; for (int i = 0; i < geometryIslands.Length; ++i) { geometryIslands[i] = new tk2dSpriteColliderIsland(); geometryIslands[i].CopyFrom(src.geometryIslands[i]); } } else { geometryIslands = new tk2dSpriteColliderIsland[0]; } attachPoints = new List<tk2dSpriteDefinition.AttachPoint>(src.attachPoints.Count); foreach (tk2dSpriteDefinition.AttachPoint srcAp in src.attachPoints) { tk2dSpriteDefinition.AttachPoint ap = new tk2dSpriteDefinition.AttachPoint(); ap.CopyFrom(srcAp); attachPoints.Add(ap); } } public void Clear() { // Reinitialize var tmpVar = new tk2dSpriteCollectionDefinition(); CopyFrom(tmpVar); } public bool CompareTo(tk2dSpriteCollectionDefinition src) { if (name != src.name) return false; if (additive != src.additive) return false; if (scale != src.scale) return false; if (texture != src.texture) return false; if (materialId != src.materialId) return false; if (anchor != src.anchor) return false; if (anchorX != src.anchorX) return false; if (anchorY != src.anchorY) return false; if (overrideMesh != src.overrideMesh) return false; if (dice != src.dice) return false; if (diceUnitX != src.diceUnitX) return false; if (diceUnitY != src.diceUnitY) return false; if (diceFilter != src.diceFilter) return false; if (pad != src.pad) return false; if (extraPadding != src.extraPadding) return false; if (doubleSidedSprite != src.doubleSidedSprite) return false; if (customSpriteGeometry != src.customSpriteGeometry) return false; if (geometryIslands != src.geometryIslands) return false; if (geometryIslands != null && src.geometryIslands != null) { if (geometryIslands.Length != src.geometryIslands.Length) return false; for (int i = 0; i < geometryIslands.Length; ++i) if (!geometryIslands[i].CompareTo(src.geometryIslands[i])) return false; } if (source != src.source) return false; if (fromSpriteSheet != src.fromSpriteSheet) return false; if (hasSpriteSheetId != src.hasSpriteSheetId) return false; if (spriteSheetId != src.spriteSheetId) return false; if (spriteSheetX != src.spriteSheetX) return false; if (spriteSheetY != src.spriteSheetY) return false; if (extractRegion != src.extractRegion) return false; if (regionX != src.regionX) return false; if (regionY != src.regionY) return false; if (regionW != src.regionW) return false; if (regionH != src.regionH) return false; if (regionId != src.regionId) return false; if (colliderType != src.colliderType) return false; if (boxColliderMin != src.boxColliderMin) return false; if (boxColliderMax != src.boxColliderMax) return false; if (polyColliderIslands != src.polyColliderIslands) return false; if (polyColliderIslands != null && src.polyColliderIslands != null) { if (polyColliderIslands.Length != src.polyColliderIslands.Length) return false; for (int i = 0; i < polyColliderIslands.Length; ++i) if (!polyColliderIslands[i].CompareTo(src.polyColliderIslands[i])) return false; } if (colliderData.Count != src.colliderData.Count) return false; for (int i = 0; i < colliderData.Count; ++i) { if (!colliderData[i].CompareTo( src.colliderData[i] )) return false; } if (polyColliderCap != src.polyColliderCap) return false; if (colliderColor != src.colliderColor) return false; if (colliderSmoothSphereCollisions != src.colliderSmoothSphereCollisions) return false; if (colliderConvex != src.colliderConvex) return false; if (attachPoints.Count != src.attachPoints.Count) return false; for (int i = 0; i < attachPoints.Count; ++i) { if (!attachPoints[i].CompareTo(src.attachPoints[i])) return false; } return true; } } [System.Serializable] public class tk2dSpriteCollectionDefault { public bool additive = false; public Vector3 scale = new Vector3(1,1,1); public tk2dSpriteCollectionDefinition.Anchor anchor = tk2dSpriteCollectionDefinition.Anchor.MiddleCenter; public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default; public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; } [System.Serializable] public class tk2dSpriteSheetSource { public enum Anchor { UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight, } public enum SplitMethod { UniformDivision, } public Texture2D texture; public int tilesX, tilesY; public int numTiles = 0; public Anchor anchor = Anchor.MiddleCenter; public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default; public Vector3 scale = new Vector3(1,1,1); public bool additive = false; // version 1 public bool active = false; public int tileWidth, tileHeight; public int tileMarginX, tileMarginY; public int tileSpacingX, tileSpacingY; public SplitMethod splitMethod = SplitMethod.UniformDivision; public int version = 0; public const int CURRENT_VERSION = 1; public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; public void CopyFrom(tk2dSpriteSheetSource src) { texture = src.texture; tilesX = src.tilesX; tilesY = src.tilesY; numTiles = src.numTiles; anchor = src.anchor; pad = src.pad; scale = src.scale; colliderType = src.colliderType; version = src.version; active = src.active; tileWidth = src.tileWidth; tileHeight = src.tileHeight; tileSpacingX = src.tileSpacingX; tileSpacingY = src.tileSpacingY; tileMarginX = src.tileMarginX; tileMarginY = src.tileMarginY; splitMethod = src.splitMethod; } public bool CompareTo(tk2dSpriteSheetSource src) { if (texture != src.texture) return false; if (tilesX != src.tilesX) return false; if (tilesY != src.tilesY) return false; if (numTiles != src.numTiles) return false; if (anchor != src.anchor) return false; if (pad != src.pad) return false; if (scale != src.scale) return false; if (colliderType != src.colliderType) return false; if (version != src.version) return false; if (active != src.active) return false; if (tileWidth != src.tileWidth) return false; if (tileHeight != src.tileHeight) return false; if (tileSpacingX != src.tileSpacingX) return false; if (tileSpacingY != src.tileSpacingY) return false; if (tileMarginX != src.tileMarginX) return false; if (tileMarginY != src.tileMarginY) return false; if (splitMethod != src.splitMethod) return false; return true; } public string Name { get { return texture != null?texture.name:"New Sprite Sheet"; } } } [System.Serializable] public class tk2dSpriteCollectionFont { public bool active = false; public TextAsset bmFont; public Texture2D texture; public bool dupeCaps = false; // duplicate lowercase into uc, or vice-versa, depending on which exists public bool flipTextureY = false; public int charPadX = 0; public tk2dFontData data; public tk2dFont editorData; public int materialId; public bool useGradient = false; public Texture2D gradientTexture = null; public int gradientCount = 1; public void CopyFrom(tk2dSpriteCollectionFont src) { active = src.active; bmFont = src.bmFont; texture = src.texture; dupeCaps = src.dupeCaps; flipTextureY = src.flipTextureY; charPadX = src.charPadX; data = src.data; editorData = src.editorData; materialId = src.materialId; gradientCount = src.gradientCount; gradientTexture = src.gradientTexture; useGradient = src.useGradient; } public string Name { get { if (bmFont == null || texture == null) return "Empty"; else { if (data == null) return bmFont.name + " (Inactive)"; else return bmFont.name; } } } public bool InUse { get { return active && bmFont != null && texture != null && data != null && editorData != null; } } } [System.Serializable] public class tk2dSpriteCollectionPlatform { public string name = ""; public tk2dSpriteCollection spriteCollection = null; public bool Valid { get { return name.Length > 0 && spriteCollection != null; } } public void CopyFrom(tk2dSpriteCollectionPlatform source) { name = source.name; spriteCollection = source.spriteCollection; } } [AddComponentMenu("2D Toolkit/Backend/tk2dSpriteCollection")] public class tk2dSpriteCollection : MonoBehaviour { public const int CURRENT_VERSION = 4; public enum NormalGenerationMode { None, NormalsOnly, NormalsAndTangents, }; // Deprecated fields [SerializeField] private tk2dSpriteCollectionDefinition[] textures; [SerializeField] private Texture2D[] textureRefs; public Texture2D[] DoNotUse__TextureRefs { get { return textureRefs; } set { textureRefs = value; } } // Don't use this for anything. Except maybe in tk2dSpriteCollectionBuilderDeprecated... // new method public tk2dSpriteSheetSource[] spriteSheets; public tk2dSpriteCollectionFont[] fonts; public tk2dSpriteCollectionDefault defaults; // platforms public List<tk2dSpriteCollectionPlatform> platforms = new List<tk2dSpriteCollectionPlatform>(); public bool managedSpriteCollection = false; // true when generated and managed by system, eg. platform specific data public tk2dSpriteCollection linkParent = null; // is this sprite collection linked to something else? eg. sync'ed diffused and normal sprite collection. This points to the parent public bool HasPlatformData { get { return platforms.Count > 1; } } public bool loadable = false; public AtlasFormat atlasFormat = AtlasFormat.UnityTexture; public int maxTextureSize = 2048; public bool forceTextureSize = false; public int forcedTextureWidth = 2048; public int forcedTextureHeight = 2048; public enum TextureCompression { Uncompressed, Reduced16Bit, Compressed, Dithered16Bit_Alpha, Dithered16Bit_NoAlpha, } public enum AtlasFormat { UnityTexture, // Normal Unity texture Png, } public TextureCompression textureCompression = TextureCompression.Uncompressed; public int atlasWidth, atlasHeight; public bool forceSquareAtlas = false; public float atlasWastage; public bool allowMultipleAtlases = false; public bool removeDuplicates = true; public tk2dSpriteCollectionDefinition[] textureParams; public tk2dSpriteCollectionData spriteCollection; public bool premultipliedAlpha = false; public Material[] altMaterials; public Material[] atlasMaterials; public Texture2D[] atlasTextures; public TextAsset[] atlasTextureFiles = new TextAsset[0]; [SerializeField] private bool useTk2dCamera = false; [SerializeField] private int targetHeight = 640; [SerializeField] private float targetOrthoSize = 10.0f; // New method of storing sprite size public tk2dSpriteCollectionSize sizeDef = tk2dSpriteCollectionSize.Default(); public float globalScale = 1.0f; public float globalTextureRescale = 1.0f; // Remember test data for attach points [System.Serializable] public class AttachPointTestSprite { public string attachPointName = ""; public tk2dSpriteCollectionData spriteCollection = null; public int spriteId = -1; public bool CompareTo(AttachPointTestSprite src) { return src.attachPointName == attachPointName && src.spriteCollection == spriteCollection && src.spriteId == spriteId; } public void CopyFrom(AttachPointTestSprite src) { attachPointName = src.attachPointName; spriteCollection = src.spriteCollection; spriteId = src.spriteId; } } public List<AttachPointTestSprite> attachPointTestSprites = new List<AttachPointTestSprite>(); // Texture settings [SerializeField] private bool pixelPerfectPointSampled = false; // obsolete public FilterMode filterMode = FilterMode.Bilinear; public TextureWrapMode wrapMode = TextureWrapMode.Clamp; public bool userDefinedTextureSettings = false; public bool mipmapEnabled = false; public int anisoLevel = 1; // Starts off with Unity Physics 3D for current platforms public tk2dSpriteDefinition.PhysicsEngine physicsEngine = tk2dSpriteDefinition.PhysicsEngine.Physics3D; public float physicsDepth = 0.1f; public bool disableTrimming = false; public bool disableRotation = false; public NormalGenerationMode normalGenerationMode = NormalGenerationMode.None; public int padAmount = -1; // default public bool autoUpdate = true; public float editorDisplayScale = 1.0f; public int version = 0; public string assetName = ""; // Linked sprite collections public List<tk2dLinkedSpriteCollection> linkedSpriteCollections = new List<tk2dLinkedSpriteCollection>(); // Fix up upgraded data structures public void Upgrade() { if (version == CURRENT_VERSION) return; Debug.Log("SpriteCollection '" + this.name + "' - Upgraded from version " + version.ToString()); if (version == 0) { if (pixelPerfectPointSampled) filterMode = FilterMode.Point; else filterMode = FilterMode.Bilinear; // don't bother messing about with user settings // on old atlases userDefinedTextureSettings = true; } if (version < 3) { if (textureRefs != null && textureParams != null && textureRefs.Length == textureParams.Length) { for (int i = 0; i < textureRefs.Length; ++i) textureParams[i].texture = textureRefs[i]; textureRefs = null; } } if (version < 4) { sizeDef.CopyFromLegacy( useTk2dCamera, targetOrthoSize, targetHeight ); } version = CURRENT_VERSION; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif } }
//----------------------------------------------------------------------- // <copyright file="GraphStageLogicSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using Akka.Actor; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.Stage; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.Streams.Tests.Implementation.Fusing; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Implementation { public class GraphStageLogicSpec : GraphInterpreterSpecKit { private class Emit1234 : GraphStage<FlowShape<int, int>> { #region internal classes private class Emit1234Logic : GraphStageLogic { private readonly Emit1234 _emit; public Emit1234Logic(Emit1234 emit) : base(emit.Shape) { _emit = emit; SetHandler(emit._in, EagerTerminateInput); SetHandler(emit._out, EagerTerminateOutput); } public override void PreStart() { Emit(_emit._out, 1, () => Emit(_emit._out, 2)); Emit(_emit._out, 3, () => Emit(_emit._out, 4)); } } #endregion private readonly Inlet<int> _in = new Inlet<int>("in"); private readonly Outlet<int> _out = new Outlet<int>("out"); public Emit1234() { Shape = new FlowShape<int, int>(_in, _out); } public override FlowShape<int, int> Shape { get; } protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Emit1234Logic(this); } private class Emit5678 : GraphStage<FlowShape<int, int>> { #region internal classes private class Emit5678Logic : GraphStageLogic { public Emit5678Logic(Emit5678 emit) : base(emit.Shape) { SetHandler(emit._in, onPush: () => Push(emit._out, Grab(emit._in)), onUpstreamFinish: () => { Emit(emit._out, 5, () => Emit(emit._out, 6)); Emit(emit._out, 7, () => Emit(emit._out, 8)); CompleteStage(); }); SetHandler(emit._out, onPull: () => Pull(emit._in)); } } #endregion private readonly Inlet<int> _in = new Inlet<int>("in"); private readonly Outlet<int> _out = new Outlet<int>("out"); public Emit5678() { Shape = new FlowShape<int, int>(_in, _out); } public override FlowShape<int, int> Shape { get; } protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Emit5678Logic(this); } private class PassThrough : GraphStage<FlowShape<int, int>> { #region internal classes private class PassThroughLogic : GraphStageLogic { public PassThroughLogic(PassThrough emit) : base(emit.Shape) { SetHandler(emit.In, onPush: () => Push(emit.Out, Grab(emit.In)), onUpstreamFinish: () => Complete(emit.Out)); SetHandler(emit.Out, onPull: () => Pull(emit.In)); } } #endregion public Inlet<int> In { get; } = new Inlet<int>("in"); public Outlet<int> Out { get; } = new Outlet<int>("out"); public PassThrough() { Shape = new FlowShape<int, int>(In, Out); } public override FlowShape<int, int> Shape { get; } protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new PassThroughLogic(this); } private class EmitEmptyIterable : GraphStage<SourceShape<int>> { #region internal classes private class EmitEmptyIterableLogic : GraphStageLogic { public EmitEmptyIterableLogic(EmitEmptyIterable emit) : base(emit.Shape) { SetHandler(emit._out, () => EmitMultiple(emit._out, Enumerable.Empty<int>(), () => Emit(emit._out, 42, CompleteStage))); } } #endregion private readonly Outlet<int> _out = new Outlet<int>("out"); public EmitEmptyIterable() { Shape = new SourceShape<int>(_out); } public override SourceShape<int> Shape { get; } protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new EmitEmptyIterableLogic(this); } private class ReadNEmitN : GraphStage<FlowShape<int, int>> { private readonly int _n; #region internal classes private class ReadNEmitNLogic : GraphStageLogic { private readonly ReadNEmitN _emit; public ReadNEmitNLogic(ReadNEmitN emit) : base(emit.Shape) { _emit = emit; SetHandler(emit.Shape.Inlet, EagerTerminateInput); SetHandler(emit.Shape.Outlet, EagerTerminateOutput); } public override void PreStart() { ReadMany(_emit.Shape.Inlet, _emit._n, e => EmitMultiple(_emit.Shape.Outlet, e.GetEnumerator(), CompleteStage), _ => { }); } } #endregion public ReadNEmitN(int n) { _n = n; } public override FlowShape<int, int> Shape { get; } = new FlowShape<int, int>(new Inlet<int>("readN.in"), new Outlet<int>("readN.out")); protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new ReadNEmitNLogic(this); } private class ReadNEmitRestOnComplete : GraphStage<FlowShape<int, int>> { private readonly int _n; #region internal classes private class ReadNEmitRestOnCompleteLogic : GraphStageLogic { private readonly ReadNEmitRestOnComplete _emit; public ReadNEmitRestOnCompleteLogic(ReadNEmitRestOnComplete emit) : base(emit.Shape) { _emit = emit; SetHandler(emit.Shape.Inlet, EagerTerminateInput); SetHandler(emit.Shape.Outlet, EagerTerminateOutput); } public override void PreStart() { ReadMany(_emit.Shape.Inlet, _emit._n, _=> FailStage(new IllegalStateException("Shouldn't happen!")), e=> EmitMultiple(_emit.Shape.Outlet, e.GetEnumerator(), CompleteStage)); } } #endregion public ReadNEmitRestOnComplete(int n) { _n = n; } public override FlowShape<int, int> Shape { get; } = new FlowShape<int, int>(new Inlet<int>("readN.in"), new Outlet<int>("readN.out")); protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new ReadNEmitRestOnCompleteLogic(this); } private ActorMaterializer Materializer { get; } public GraphStageLogicSpec(ITestOutputHelper output) : base(output) { Materializer = ActorMaterializer.Create(Sys); } [Fact] public void A_GraphStageLogic_must_read_N_and_emit_N_before_completing() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 10)) .Via(new ReadNEmitN(2)) .RunWith(this.SinkProbe<int>(), Materializer) .Request(10) .ExpectNext(1, 2) .ExpectComplete(); }, Materializer); } [Fact] public void A_GraphStageLogic_must_read_N_should_not_emit_if_upstream_completes_before_N_is_sent() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 5)) .Via(new ReadNEmitN(6)) .RunWith(this.SinkProbe<int>(), Materializer) .Request(10) .ExpectComplete(); }, Materializer); } [Fact] public void A_GraphStageLogic_must_read_N_should_not_emit_if_upstream_fails_before_N_is_sent() { this.AssertAllStagesStopped(() => { var error = new ArgumentException("Don't argue like that!"); Source.From(Enumerable.Range(1, 5)) .Select(x => { if (x > 3) throw error; return x; }) .Via(new ReadNEmitN(6)) .RunWith(this.SinkProbe<int>(), Materializer) .Request(10) .ExpectError().Should().Be(error); }, Materializer); } [Fact] public void A_GraphStageLogic_must_read_N_should_provide_elements_read_if_OnComplete_happens_before_N_elements_have_been_seen() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 5)) .Via(new ReadNEmitRestOnComplete(6)) .RunWith(this.SinkProbe<int>(), Materializer) .Request(10) .ExpectNext(1, 2, 3, 4, 5) .ExpectComplete(); }, Materializer); } [Fact] public void A_GraphStageLogic_must_emit_all_things_before_completing() { this.AssertAllStagesStopped(() => { Source.Empty<int>() .Via(new Emit1234().Named("testStage")) .RunWith(this.SinkProbe<int>(), Materializer) .Request(5) .ExpectNext(1, 2, 3, 4) .ExpectComplete(); }, Materializer); } [Fact] public void A_GraphStageLogic_must_emit_all_things_before_completing_with_two_fused_stages() { this.AssertAllStagesStopped(() => { var flow = Flow.Create<int>().Via(new Emit1234()).Via(new Emit5678()); var g = Streams.Implementation.Fusing.Fusing.Aggressive(flow); Source.Empty<int>() .Via(g) .RunWith(this.SinkProbe<int>(), Materializer) .Request(9) .ExpectNext(1, 2, 3, 4, 5, 6, 7, 8) .ExpectComplete(); }, Materializer); } [Fact] public void A_GraphStageLogic_must_emit_all_things_before_completing_with_three_fused_stages() { this.AssertAllStagesStopped(() => { var flow = Flow.Create<int>().Via(new Emit1234()).Via(new PassThrough()).Via(new Emit5678()); var g = Streams.Implementation.Fusing.Fusing.Aggressive(flow); Source.Empty<int>() .Via(g) .RunWith(this.SinkProbe<int>(), Materializer) .Request(9) .ExpectNext(1, 2, 3, 4, 5, 6, 7, 8) .ExpectComplete(); }, Materializer); } [Fact] public void A_GraphStageLogic_must_emit_properly_after_empty_iterable() { this.AssertAllStagesStopped(() => { Source.FromGraph(new EmitEmptyIterable()) .RunWith(Sink.Seq<int>(), Materializer) .Result.Should() .HaveCount(1) .And.OnlyContain(x => x == 42); }, Materializer); } [Fact] public void A_GraphStageLogic_must_infoke_livecycle_hooks_in_the_right_order() { this.AssertAllStagesStopped(() => { var g = new LifecycleStage(TestActor); Source.Single(1).Via(g).RunWith(Sink.Ignore<int>(), Materializer); ExpectMsg("preStart"); ExpectMsg("pulled"); ExpectMsg("postStop"); }, Materializer); } private class LifecycleStage : GraphStage<FlowShape<int, int>> { #region internal class private class LivecycleLogic : GraphStageLogic { private readonly IActorRef _testActor; public LivecycleLogic(LifecycleStage stage, IActorRef testActor) : base(stage.Shape) { _testActor = testActor; SetHandler(stage._in, EagerTerminateInput); SetHandler(stage._out, () => { CompleteStage(); testActor.Tell("pulled"); }); } public override void PreStart() { _testActor.Tell("preStart"); } public override void PostStop() { _testActor.Tell("postStop"); } } #endregion private readonly Inlet<int> _in = new Inlet<int>("in"); private readonly Outlet<int> _out = new Outlet<int>("out"); private readonly IActorRef _testActor; public LifecycleStage(IActorRef testActor) { _testActor = testActor; Shape = new FlowShape<int, int>(_in, _out); } public override FlowShape<int, int> Shape { get; } protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new LivecycleLogic(this, _testActor); } [Fact] public void A_GraphStageLogic_must_not_double_terminate_a_single_stage() { WithBaseBuilderSetup( new GraphStage<FlowShape<int, int>>[] {new DoubleTerminateStage(TestActor), new PassThrough()}, interpreter => { interpreter.Complete(interpreter.Connections[0]); interpreter.Cancel(interpreter.Connections[1]); interpreter.Execute(2); ExpectMsg("postStop2"); ExpectNoMsg(0); interpreter.IsCompleted.Should().BeFalse(); interpreter.IsSuspended.Should().BeFalse(); interpreter.IsStageCompleted(interpreter.Logics[0]).Should().BeTrue(); interpreter.IsStageCompleted(interpreter.Logics[1]).Should().BeFalse(); }); } private class DoubleTerminateStage : GraphStage<FlowShape<int, int>> { #region internal class private class DoubleTerminateLogic : GraphStageLogic { private readonly IActorRef _testActor; public DoubleTerminateLogic(DoubleTerminateStage stage, IActorRef testActor) : base(stage.Shape) { _testActor = testActor; SetHandler(stage.In, EagerTerminateInput); SetHandler(stage.Out, EagerTerminateOutput); } public override void PostStop() { _testActor.Tell("postStop2"); } } #endregion private readonly IActorRef _testActor; public DoubleTerminateStage(IActorRef testActor) { _testActor = testActor; Shape = new FlowShape<int, int>(In, Out); } public override FlowShape<int, int> Shape { get; } public Inlet<int> In { get; } = new Inlet<int>("in"); public Outlet<int> Out { get; } = new Outlet<int>("out"); protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new DoubleTerminateLogic(this, _testActor); } } }
using System; using System.Collections.Specialized; using System.Configuration.Provider; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Security; using Umbraco.Core.Logging; namespace Umbraco.Core.Security { /// <summary> /// A base membership provider class offering much of the underlying functionality for initializing and password encryption/hashing. /// </summary> public abstract class MembershipProviderBase : MembershipProvider { public string HashPasswordForStorage(string password) { string salt; var hashed = EncryptOrHashNewPassword(password, out salt); return FormatPasswordForStorage(hashed, salt); } public bool VerifyPassword(string password, string hashedPassword) { return CheckPassword(password, hashedPassword); } /// <summary> /// Providers can override this setting, default is 7 /// </summary> public virtual int DefaultMinPasswordLength { get { return 7; } } /// <summary> /// Providers can override this setting, default is 1 /// </summary> public virtual int DefaultMinNonAlphanumericChars { get { return 1; } } /// <summary> /// Providers can override this setting, default is false to use better security /// </summary> public virtual bool DefaultUseLegacyEncoding { get { return false; } } /// <summary> /// Providers can override this setting, by default this is false which means that the provider will /// authenticate the username + password when ChangePassword is called. This property exists purely for /// backwards compatibility. /// </summary> public virtual bool AllowManuallyChangingPassword { get { return false; } } private string _applicationName; private bool _enablePasswordReset; private bool _enablePasswordRetrieval; private int _maxInvalidPasswordAttempts; private int _minRequiredNonAlphanumericCharacters; private int _minRequiredPasswordLength; private int _passwordAttemptWindow; private MembershipPasswordFormat _passwordFormat; private string _passwordStrengthRegularExpression; private bool _requiresQuestionAndAnswer; private bool _requiresUniqueEmail; private string _customHashAlgorithmType ; internal bool UseLegacyEncoding; #region Properties /// <summary> /// Indicates whether the membership provider is configured to allow users to reset their passwords. /// </summary> /// <value></value> /// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns> public override bool EnablePasswordReset { get { return _enablePasswordReset; } } /// <summary> /// Indicates whether the membership provider is configured to allow users to retrieve their passwords. /// </summary> /// <value></value> /// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns> public override bool EnablePasswordRetrieval { get { return _enablePasswordRetrieval; } } /// <summary> /// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out. /// </summary> /// <value></value> /// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns> public override int MaxInvalidPasswordAttempts { get { return _maxInvalidPasswordAttempts; } } /// <summary> /// Gets the minimum number of special characters that must be present in a valid password. /// </summary> /// <value></value> /// <returns>The minimum number of special characters that must be present in a valid password.</returns> public override int MinRequiredNonAlphanumericCharacters { get { return _minRequiredNonAlphanumericCharacters; } } /// <summary> /// Gets the minimum length required for a password. /// </summary> /// <value></value> /// <returns>The minimum length required for a password. </returns> public override int MinRequiredPasswordLength { get { return _minRequiredPasswordLength; } } /// <summary> /// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out. /// </summary> /// <value></value> /// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns> public override int PasswordAttemptWindow { get { return _passwordAttemptWindow; } } /// <summary> /// Gets a value indicating the format for storing passwords in the membership data store. /// </summary> /// <value></value> /// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.</returns> public override MembershipPasswordFormat PasswordFormat { get { return _passwordFormat; } } /// <summary> /// Gets the regular expression used to evaluate a password. /// </summary> /// <value></value> /// <returns>A regular expression used to evaluate a password.</returns> public override string PasswordStrengthRegularExpression { get { return _passwordStrengthRegularExpression; } } /// <summary> /// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval. /// </summary> /// <value></value> /// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns> public override bool RequiresQuestionAndAnswer { get { return _requiresQuestionAndAnswer; } } /// <summary> /// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name. /// </summary> /// <value></value> /// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns> public override bool RequiresUniqueEmail { get { return _requiresUniqueEmail; } } /// <summary> /// The name of the application using the custom membership provider. /// </summary> /// <value></value> /// <returns>The name of the application using the custom membership provider.</returns> public override string ApplicationName { get { return _applicationName; } set { if (string.IsNullOrEmpty(value)) throw new ProviderException("ApplicationName cannot be empty."); if (value.Length > 0x100) throw new ProviderException("Provider application name too long."); _applicationName = value; } } #endregion /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// <exception cref="T:System.InvalidOperationException">An attempt is made to call /// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider /// has already been initialized.</exception> /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> public override void Initialize(string name, NameValueCollection config) { // Initialize base provider class base.Initialize(name, config); _enablePasswordRetrieval = config.GetValue("enablePasswordRetrieval", false); _enablePasswordReset = config.GetValue("enablePasswordReset", false); _requiresQuestionAndAnswer = config.GetValue("requiresQuestionAndAnswer", false); _requiresUniqueEmail = config.GetValue("requiresUniqueEmail", true); _maxInvalidPasswordAttempts = GetIntValue(config, "maxInvalidPasswordAttempts", 20, false, 0); _passwordAttemptWindow = GetIntValue(config, "passwordAttemptWindow", 10, false, 0); _minRequiredPasswordLength = GetIntValue(config, "minRequiredPasswordLength", DefaultMinPasswordLength, true, 0x80); _minRequiredNonAlphanumericCharacters = GetIntValue(config, "minRequiredNonalphanumericCharacters", DefaultMinNonAlphanumericChars, true, 0x80); _passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; _applicationName = config["applicationName"]; if (string.IsNullOrEmpty(_applicationName)) _applicationName = GetDefaultAppName(); //by default we will continue using the legacy encoding. UseLegacyEncoding = config.GetValue("useLegacyEncoding", DefaultUseLegacyEncoding); // make sure password format is Hashed by default. string str = config["passwordFormat"] ?? "Hashed"; switch (str.ToLower()) { case "clear": _passwordFormat = MembershipPasswordFormat.Clear; break; case "encrypted": _passwordFormat = MembershipPasswordFormat.Encrypted; break; case "hashed": _passwordFormat = MembershipPasswordFormat.Hashed; break; default: throw new ProviderException("Provider bad password format"); } if ((PasswordFormat == MembershipPasswordFormat.Hashed) && EnablePasswordRetrieval) { var ex = new ProviderException("Provider can not retrieve a hashed password"); LogHelper.Error<MembershipProviderBase>("Cannot specify a Hashed password format with the enabledPasswordRetrieval option set to true", ex); throw ex; } _customHashAlgorithmType = config.GetValue("hashAlgorithmType", string.Empty); } /// <summary> /// Override this method to ensure the password is valid before raising the event /// </summary> /// <param name="e"></param> protected override void OnValidatingPassword(ValidatePasswordEventArgs e) { var attempt = IsPasswordValid(e.Password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength); if (attempt.Success == false) { e.Cancel = true; return; } base.OnValidatingPassword(e); } protected internal enum PasswordValidityError { Ok, Length, AlphanumericChars, Strength } /// <summary> /// Processes a request to update the password for a membership user. /// </summary> /// <param name="username">The user to update the password for.</param> /// <param name="oldPassword">This property is ignore for this provider</param> /// <param name="newPassword">The new password for the specified user.</param> /// <returns> /// true if the password was updated successfully; otherwise, false. /// </returns> /// <remarks> /// Checks to ensure the AllowManuallyChangingPassword rule is adhered to /// </remarks> public override bool ChangePassword(string username, string oldPassword, string newPassword) { if (oldPassword.IsNullOrWhiteSpace() && AllowManuallyChangingPassword == false) { //If the old password is empty and AllowManuallyChangingPassword is false, than this provider cannot just arbitrarily change the password throw new NotSupportedException("This provider does not support manually changing the password"); } var args = new ValidatePasswordEventArgs(username, newPassword, false); OnValidatingPassword(args); if (args.Cancel) { if (args.FailureInformation != null) throw args.FailureInformation; throw new MembershipPasswordException("Change password canceled due to password validation failure."); } if (AllowManuallyChangingPassword == false) { if (ValidateUser(username, oldPassword) == false) return false; } return PerformChangePassword(username, oldPassword, newPassword); } /// <summary> /// Processes a request to update the password for a membership user. /// </summary> /// <param name="username">The user to update the password for.</param> /// <param name="oldPassword">This property is ignore for this provider</param> /// <param name="newPassword">The new password for the specified user.</param> /// <returns> /// true if the password was updated successfully; otherwise, false. /// </returns> protected abstract bool PerformChangePassword(string username, string oldPassword, string newPassword); /// <summary> /// Processes a request to update the password question and answer for a membership user. /// </summary> /// <param name="username">The user to change the password question and answer for.</param> /// <param name="password">The password for the specified user.</param> /// <param name="newPasswordQuestion">The new password question for the specified user.</param> /// <param name="newPasswordAnswer">The new password answer for the specified user.</param> /// <returns> /// true if the password question and answer are updated successfully; otherwise, false. /// </returns> /// <remarks> /// Performs the basic validation before passing off to PerformChangePasswordQuestionAndAnswer /// </remarks> public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { if (RequiresQuestionAndAnswer == false) { throw new NotSupportedException("Updating the password Question and Answer is not available if requiresQuestionAndAnswer is not set in web.config"); } if (AllowManuallyChangingPassword == false) { if (ValidateUser(username, password) == false) { return false; } } return PerformChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer); } /// <summary> /// Processes a request to update the password question and answer for a membership user. /// </summary> /// <param name="username">The user to change the password question and answer for.</param> /// <param name="password">The password for the specified user.</param> /// <param name="newPasswordQuestion">The new password question for the specified user.</param> /// <param name="newPasswordAnswer">The new password answer for the specified user.</param> /// <returns> /// true if the password question and answer are updated successfully; otherwise, false. /// </returns> protected abstract bool PerformChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer); /// <summary> /// Adds a new membership user to the data source. /// </summary> /// <param name="username">The user name for the new user.</param> /// <param name="password">The password for the new user.</param> /// <param name="email">The e-mail address for the new user.</param> /// <param name="passwordQuestion">The password question for the new user.</param> /// <param name="passwordAnswer">The password answer for the new user</param> /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user. /// </returns> /// <remarks> /// Ensures the ValidatingPassword event is executed before executing PerformCreateUser and performs basic membership provider validation of values. /// </remarks> public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { var valStatus = ValidateNewUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey); if (valStatus != MembershipCreateStatus.Success) { status = valStatus; return null; } return PerformCreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status); } /// <summary> /// Performs the validation of the information for creating a new user /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="email"></param> /// <param name="passwordQuestion"></param> /// <param name="passwordAnswer"></param> /// <param name="isApproved"></param> /// <param name="providerUserKey"></param> /// <returns></returns> protected MembershipCreateStatus ValidateNewUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey) { var args = new ValidatePasswordEventArgs(username, password, true); OnValidatingPassword(args); if (args.Cancel) { return MembershipCreateStatus.InvalidPassword; } // Validate password var passwordValidAttempt = IsPasswordValid(password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength); if (passwordValidAttempt.Success == false) { return MembershipCreateStatus.InvalidPassword; } // Validate email if (IsEmailValid(email) == false) { return MembershipCreateStatus.InvalidEmail; } // Make sure username isn't all whitespace if (string.IsNullOrWhiteSpace(username.Trim())) { return MembershipCreateStatus.InvalidUserName; } // Check password question if (string.IsNullOrWhiteSpace(passwordQuestion) && RequiresQuestionAndAnswer) { return MembershipCreateStatus.InvalidQuestion; } // Check password answer if (string.IsNullOrWhiteSpace(passwordAnswer) && RequiresQuestionAndAnswer) { return MembershipCreateStatus.InvalidAnswer; } return MembershipCreateStatus.Success; } /// <summary> /// Adds a new membership user to the data source. /// </summary> /// <param name="username">The user name for the new user.</param> /// <param name="password">The password for the new user.</param> /// <param name="email">The e-mail address for the new user.</param> /// <param name="passwordQuestion">The password question for the new user.</param> /// <param name="passwordAnswer">The password answer for the new user</param> /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param> /// <returns> /// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user. /// </returns> protected abstract MembershipUser PerformCreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status); /// <summary> /// Gets the members password if password retreival is enabled /// </summary> /// <param name="username"></param> /// <param name="answer"></param> /// <returns></returns> public override string GetPassword(string username, string answer) { if (EnablePasswordRetrieval == false) throw new ProviderException("Password Retrieval Not Enabled."); if (PasswordFormat == MembershipPasswordFormat.Hashed) throw new ProviderException("Cannot retrieve Hashed passwords."); return PerformGetPassword(username, answer); } /// <summary> /// Gets the members password if password retreival is enabled /// </summary> /// <param name="username"></param> /// <param name="answer"></param> /// <returns></returns> protected abstract string PerformGetPassword(string username, string answer); public override string ResetPassword(string username, string answer) { if (EnablePasswordReset == false) { throw new NotSupportedException("Password reset is not supported"); } var newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); var args = new ValidatePasswordEventArgs(username, newPassword, true); OnValidatingPassword(args); if (args.Cancel) { if (args.FailureInformation != null) { throw args.FailureInformation; } throw new MembershipPasswordException("Reset password canceled due to password validation failure."); } return PerformResetPassword(username, answer, newPassword); } protected abstract string PerformResetPassword(string username, string answer, string generatedPassword); protected internal static Attempt<PasswordValidityError> IsPasswordValid(string password, int minRequiredNonAlphanumericChars, string strengthRegex, int minLength) { if (minRequiredNonAlphanumericChars > 0) { var nonAlphaNumeric = Regex.Replace(password, "[a-zA-Z0-9]", "", RegexOptions.Multiline | RegexOptions.IgnoreCase); if (nonAlphaNumeric.Length < minRequiredNonAlphanumericChars) { return Attempt.Fail(PasswordValidityError.AlphanumericChars); } } if (string.IsNullOrEmpty(strengthRegex) == false) { if (Regex.IsMatch(password, strengthRegex, RegexOptions.Compiled) == false) { return Attempt.Fail(PasswordValidityError.Strength); } } if (password.Length < minLength) { return Attempt.Fail(PasswordValidityError.Length); } return Attempt.Succeed(PasswordValidityError.Ok); } /// <summary> /// Gets the name of the default app. /// </summary> /// <returns></returns> internal static string GetDefaultAppName() { try { string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath; if (string.IsNullOrEmpty(applicationVirtualPath)) { return "/"; } return applicationVirtualPath; } catch { return "/"; } } internal static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed) { int num; string s = config[valueName]; if (s == null) { return defaultValue; } if (!int.TryParse(s, out num)) { if (zeroAllowed) { throw new ProviderException("Value must be non negative integer"); } throw new ProviderException("Value must be positive integer"); } if (zeroAllowed && (num < 0)) { throw new ProviderException("Value must be non negativeinteger"); } if (!zeroAllowed && (num <= 0)) { throw new ProviderException("Value must be positive integer"); } if ((maxValueAllowed > 0) && (num > maxValueAllowed)) { throw new ProviderException("Value too big"); } return num; } /// <summary> /// If the password format is a hashed keyed algorithm then we will pre-pend the salt used to hash the password /// to the hashed password itself. /// </summary> /// <param name="pass"></param> /// <param name="salt"></param> /// <returns></returns> protected internal string FormatPasswordForStorage(string pass, string salt) { if (UseLegacyEncoding) { return pass; } if (PasswordFormat == MembershipPasswordFormat.Hashed) { //the better way, we use salt per member return salt + pass; } return pass; } internal static bool IsEmailValid(string email) { const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"; return Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); } protected internal string EncryptOrHashPassword(string pass, string salt) { //if we are doing it the old way if (UseLegacyEncoding) { return LegacyEncodePassword(pass); } //This is the correct way to implement this (as per the sql membership provider) if (PasswordFormat == MembershipPasswordFormat.Clear) return pass; var bytes = Encoding.Unicode.GetBytes(pass); var numArray1 = Convert.FromBase64String(salt); byte[] inArray; if (PasswordFormat == MembershipPasswordFormat.Hashed) { var hashAlgorithm = GetHashAlgorithm(pass); var algorithm = hashAlgorithm as KeyedHashAlgorithm; if (algorithm != null) { var keyedHashAlgorithm = algorithm; if (keyedHashAlgorithm.Key.Length == numArray1.Length) keyedHashAlgorithm.Key = numArray1; else if (keyedHashAlgorithm.Key.Length < numArray1.Length) { var numArray2 = new byte[keyedHashAlgorithm.Key.Length]; Buffer.BlockCopy(numArray1, 0, numArray2, 0, numArray2.Length); keyedHashAlgorithm.Key = numArray2; } else { var numArray2 = new byte[keyedHashAlgorithm.Key.Length]; var dstOffset = 0; while (dstOffset < numArray2.Length) { var count = Math.Min(numArray1.Length, numArray2.Length - dstOffset); Buffer.BlockCopy(numArray1, 0, numArray2, dstOffset, count); dstOffset += count; } keyedHashAlgorithm.Key = numArray2; } inArray = keyedHashAlgorithm.ComputeHash(bytes); } else { var buffer = new byte[numArray1.Length + bytes.Length]; Buffer.BlockCopy(numArray1, 0, buffer, 0, numArray1.Length); Buffer.BlockCopy(bytes, 0, buffer, numArray1.Length, bytes.Length); inArray = hashAlgorithm.ComputeHash(buffer); } } else { //this code is copied from the sql membership provider - pretty sure this could be nicely re-written to completely // ignore the salt stuff since we are not salting the password when encrypting. var password = new byte[numArray1.Length + bytes.Length]; Buffer.BlockCopy(numArray1, 0, password, 0, numArray1.Length); Buffer.BlockCopy(bytes, 0, password, numArray1.Length, bytes.Length); inArray = EncryptPassword(password, MembershipPasswordCompatibilityMode.Framework40); } return Convert.ToBase64String(inArray); } /// <summary> /// Checks the password. /// </summary> /// <param name="password">The password.</param> /// <param name="dbPassword">The dbPassword.</param> /// <returns></returns> protected internal bool CheckPassword(string password, string dbPassword) { switch (PasswordFormat) { case MembershipPasswordFormat.Encrypted: var decrypted = DecryptPassword(dbPassword); return decrypted == password; case MembershipPasswordFormat.Hashed: string salt; var storedHashedPass = StoredPassword(dbPassword, out salt); var hashed = EncryptOrHashPassword(password, salt); return storedHashedPass == hashed; case MembershipPasswordFormat.Clear: return password == dbPassword; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Encrypt/hash a new password with a new salt /// </summary> /// <param name="newPassword"></param> /// <param name="salt"></param> /// <returns></returns> protected internal string EncryptOrHashNewPassword(string newPassword, out string salt) { salt = GenerateSalt(); return EncryptOrHashPassword(newPassword, salt); } protected internal string DecryptPassword(string pass) { //if we are doing it the old way if (UseLegacyEncoding) { return LegacyUnEncodePassword(pass); } //This is the correct way to implement this (as per the sql membership provider) switch ((int)PasswordFormat) { case 0: return pass; case 1: throw new ProviderException("Provider can not decrypt hashed password"); default: var bytes = DecryptPassword(Convert.FromBase64String(pass)); return bytes == null ? null : Encoding.Unicode.GetString(bytes, 16, bytes.Length - 16); } } /// <summary> /// Returns the hashed password without the salt if it is hashed /// </summary> /// <param name="storedString"></param> /// <param name="salt">returns the salt</param> /// <returns></returns> internal string StoredPassword(string storedString, out string salt) { if (UseLegacyEncoding) { salt = string.Empty; return storedString; } switch (PasswordFormat) { case MembershipPasswordFormat.Hashed: var saltLen = GenerateSalt(); salt = storedString.Substring(0, saltLen.Length); return storedString.Substring(saltLen.Length); case MembershipPasswordFormat.Clear: case MembershipPasswordFormat.Encrypted: default: salt = string.Empty; return storedString; } } protected internal static string GenerateSalt() { var numArray = new byte[16]; new RNGCryptoServiceProvider().GetBytes(numArray); return Convert.ToBase64String(numArray); } protected internal HashAlgorithm GetHashAlgorithm(string password) { if (UseLegacyEncoding) { //before we were never checking for an algorithm type so we were always using HMACSHA1 // for any SHA specified algorithm :( so we'll need to keep doing that for backwards compat support. if (Membership.HashAlgorithmType.InvariantContains("SHA")) { return new HMACSHA1 { //the legacy salt was actually the password :( Key = Encoding.Unicode.GetBytes(password) }; } } //get the algorithm by name if (_customHashAlgorithmType.IsNullOrWhiteSpace()) { _customHashAlgorithmType = Membership.HashAlgorithmType; } var alg = HashAlgorithm.Create(_customHashAlgorithmType); if (alg == null) { throw new InvalidOperationException("The hash algorithm specified " + Membership.HashAlgorithmType + " cannot be resolved"); } return alg; } /// <summary> /// Encodes the password. /// </summary> /// <param name="password">The password.</param> /// <returns>The encoded password.</returns> protected string LegacyEncodePassword(string password) { string encodedPassword = password; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); break; case MembershipPasswordFormat.Hashed: var hashAlgorith = GetHashAlgorithm(password); encodedPassword = Convert.ToBase64String(hashAlgorith.ComputeHash(Encoding.Unicode.GetBytes(password))); break; default: throw new ProviderException("Unsupported password format."); } return encodedPassword; } /// <summary> /// Unencode password. /// </summary> /// <param name="encodedPassword">The encoded password.</param> /// <returns>The unencoded password.</returns> protected string LegacyUnEncodePassword(string encodedPassword) { string password = encodedPassword; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); break; case MembershipPasswordFormat.Hashed: throw new ProviderException("Cannot unencode a hashed password."); default: throw new ProviderException("Unsupported password format."); } return password; } public override string ToString() { var result = base.ToString(); var sb = new StringBuilder(result); sb.AppendLine("Name =" + Name); sb.AppendLine("_applicationName =" + _applicationName); sb.AppendLine("_enablePasswordReset=" + _enablePasswordReset); sb.AppendLine("_enablePasswordRetrieval=" + _enablePasswordRetrieval); sb.AppendLine("_maxInvalidPasswordAttempts=" + _maxInvalidPasswordAttempts); sb.AppendLine("_minRequiredNonAlphanumericCharacters=" + _minRequiredNonAlphanumericCharacters); sb.AppendLine("_minRequiredPasswordLength=" + _minRequiredPasswordLength); sb.AppendLine("_passwordAttemptWindow=" + _passwordAttemptWindow); sb.AppendLine("_passwordFormat=" + _passwordFormat); sb.AppendLine("_passwordStrengthRegularExpression=" + _passwordStrengthRegularExpression); sb.AppendLine("_requiresQuestionAndAnswer=" + _requiresQuestionAndAnswer); sb.AppendLine("_requiresUniqueEmail=" + _requiresUniqueEmail); return sb.ToString(); } /// <summary> /// Returns the current request IP address for logging if there is one /// </summary> /// <returns></returns> protected string GetCurrentRequestIpAddress() { var httpContext = HttpContext.Current == null ? (HttpContextBase) null : new HttpContextWrapper(HttpContext.Current); return httpContext.GetCurrentRequestIpAddress(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Abp.Collections.Extensions; using Abp.Dependency; using Abp.Reflection; namespace Abp.Runtime.Validation.Interception { /// <summary> /// This class is used to validate a method call (invocation) for method arguments. /// </summary> public class MethodInvocationValidator : ITransientDependency { public static List<Type> IgnoredTypesForRecursiveValidation { get; } protected MethodInfo Method { get; private set; } protected object[] ParameterValues { get; private set; } protected ParameterInfo[] Parameters { get; private set; } protected List<ValidationResult> ValidationErrors { get; } static MethodInvocationValidator() { IgnoredTypesForRecursiveValidation = new List<Type>(); } /// <summary> /// Creates a new <see cref="MethodInvocationValidator"/> instance. /// </summary> public MethodInvocationValidator() { ValidationErrors = new List<ValidationResult>(); } /// <param name="method">Method to be validated</param> /// <param name="parameterValues">List of arguments those are used to call the <paramref name="method"/>.</param> public virtual void Initialize(MethodInfo method, object[] parameterValues) { if (method == null) { throw new ArgumentNullException(nameof(method)); } if (parameterValues == null) { throw new ArgumentNullException(nameof(parameterValues)); } Method = method; ParameterValues = parameterValues; Parameters = method.GetParameters(); } /// <summary> /// Validates the method invocation. /// </summary> public void Validate() { CheckInitialized(); if (!Method.IsPublic) { return; } if (IsValidationDisabled()) { return; } if (Parameters.IsNullOrEmpty()) { return; } if (Parameters.Length != ParameterValues.Length) { throw new Exception("Method parameter count does not match with argument count!"); } for (var i = 0; i < Parameters.Length; i++) { ValidateMethodParameter(Parameters[i], ParameterValues[i]); } if (ValidationErrors.Any()) { throw new AbpValidationException( "Method arguments are not valid! See ValidationErrors for details.", ValidationErrors ); } foreach (var parameterValue in ParameterValues) { NormalizeParameter(parameterValue); } } private void CheckInitialized() { if (Method == null) { throw new AbpException("This object has not been initialized. Call Initialize method first."); } } protected virtual bool IsValidationDisabled() { if (Method.IsDefined(typeof(EnableValidationAttribute), true)) { return false; } return ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<DisableValidationAttribute>(Method) != null; } /// <summary> /// Validates given parameter for given value. /// </summary> /// <param name="parameterInfo">Parameter of the method to validate</param> /// <param name="parameterValue">Value to validate</param> protected virtual void ValidateMethodParameter(ParameterInfo parameterInfo, object parameterValue) { if (parameterValue == null) { if (!parameterInfo.IsOptional && !parameterInfo.IsOut && !TypeHelper.IsPrimitiveExtendedIncludingNullable(parameterInfo.ParameterType)) { ValidationErrors.Add(new ValidationResult(parameterInfo.Name + " is null!", new[] { parameterInfo.Name })); } return; } ValidateObjectRecursively(parameterValue); } protected virtual void ValidateObjectRecursively(object validatingObject) { if (validatingObject == null) { return; } SetDataAnnotationAttributeErrors(validatingObject); //Validate items of enumerable if (validatingObject is IEnumerable && !(validatingObject is IQueryable)) { foreach (var item in (validatingObject as IEnumerable)) { ValidateObjectRecursively(item); } } if (validatingObject is ICustomValidate) { (validatingObject as ICustomValidate).AddValidationErrors(ValidationErrors); } //Do not recursively validate for enumerable objects if (validatingObject is IEnumerable) { return; } var validatingObjectType = validatingObject.GetType(); //Do not recursively validate for primitive objects if (TypeHelper.IsPrimitiveExtendedIncludingNullable(validatingObjectType)) { return; } if (IgnoredTypesForRecursiveValidation.Contains(validatingObjectType)) { return; } var properties = TypeDescriptor.GetProperties(validatingObject).Cast<PropertyDescriptor>(); foreach (var property in properties) { if (property.Attributes.OfType<DisableValidationAttribute>().Any()) { continue; } ValidateObjectRecursively(property.GetValue(validatingObject)); } } /// <summary> /// Checks all properties for DataAnnotations attributes. /// </summary> protected virtual void SetDataAnnotationAttributeErrors(object validatingObject) { var properties = TypeDescriptor.GetProperties(validatingObject).Cast<PropertyDescriptor>(); foreach (var property in properties) { var validationAttributes = property.Attributes.OfType<ValidationAttribute>().ToArray(); if (validationAttributes.IsNullOrEmpty()) { continue; } var validationContext = new ValidationContext(validatingObject) { DisplayName = property.DisplayName, MemberName = property.Name }; foreach (var attribute in validationAttributes) { var result = attribute.GetValidationResult(property.GetValue(validatingObject), validationContext); if (result != null) { ValidationErrors.Add(result); } } } } protected virtual void NormalizeParameter(object parameterValue) { if (parameterValue is IShouldNormalize) { (parameterValue as IShouldNormalize).Normalize(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** PURPOSE: Tokenize "Elementary XML", that is, XML without ** attributes or DTDs, in other words, XML with ** elements only. ** ** ===========================================================*/ namespace System.Security.Util { using System.Text; using System; using System.IO; using System.Globalization; using System.Diagnostics.Contracts; internal sealed class Tokenizer { // There are five externally knowable token types: bras, kets, // slashes, cstrs, and equals. internal const byte bra = 0; internal const byte ket = 1; internal const byte slash = 2; internal const byte cstr = 3; internal const byte equals = 4; internal const byte quest = 5; internal const byte bang = 6; internal const byte dash = 7; // these are the assorted text characters that the tokenizer must // understand to do its job internal const int intOpenBracket = (int) '<'; internal const int intCloseBracket = (int) '>'; internal const int intSlash = (int) '/'; internal const int intEquals = (int) '='; internal const int intQuote = (int) '\"'; internal const int intQuest = (int) '?'; internal const int intBang = (int) '!'; internal const int intDash = (int) '-'; internal const int intTab = (int) '\t'; internal const int intCR = (int) '\r'; internal const int intLF = (int) '\n'; internal const int intSpace = (int) ' '; // this tells us where we will be getting our input from // and what the encoding is (if any) private enum TokenSource { UnicodeByteArray, // this is little-endian unicode (there are other encodings) UTF8ByteArray, ASCIIByteArray, CharArray, String, NestedStrings, Other } // byte streams can come in 3 different flavors internal enum ByteTokenEncoding { UnicodeTokens, // this is little-endian unicode (there are other encodings) UTF8Tokens, ByteTokens } public int LineNo; // these variables represent the input state of the of the tokenizer private int _inProcessingTag; private byte[] _inBytes; private char[] _inChars; private String _inString; private int _inIndex; private int _inSize; private int _inSavedCharacter; private TokenSource _inTokenSource; private ITokenReader _inTokenReader; // these variables are used to build and deliver tokenizer output strings private StringMaker _maker = null; private String[] _searchStrings; private String[] _replaceStrings; private int _inNestedIndex; private int _inNestedSize; private String _inNestedString; //================================================================ // Constructor uses given ICharInputStream // internal void BasicInitialization() { LineNo = 1 ; _inProcessingTag = 0; _inSavedCharacter = -1; _inIndex = 0; _inSize = 0; _inNestedSize = 0; _inNestedIndex = 0; _inTokenSource = TokenSource.Other; _maker = System.SharedStatics.GetSharedStringMaker(); } public void Recycle() { System.SharedStatics.ReleaseSharedStringMaker(ref _maker); // will set _maker to null } internal Tokenizer (String input) { BasicInitialization(); _inString = input; _inSize = input.Length; _inTokenSource = TokenSource.String; } internal Tokenizer (String input, String[] searchStrings, String[] replaceStrings) { BasicInitialization(); _inString = input; _inSize = _inString.Length; _inTokenSource = TokenSource.NestedStrings; _searchStrings = searchStrings; _replaceStrings = replaceStrings; #if DEBUG Contract.Assert(searchStrings.Length == replaceStrings.Length, "different number of search/replace strings"); Contract.Assert(searchStrings.Length != 0, "no search replace strings, shouldn't be using this ctor"); for (int istr=0; istr<searchStrings.Length; istr++) { String str = searchStrings[istr]; Contract.Assert( str != null, "XML Slug null"); Contract.Assert( str.Length >= 3 , "XML Slug too small"); Contract.Assert( str[0] == '{', "XML Slug doesn't start with '{'" ); Contract.Assert( str[str.Length-1] == '}', "XML Slug doesn't end with '}'" ); str = replaceStrings[istr]; Contract.Assert( str != null, "XML Replacement null"); Contract.Assert( str.Length >= 1, "XML Replacement empty"); } #endif } internal Tokenizer (byte[] array, ByteTokenEncoding encoding, int startIndex) { BasicInitialization(); _inBytes = array; _inSize = array.Length; _inIndex = startIndex; switch (encoding) { case ByteTokenEncoding.UnicodeTokens: _inTokenSource = TokenSource.UnicodeByteArray; break; case ByteTokenEncoding.UTF8Tokens: _inTokenSource = TokenSource.UTF8ByteArray; break; case ByteTokenEncoding.ByteTokens: _inTokenSource = TokenSource.ASCIIByteArray; break; default: throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)encoding)); } } internal Tokenizer (char[] array) { BasicInitialization(); _inChars = array; _inSize = array.Length; _inTokenSource = TokenSource.CharArray; } internal Tokenizer (StreamReader input) { BasicInitialization(); _inTokenReader = new StreamTokenReader(input); } internal void ChangeFormat( System.Text.Encoding encoding ) { if (encoding == null) { return; } Contract.Assert( _inSavedCharacter == -1, "There was a lookahead character at the stream change point, that means the parser is changing encodings too late" ); switch (_inTokenSource) { case TokenSource.UnicodeByteArray: case TokenSource.UTF8ByteArray: case TokenSource.ASCIIByteArray: // these are the ones we can change on the fly if (encoding == System.Text.Encoding.Unicode) { _inTokenSource = TokenSource.UnicodeByteArray; return; } if (encoding == System.Text.Encoding.UTF8) { _inTokenSource = TokenSource.UTF8ByteArray; return; } #if FEATURE_ASCII if (encoding == System.Text.Encoding.ASCII) { _inTokenSource = TokenSource.ASCIIByteArray; return; } #endif break; case TokenSource.String: case TokenSource.CharArray: case TokenSource.NestedStrings: // these are already unicode and encoding changes are moot // they can't be further decoded return; } // if we're here it means we don't know how to change // to the desired encoding with the memory that we have // we'll have to do this the hard way -- that means // creating a suitable stream from what we've got // this is thankfully the rare case as UTF8 and unicode // dominate the scene Stream stream = null; switch (_inTokenSource) { case TokenSource.UnicodeByteArray: case TokenSource.UTF8ByteArray: case TokenSource.ASCIIByteArray: stream = new MemoryStream(_inBytes, _inIndex, _inSize - _inIndex); break; case TokenSource.CharArray: case TokenSource.String: case TokenSource.NestedStrings: Contract.Assert(false, "attempting to change encoding on a non-changable source, should have been prevented earlier" ); return; default: StreamTokenReader reader = _inTokenReader as StreamTokenReader; if (reader == null) { Contract.Assert(false, "A new input source type has been added to the Tokenizer but it doesn't support encoding changes"); return; } stream = reader._in.BaseStream; Contract.Assert( reader._in.CurrentEncoding != null, "Tokenizer's StreamReader does not have an encoding" ); String fakeReadString = new String(' ', reader.NumCharEncountered); stream.Position = reader._in.CurrentEncoding.GetByteCount( fakeReadString ); break; } Contract.Assert(stream != null, "The XML stream with new encoding was not properly initialized for kind of input we had"); // we now have an initialized memory stream based on whatever source we had before _inTokenReader = new StreamTokenReader( new StreamReader( stream, encoding ) ); _inTokenSource = TokenSource.Other; } internal void GetTokens( TokenizerStream stream, int maxNum, bool endAfterKet ) { while (maxNum == -1 || stream.GetTokenCount() < maxNum) { int i = -1; byte ch; int cb = 0; bool inLiteral = false; bool inQuotedString = false; StringMaker m = _maker; m._outStringBuilder = null; m._outIndex = 0; BEGINNING: if (_inSavedCharacter != -1) { i = _inSavedCharacter; _inSavedCharacter = -1; } else switch (_inTokenSource) { case TokenSource.UnicodeByteArray: if (_inIndex + 1 >= _inSize) { stream.AddToken( -1 ); return; } i = (int)((_inBytes[_inIndex+1]<<8) + _inBytes[_inIndex]); _inIndex += 2; break; case TokenSource.UTF8ByteArray: if (_inIndex >= _inSize) { stream.AddToken( -1 ); return; } i = (int)(_inBytes[_inIndex++]); // single byte -- case, early out as we're done already if ((i & 0x80) == 0x00) break; // to decode the lead byte switch on the high nibble // shifted down so the switch gets dense integers switch ((i & 0xf0) >>4) { case 0x8: // 1000 (together these 4 make 10xxxxx) case 0x9: // 1001 case 0xa: // 1010 case 0xb: // 1011 // trail byte is an error throw new XmlSyntaxException( LineNo ); case 0xc: // 1100 (these two make 110xxxxx) case 0xd: // 1101 // two byte encoding (1 trail byte) i &= 0x1f; cb = 2; break; case 0xe: // 1110 (this gets us 1110xxxx) // three byte encoding (2 trail bytes) i &= 0x0f; cb = 3; break; case 0xf: // 1111 (and finally 1111xxxx) // 4 byte encoding is an error throw new XmlSyntaxException( LineNo ); } // at least one trail byte, fetch it if (_inIndex >= _inSize) throw new XmlSyntaxException (LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); ch = _inBytes[_inIndex++]; // must be trail byte encoding if ((ch & 0xc0) != 0x80) throw new XmlSyntaxException( LineNo ); i = (i<<6) | (ch & 0x3f); // done now if 2 byte encoding, otherwise go for 3 if (cb == 2) break; if (_inIndex >= _inSize) throw new XmlSyntaxException (LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); ch = _inBytes[_inIndex++]; // must be trail byte encoding if ((ch & 0xc0) != 0x80) throw new XmlSyntaxException( LineNo ); i = (i<<6) | (ch & 0x3f); break; case TokenSource.ASCIIByteArray: if (_inIndex >= _inSize) { stream.AddToken( -1 ); return; } i = (int)(_inBytes[_inIndex++]); break; case TokenSource.CharArray: if (_inIndex >= _inSize) { stream.AddToken( -1 ); return; } i = (int)(_inChars[_inIndex++]); break; case TokenSource.String: if (_inIndex >= _inSize) { stream.AddToken( -1 ); return; } i = (int)(_inString[_inIndex++]); break; case TokenSource.NestedStrings: if (_inNestedSize != 0) { if (_inNestedIndex < _inNestedSize) { i = _inNestedString[_inNestedIndex++]; break; } _inNestedSize = 0; } if (_inIndex >= _inSize) { stream.AddToken( -1 ); return; } i = (int)(_inString[_inIndex++]); if (i != '{') break; for (int istr=0; istr < _searchStrings.Length; istr++) { if (0==String.Compare(_searchStrings[istr], 0, _inString, _inIndex-1, _searchStrings[istr].Length, StringComparison.Ordinal)) { _inNestedString = _replaceStrings[istr]; _inNestedSize = _inNestedString.Length; _inNestedIndex = 1; i = _inNestedString[0]; _inIndex += _searchStrings[istr].Length - 1; break; } } break; default: i = _inTokenReader.Read(); if (i == -1) { stream.AddToken( -1 ); return; } break; } if (!inLiteral) { switch (i) { // skip whitespace case intSpace: case intTab: case intCR: goto BEGINNING; // count linefeeds case intLF: LineNo++; goto BEGINNING; case intOpenBracket: _inProcessingTag++; stream.AddToken( bra ); continue; case intCloseBracket: _inProcessingTag--; stream.AddToken( ket ); if (endAfterKet) return; continue; case intEquals: stream.AddToken( equals ); continue; case intSlash: if (_inProcessingTag != 0) { stream.AddToken( slash ); continue; } break; case intQuest: if (_inProcessingTag != 0) { stream.AddToken( quest ); continue; } break; case intBang: if (_inProcessingTag != 0) { stream.AddToken( bang ); continue; } break; case intDash: if (_inProcessingTag != 0) { stream.AddToken( dash ); continue; } break; case intQuote: inLiteral = true; inQuotedString = true; goto BEGINNING; } } else { switch (i) { case intOpenBracket: if (!inQuotedString) { _inSavedCharacter = i; stream.AddToken( cstr ); stream.AddString( this.GetStringToken() ); continue; } break; case intCloseBracket: case intEquals: case intSlash: if (!inQuotedString && _inProcessingTag != 0) { _inSavedCharacter = i; stream.AddToken( cstr ); stream.AddString( this.GetStringToken() ); continue; } break; case intQuote: if (inQuotedString) { stream.AddToken( cstr ); stream.AddString( this.GetStringToken() ); continue; } break; case intTab: case intCR: case intSpace: if (!inQuotedString) { stream.AddToken( cstr ); stream.AddString( this.GetStringToken() ); continue; } break; // count linefeeds case intLF: LineNo++; if (!inQuotedString) { stream.AddToken( cstr ); stream.AddString( this.GetStringToken() ); continue; } break; } } inLiteral = true; // add character to the string if (m._outIndex < StringMaker.outMaxSize) { // easy case m._outChars[m._outIndex++] = (char)i; } else { if (m._outStringBuilder == null) { // OK, first check if we have to init the StringBuilder m._outStringBuilder = new StringBuilder(); } // OK, copy from _outChars to _outStringBuilder m._outStringBuilder.Append(m._outChars, 0, StringMaker.outMaxSize); // reset _outChars pointer m._outChars[0] = (char)i; m._outIndex = 1; } goto BEGINNING; } } [Serializable] internal sealed class StringMaker { String[] aStrings; uint cStringsMax; uint cStringsUsed; public StringBuilder _outStringBuilder; public char[] _outChars; public int _outIndex; public const int outMaxSize = 512; static uint HashString(String str) { uint hash = 0; int l = str.Length; // rotate in string character for (int i=0; i < l; i++) { hash = (hash << 3) ^ (uint)str[i] ^ (hash >> 29); } return hash; } static uint HashCharArray(char[] a, int l) { uint hash = 0; // rotate in a character for (int i=0; i < l; i++) { hash = (hash << 3) ^ (uint)a[i] ^ (hash >> 29); } return hash; } public StringMaker() { cStringsMax = 2048; cStringsUsed = 0; aStrings = new String[cStringsMax]; _outChars = new char[outMaxSize]; } bool CompareStringAndChars(String str, char [] a, int l) { if (str.Length != l) return false; for (int i=0; i<l; i++) if (a[i] != str[i]) return false; return true; } public String MakeString() { uint hash; char[] a = _outChars; int l = _outIndex; // if we have a stringbuilder then we have to append... slow case if (_outStringBuilder != null) { _outStringBuilder.Append(_outChars, 0, _outIndex); return _outStringBuilder.ToString(); } // no stringbuilder, fast case, shareable string if (cStringsUsed > (cStringsMax / 4) * 3) { // we need to rehash uint cNewMax = cStringsMax * 2; String [] aStringsNew = new String[cNewMax]; for (int i=0; i < cStringsMax;i++) { if (aStrings[i] != null) { hash = HashString(aStrings[i]) % cNewMax; while (aStringsNew[hash] != null) { // slot full, skip if (++hash >= cNewMax) hash = 0; } aStringsNew[hash] = aStrings[i]; } } // all done, cutover to the new hash table cStringsMax = cNewMax; aStrings = aStringsNew; } hash = HashCharArray(a, l) % cStringsMax; String str; while ((str = aStrings[hash]) != null) { if (CompareStringAndChars(str, a, l)) return str; if (++hash >= cStringsMax) hash = 0; } str = new String(a,0,l); aStrings[hash] = str; cStringsUsed++; return str; } } //================================================================ // // private String GetStringToken () { return _maker.MakeString(); } internal interface ITokenReader { int Read(); } internal class StreamTokenReader : ITokenReader { internal StreamReader _in; internal int _numCharRead; internal StreamTokenReader(StreamReader input) { _in = input; _numCharRead = 0; } public virtual int Read() { int value = _in.Read(); if (value != -1) _numCharRead++; return value; } internal int NumCharEncountered { get { return _numCharRead; } } } } internal sealed class TokenizerShortBlock { internal short[] m_block = new short[16]; internal TokenizerShortBlock m_next = null; } internal sealed class TokenizerStringBlock { internal String[] m_block = new String[16]; internal TokenizerStringBlock m_next = null; } internal sealed class TokenizerStream { private int m_countTokens; private TokenizerShortBlock m_headTokens; private TokenizerShortBlock m_lastTokens; private TokenizerShortBlock m_currentTokens; private int m_indexTokens; private TokenizerStringBlock m_headStrings; private TokenizerStringBlock m_currentStrings; private int m_indexStrings; #if _DEBUG private bool m_bLastWasCStr; #endif internal TokenizerStream() { m_countTokens = 0; m_headTokens = new TokenizerShortBlock(); m_headStrings = new TokenizerStringBlock(); Reset(); } internal void AddToken( short token ) { if (m_currentTokens.m_block.Length <= m_indexTokens) { m_currentTokens.m_next = new TokenizerShortBlock(); m_currentTokens = m_currentTokens.m_next; m_indexTokens = 0; } m_countTokens++; m_currentTokens.m_block[m_indexTokens++] = token; } internal void AddString( String str ) { if (m_currentStrings.m_block.Length <= m_indexStrings) { m_currentStrings.m_next = new TokenizerStringBlock(); m_currentStrings = m_currentStrings.m_next; m_indexStrings = 0; } m_currentStrings.m_block[m_indexStrings++] = str; } internal void Reset() { m_lastTokens = null; m_currentTokens = m_headTokens; m_currentStrings = m_headStrings; m_indexTokens = 0; m_indexStrings = 0; #if _DEBUG m_bLastWasCStr = false; #endif } internal short GetNextFullToken() { if (m_currentTokens.m_block.Length <= m_indexTokens) { m_lastTokens = m_currentTokens; m_currentTokens = m_currentTokens.m_next; m_indexTokens = 0; } return m_currentTokens.m_block[m_indexTokens++]; } internal short GetNextToken() { short retval = (short)(GetNextFullToken() & 0x00FF); #if _DEBUG Contract.Assert( !m_bLastWasCStr, "CStr token not followed by GetNextString()" ); m_bLastWasCStr = (retval == Tokenizer.cstr); #endif return retval; } internal String GetNextString() { if (m_currentStrings.m_block.Length <= m_indexStrings) { m_currentStrings = m_currentStrings.m_next; m_indexStrings = 0; } #if _DEBUG m_bLastWasCStr = false; #endif return m_currentStrings.m_block[m_indexStrings++]; } internal void ThrowAwayNextString() { GetNextString(); } internal void TagLastToken( short tag ) { if (m_indexTokens == 0) m_lastTokens.m_block[m_lastTokens.m_block.Length-1] = (short)((ushort)m_lastTokens.m_block[m_lastTokens.m_block.Length-1] | (ushort)tag); else m_currentTokens.m_block[m_indexTokens-1] = (short)((ushort)m_currentTokens.m_block[m_indexTokens-1] | (ushort)tag); } internal int GetTokenCount() { return m_countTokens; } internal void GoToPosition( int position ) { Reset(); for (int count = 0; count < position; ++count) { if (GetNextToken() == Tokenizer.cstr) ThrowAwayNextString(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; namespace System.Runtime.Serialization.Json { #if FEATURE_LEGACYNETCF public #else internal #endif class JavaScriptObjectDeserializer { private const string DateTimePrefix = @"""\/Date("; private const int DateTimePrefixLength = 8; private const string DateTimeSuffix = @")\/"""; private const int DateTimeSuffixLength = 4; internal JavaScriptString _s; private bool _isDataContract; #if FEATURE_LEGACYNETCF public #else internal #endif object BasicDeserialize() { object result = this.DeserializeInternal(0); if (this._s.GetNextNonEmptyChar() != null) { throw new SerializationException(SR.Format(SR.ObjectDeserializer_IllegalPrimitive, this._s.ToString())); } return result; } internal JavaScriptObjectDeserializer(string input) : this(input, true) { } #if FEATURE_LEGACYNETCF public #else internal #endif JavaScriptObjectDeserializer(string input, bool isDataContract) { _s = new JavaScriptString(input); _isDataContract = isDataContract; } private object DeserializeInternal(int depth) { Nullable<Char> c = _s.GetNextNonEmptyChar(); if (c == null) { return null; } _s.MovePrev(); if (IsNextElementDateTime()) { return DeserializeStringIntoDateTime(); } if (IsNextElementObject(c)) { IDictionary<string, object> dict = DeserializeDictionary(depth); return dict; } if (IsNextElementArray(c)) { return DeserializeList(depth); } if (IsNextElementString(c)) { return DeserializeString(); } return DeserializePrimitiveObject(); } private IList DeserializeList(int depth) { IList list = new List<object>(); Nullable<Char> c = _s.MoveNext(); if (c != '[') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, '['))); } bool expectMore = false; while ((c = _s.GetNextNonEmptyChar()) != null && c != ']') { _s.MovePrev(); object o = DeserializeInternal(depth); list.Add(o); expectMore = false; c = _s.GetNextNonEmptyChar(); if (c == ']') { break; } expectMore = true; if (c != ',') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ','))); } } if (expectMore) { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_InvalidArrayExtraComma))); } if (c != ']') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ']'))); } return list; } private IDictionary<string, object> DeserializeDictionary(int depth) { IDictionary<string, object> dictionary = null; Nullable<Char> c = _s.MoveNext(); if (c != '{') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, '{'))); } bool encounteredFirstMember = false; while ((c = _s.GetNextNonEmptyChar()) != null) { _s.MovePrev(); if (c == ':') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_InvalidMemberName))); } string memberName = null; if (c != '}') { memberName = DeserializeMemberName(); if (String.IsNullOrEmpty(memberName)) { throw new SerializationException (_s.GetDebugString(SR.Format(SR.ObjectDeserializer_InvalidMemberName))); } c = _s.GetNextNonEmptyChar(); if (c != ':') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ':'))); } } if (dictionary == null) { dictionary = new Dictionary<string, object>(); if (String.IsNullOrEmpty(memberName)) { c = _s.GetNextNonEmptyChar(); break; } } object propVal = DeserializeInternal(depth); //Ignore the __type attribute when its not the first element in the dictionary if (!encounteredFirstMember || (memberName != null && !memberName.Equals(JsonGlobals.ServerTypeString))) { if (dictionary.ContainsKey(memberName)) { throw new SerializationException(SR.Format(SR.JsonDuplicateMemberInInput, memberName)); } dictionary[memberName] = propVal; //Added the first member from the dictionary encounteredFirstMember = true; } c = _s.GetNextNonEmptyChar(); if (c == '}') { break; } if (c != ',') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, ','))); } } if (c != '}') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnexpectedToken, c, '}'))); } return dictionary; } private string DeserializeMemberName() { Nullable<Char> c = _s.GetNextNonEmptyChar(); if (c == null) { return null; } _s.MovePrev(); if (IsNextElementString(c)) { return DeserializeString(); } return DeserializePrimitiveToken(); } private object DeserializePrimitiveObject() { string input = DeserializePrimitiveToken(); if (input.Equals("null")) { return null; } if (input.Equals(Globals.True)) { return true; } if (input.Equals(Globals.False)) { return false; } if (input.Equals(JsonGlobals.PositiveInf)) { return float.PositiveInfinity; } if (input.Equals(JsonGlobals.NegativeInf)) { return float.NegativeInfinity; } bool hasDecimalPoint = input.IndexOfAny(JsonGlobals.FloatingPointCharacters) >= 0; if (!hasDecimalPoint) { int parseInt; if (Int32.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseInt)) { return parseInt; } long parseLong; if (Int64.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseLong)) { return parseLong; } if (_isDataContract) { return JavaScriptObjectDeserializer.ParseJsonNumberAsDoubleOrDecimal(input); } } //Ensure that the number is a valid JSON number. object ret = JavaScriptObjectDeserializer.ParseJsonNumberAsDoubleOrDecimal(input); if (ret.GetType() == Globals.TypeOfString) { throw new SerializationException(SR.Format(SR.ObjectDeserializer_IllegalPrimitive, input)); } // return floating point number as string in DataContract case. return _isDataContract ? input : ret; } private string DeserializePrimitiveToken() { StringBuilder sb = new StringBuilder(); Nullable<Char> c = null; while ((c = _s.MoveNext()) != null) { if (Char.IsLetterOrDigit(c.Value) || c.Value == '.' || c.Value == '-' || c.Value == '_' || c.Value == '+') { sb.Append(c); } else { _s.MovePrev(); break; } } return sb.ToString(); } internal string DeserializeString() { StringBuilder sb = new StringBuilder(); bool escapedChar = false; Nullable<Char> c = _s.MoveNext(); Char quoteChar = CheckQuoteChar(c); while ((c = _s.MoveNext()) != null) { if (c == '\\') { if (escapedChar) { sb.Append('\\'); escapedChar = false; } else { escapedChar = true; } continue; } if (escapedChar) { AppendCharToBuilder(c, sb); escapedChar = false; } else { if (c == quoteChar) { return sb.ToString(); } sb.Append(c); } } throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_UnterminatedString))); } private void AppendCharToBuilder(char? c, StringBuilder sb) { if (c == '"' || c == '\'' || c == '/') { sb.Append(c); } else if (c == 'b') { sb.Append('\b'); } else if (c == 'f') { sb.Append('\f'); } else if (c == 'n') { sb.Append('\n'); } else if (c == 'r') { sb.Append('\r'); } else if (c == 't') { sb.Append('\t'); } else if (c == 'u') { sb.Append((char)int.Parse(_s.MoveNext(4), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } else { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_BadEscape))); } } private char CheckQuoteChar(char? c) { Char quoteChar = '"'; if (c == '\'') { quoteChar = c.Value; } else if (c != '"') { throw new SerializationException(_s.GetDebugString(SR.Format(SR.ObjectDeserializer_StringNotQuoted))); } return quoteChar; } private object DeserializeStringIntoDateTime() { string dateTimeValue = DeserializeString(); string ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8); long millisecondsSinceUnixEpoch; DateTimeKind dateTimeKind = DateTimeKind.Utc; int indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1); if (indexOfTimeZoneOffset == -1) { indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1); } if (indexOfTimeZoneOffset != -1) { dateTimeKind = DateTimeKind.Local; ticksvalue = ticksvalue.Substring(0, indexOfTimeZoneOffset); } try { millisecondsSinceUnixEpoch = Int64.Parse(ticksvalue, NumberStyles.Integer, CultureInfo.InvariantCulture); } catch (ArgumentException exception) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception)); } catch (FormatException exception) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception)); } catch (OverflowException exception) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception)); } // Convert from # millseconds since epoch to # of 100-nanosecond units, which is what DateTime understands long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks; try { DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc); switch (dateTimeKind) { case DateTimeKind.Local: dateTime = dateTime.ToLocalTime(); break; case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified); break; case DateTimeKind.Utc: default: break; } // This string could be serialized from DateTime or String, keeping both until DataContract information is available return Tuple.Create<DateTime, string>(dateTime, dateTimeValue); } catch (ArgumentException exception) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception)); } } private static bool IsNextElementArray(Nullable<Char> c) { return c == '['; } private bool IsNextElementDateTime() { String next = _s.MoveNext(DateTimePrefixLength); if (next != null) { _s.MovePrev(DateTimePrefixLength); return String.Equals(next, DateTimePrefix, StringComparison.Ordinal); } return false; } private static bool IsNextElementObject(Nullable<Char> c) { return c == '{'; } private static bool IsNextElementString(Nullable<Char> c) { return c == '"' || c == '\''; } internal static object ParseJsonNumberAsDoubleOrDecimal(string input) { decimal parseDecimal; if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseDecimal) && parseDecimal != 0) { return parseDecimal; } double parseDouble; if (Double.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out parseDouble)) { return parseDouble; } return input; } } } // File provided for Microsoft ASP.NET AJAX. // Copyright (c) Microsoft Corporation. All rights reserved.
// AdminUserCollectionsModal.cs // using System; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; using afung.MangaWeb3.Client.Admin.Module; using afung.MangaWeb3.Client.Modal; using afung.MangaWeb3.Client.Widget; using afung.MangaWeb3.Common; using jQueryApi; namespace afung.MangaWeb3.Client.Admin.Modal { public class AdminUserCollectionsModal : ModalBase { private static AdminUserCollectionsModal instance = null; private int uid; private string username; private string[] collectionNames; private Pagination pagination; private CollectionUserJson[] data; private int currentPage; private bool submittingForm; private AdminUserCollectionsModal() : base("admin", "admin-user-collections-modal") { } protected override void Initialize() { pagination = new Pagination(jQuery.Select("#admin-user-collections-pagination"), ChangePage, GetTotalPage, "right"); jQuery.Select("#admin-user-collections-form").Submit(SubmitAddForm); jQuery.Select("#admin-user-collections-add-submit").Click(SubmitAddForm); jQuery.Select("#admin-user-collections-delete-btn").Click(DeleteButtonClicked); jQuery.Select("#admin-user-collections-allow-btn").Click(AllowButtonClicked); jQuery.Select("#admin-user-collections-deny-btn").Click(DenyButtonClicked); Utility.FixDropdownTouch(jQuery.Select("#admin-user-collections-action-dropdown")); } private int GetTotalPage() { if (data == null || data.Length == 0) { return 1; } return Math.Ceil(data.Length / Environment.ModalElementsPerPage); } public static void ShowDialog(int uid) { if (instance == null) { instance = new AdminUserCollectionsModal(); } instance.InternalShow(uid); } public void InternalShow(int uid) { this.uid = uid; Refresh(); } [AlternateSignature] public extern void Refresh(JsonResponse response); public void Refresh() { AdminCollectionsUsersGetRequest request = new AdminCollectionsUsersGetRequest(); request.t = 1; request.id = uid; Request.Send(request, GetRequestSuccess); jQuery.Select("#admin-user-collections-tbody").Children().Remove(); Template.Get("admin", "loading-trow", true).AppendTo(jQuery.Select("#admin-user-collections-tbody")); } [AlternateSignature] private extern void GetRequestSuccess(JsonResponse response); private void GetRequestSuccess(AdminCollectionsUsersGetResponse response) { Show(); jQuery.Select("#admin-user-collections-name").Text(username = response.name); ((BootstrapTypeahead)((jQueryBootstrap)jQuery.Select("#admin-user-collections-add-collection").Value("")).Typeahead().GetDataValue("typeahead")).Source = collectionNames = response.names; data = response.data; ChangePage(1); pagination.Refresh(true); } private void ChangePage(int page) { currentPage = page; jQuery.Select("#admin-user-collections-tbody").Children().Remove(); if (data.Length == 0) { Template.Get("admin", "noitem-trow", true).AppendTo(jQuery.Select("#admin-user-collections-tbody")); } for (int i = (page - 1) * Environment.ModalElementsPerPage; i < data.Length && i < page * Environment.ModalElementsPerPage; i++) { jQueryObject row = Template.Get("admin", "admin-user-collections-trow", true).AppendTo(jQuery.Select("#admin-user-collections-tbody")); jQuery.Select(".admin-user-collections-checkbox", row).Value(data[i].cid.ToString()); jQuery.Select(".admin-user-collections-collection", row).Text(data[i].collectionName); jQuery.Select(".admin-user-collections-access", row).Text(Strings.Get(data[i].access ? "Yes" : "No")).AddClass(data[i].access ? "label-success" : ""); } Show(); } private void SubmitAddForm(jQueryEvent e) { e.PreventDefault(); string collectionName = jQuery.Select("#admin-user-collections-add-collection").GetValue(); if (collectionNames.Contains(collectionName) && !submittingForm) { submittingForm = true; AdminCollectionUserAddRequest request = new AdminCollectionUserAddRequest(); request.username = username; request.collectionName = collectionName; request.access = jQuery.Select("#admin-user-collections-add-access").GetValue() == "true"; Request.Send(request, SubmitAddFormSuccess, SubmitAddFormFailure); } } private void SubmitAddFormSuccess(JsonResponse response) { submittingForm = false; Refresh(); } private void SubmitAddFormFailure(Exception error) { submittingForm = false; ErrorModal.ShowError(error.ToString()); } private void AllowButtonClicked(jQueryEvent e) { e.PreventDefault(); InternalAccessButtonClicked(true); } private void DenyButtonClicked(jQueryEvent e) { e.PreventDefault(); InternalAccessButtonClicked(false); } private void InternalAccessButtonClicked(bool access) { int[] ids = GetSelectedIds(); if (ids.Length > 0) { AdminCollectionsUsersAccessRequest request = new AdminCollectionsUsersAccessRequest(); request.t = 1; request.id = uid; request.ids = ids; request.access = access; Request.Send(request, Refresh); } } private void DeleteButtonClicked(jQueryEvent e) { e.PreventDefault(); int[] ids = GetSelectedIds(); if (ids.Length > 0) { ConfirmModal.Show(Strings.Get("DeleteItemsConfirm"), DeleteConfirm); } } private void DeleteConfirm(bool confirm) { int[] ids = GetSelectedIds(); if (confirm && ids.Length > 0) { AdminCollectionsUsersDeleteRequest request = new AdminCollectionsUsersDeleteRequest(); request.t = 1; request.id = uid; request.ids = ids; Request.Send(request, Refresh); } } private int[] GetSelectedIds() { return Utility.GetSelectedCheckboxIds("admin-user-collections-checkbox"); } } }
using System; using System.Data.Common; using System.IO; using System.Threading; using System.Threading.Tasks; #if CLUSTERING_ADONET namespace Orleans.Clustering.AdoNet.Storage #elif PERSISTENCE_ADONET namespace Orleans.Persistence.AdoNet.Storage #elif REMINDERS_ADONET namespace Orleans.Reminders.AdoNet.Storage #elif TESTER_SQLUTILS namespace Orleans.Tests.SqlUtils #else // No default namespace intentionally to cause compile errors if something is not defined #endif { /// <summary> /// This is a chunked read implementation for ADO.NET providers which do /// not otherwise implement <see cref="DbDataReader.GetStream(int)"/> natively. /// </summary> public class OrleansRelationalDownloadStream : Stream { /// <summary> /// A cached task as if there are multiple rounds of reads, it is likely /// the bytes read is the same. This saves one allocation. /// </summary> private Task<int> lastTask; /// <summary> /// The reader to use to read from the database. /// </summary> private DbDataReader reader; /// <summary> /// The position in the overall stream. /// </summary> private long position; /// <summary> /// The column ordinal to read from. /// </summary> private readonly int ordinal; /// <summary> /// The total number of bytes in the column. /// </summary> private readonly long totalBytes; /// <summary> /// The internal byte array buffer size used in .CopyToAsync. /// This size is just a guess and is likely dependent on the database /// tuning settings (e.g. read_buffer_size in case of MySQL). /// </summary> private const int InternalReadBufferLength = 4092; /// <summary> /// The default constructor. /// </summary> /// <param name="reader">The reader to use to read from the database.</param> /// <param name="ordinal">The column ordinal to read from.</param> public OrleansRelationalDownloadStream(DbDataReader reader, int ordinal) { this.reader = reader; this.ordinal = ordinal; //This return the total length of the column pointed by the ordinal. totalBytes = reader.GetBytes(ordinal, 0, null, 0, 0); } /// <summary> /// Can the stream be read. /// </summary> public override bool CanRead { get { return ((reader != null) && (!reader.IsClosed)); } } /// <summary> /// Are seeks supported. /// </summary> /// <remarks>Returns <em>FALSE</em>.</remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Can the stream timeout. /// </summary> /// <remarks>Returns <em>FALSE</em>.</remarks> public override bool CanTimeout { get { return true; } } /// <summary> /// Can the stream write. /// </summary> /// <remarks>Returns <em>FALSE</em>.</remarks> public override bool CanWrite { get { return false; } } /// <summary> /// The length of the stream. /// </summary> public override long Length { get { return totalBytes; } } /// <summary> /// The current position in the stream. /// </summary> public override long Position { get { return position; } set { throw new NotSupportedException(); } } /// <summary> /// Throws <exception cref="NotSupportedException"/>. /// </summary> /// <exception cref="NotSupportedException" />. public override void Flush() { throw new NotSupportedException(); } /// <summary> /// Reads the stream. /// </summary> /// <param name="buffer">The buffer to read to.</param> /// <param name="offset">The offset to the buffer to stat reading.</param> /// <param name="count">The count of bytes to read to.</param> /// <returns>The number of actual bytes read from the stream.</returns> public override int Read(byte[] buffer, int offset, int count) { //This will throw with the same parameter names if the parameters are not valid. ValidateReadParameters(buffer, offset, count); try { int length = Math.Min(count, (int)(totalBytes - position)); long bytesRead = 0; if(length > 0) { bytesRead = reader.GetBytes(ordinal, position, buffer, offset, length); position += bytesRead; } return (int)bytesRead; } catch(DbException dex) { //It's not OK to throw non-IOExceptions from a Stream. throw new IOException(dex.Message, dex); } } /// <summary> /// Reads the stream. /// </summary> /// <param name="buffer">The buffer to read to.</param> /// <param name="offset">The offset to the buffer to stat reading.</param> /// <param name="count">The count of bytes to read to.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The number of actual bytes read from the stream.</returns> public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { //This will throw with the same parameter names if the parameters are not valid. ValidateReadParameters(buffer, offset, count); if(cancellationToken.IsCancellationRequested) { var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); tcs.SetCanceled(); return tcs.Task; } try { //The last used task is saved in order to avoid one allocation when the number of bytes read //will likely be the same multiple times. int bytesRead = Read(buffer, offset, count); var ret = lastTask != null && bytesRead == lastTask.Result ? lastTask : (lastTask = Task.FromResult(bytesRead)); return ret; } catch(Exception e) { //Due to call to Read, this is for sure a IOException and can be thrown out. var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); tcs.SetException(e); return tcs.Task; } } /// <summary> /// A buffer copy operation from database to the destination stream. /// </summary> /// <param name="destination">The destination stream.</param> /// <param name="bufferSize">The buffer size.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <remarks>Reading from the underlying ADO.NET provider is currently synchro</remarks> public override async Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { if(!cancellationToken.IsCancellationRequested) { byte[] buffer = new byte[InternalReadBufferLength]; int bytesRead; while((bytesRead = Read(buffer, 0, buffer.Length)) > 0) { if(cancellationToken.IsCancellationRequested) { break; } await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } } /// <summary> /// Throws <exception cref="NotSupportedException"/>. /// </summary> /// <param name="offset">The offset to the stream.</param> /// <param name="origin">The origin.</param> /// <returns>Throws <exception cref="NotSupportedException"/>.</returns> /// <exception cref="NotSupportedException" />. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Throws <exception cref="NotSupportedException"/>. /// </summary> /// <returns>Throws <exception cref="NotSupportedException"/>.</returns> /// <exception cref="NotSupportedException" />. public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Throws <exception cref="NotSupportedException"/>. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="offset">The offset to the buffer.</param> /// <param name="count">The count of bytes to read.</param> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// <summary> /// Dispose. /// </summary> /// <param name="disposing">Whether is disposing or not.</param> protected override void Dispose(bool disposing) { if(disposing) { reader = null; } base.Dispose(disposing); } /// <summary> /// Checks the parameters passed into a ReadAsync() or Read() are valid. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> private static void ValidateReadParameters(byte[] buffer, int offset, int count) { if(buffer == null) { throw new ArgumentNullException("buffer"); } if(offset < 0) { throw new ArgumentOutOfRangeException("offset"); } if(count < 0) { throw new ArgumentOutOfRangeException("count"); } try { if(checked(offset + count) > buffer.Length) { throw new ArgumentException("Invalid offset length"); } } catch(OverflowException) { throw new ArgumentException("Invalid offset length"); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { /// <summary> /// SpinLock unit tests /// </summary> public class SpinLockTests { [Fact] public static void EnterExit() { var sl = new SpinLock(); Assert.True(sl.IsThreadOwnerTrackingEnabled); for (int i = 0; i < 4; i++) { Assert.False(sl.IsHeld); Assert.False(sl.IsHeldByCurrentThread); bool lockTaken = false; if (i % 2 == 0) sl.Enter(ref lockTaken); else sl.TryEnter(ref lockTaken); Assert.True(lockTaken); Assert.True(sl.IsHeld); Assert.True(sl.IsHeldByCurrentThread); Task.Factory.StartNew(() => { Assert.True(sl.IsHeld); Assert.False(sl.IsHeldByCurrentThread); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).GetAwaiter().GetResult(); sl.Exit(); } } /// <summary> /// Run all SpinLock tests /// </summary> /// <returns>True if all tests passed, false if at least one test failed</returns> [Fact] [OuterLoop] public static void RunSpinLockTests() { for (int i = 0; i < 2; i++) { bool b; if (i == 0) { Debug.WriteLine("NO THREAD IDS -- new SpinLock(true)"); b = true; } else { Debug.WriteLine("WITH THREAD IDS -- new SpinLock(false)"); b = false; } RunSpinLockTest0_Enter(2, b); RunSpinLockTest0_Enter(128, b); RunSpinLockTest0_Enter(256, b); RunSpinLockTest1_TryEnter(2, b); RunSpinLockTest1_TryEnter(128, b); RunSpinLockTest1_TryEnter(256, b); RunSpinLockTest2_TryEnter(2, b); RunSpinLockTest2_TryEnter(128, b); RunSpinLockTest2_TryEnter(256, b); } } [Fact] public static void RunSpinLockTests_NegativeTests() { for (int i = 0; i < 2; i++) { bool b; if (i == 0) { Debug.WriteLine("NO THREAD IDS -- new SpinLock(true)"); b = true; } else { Debug.WriteLine("WITH THREAD IDS -- new SpinLock(false)"); b = false; } RunSpinLockTest3_TryEnter(b); RunSpinLockTest4_Exit(b); } } /// <summary> /// Test SpinLock.Enter by launching n threads that increment a variable inside a critical section /// the final count variable must be equal to n /// </summary> /// <param name="threadsCount">Number of threads that call enter/exit</param> /// <returns>True if succeeded, false otherwise</returns> private static void RunSpinLockTest0_Enter(int threadsCount, bool enableThreadIDs) { // threads array Task[] threads = new Task[threadsCount]; //spinlock object SpinLock slock = new SpinLock(enableThreadIDs); // succeeded threads counter int succeeded = 0; // Semaphore used to make sure that there is no other threads in the critical section SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); for (int i = 0; i < threadsCount; i++) { threads[i] = Task.Run(delegate () { bool lockTaken = false; try { slock.Enter(ref lockTaken); //use semaphore to make sure that no other thread inside the critical section if (!semaphore.Wait(0)) { // This mean that there is another thread in the critical section return; } succeeded++; if (slock.IsThreadOwnerTrackingEnabled && !slock.IsHeldByCurrentThread) { // lock is obtained successfully succeeded--; } } catch { // decrement the count in case of exception succeeded--; } finally { semaphore.Release(); if (lockTaken) { slock.Exit(); } } }); } // wait all threads for (int i = 0; i < threadsCount; i++) { threads[i].Wait(); } // count must be equal to the threads count Assert.Equal(threadsCount, succeeded); } /// <summary> /// Test SpinLock.TryEnter() by launching n threads, each one calls TryEnter, the succeeded threads increment /// a counter variable and failed threads increment failed variable, count + failed must be equal to n /// </summary> /// <param name="threadsCount">Number of threads that call enter/exit</param> /// <returns>True if succeeded, false otherwise</returns> private static void RunSpinLockTest1_TryEnter(int threadsCount, bool enableThreadIDs) { for (int j = 0; j < 2; j++) { bool useMemoryBarrier = j == 0; Task[] threads = new Task[threadsCount]; SpinLock slock = new SpinLock(enableThreadIDs); int succeeded = 0; int failed = 0; // Run threads for (int i = 0; i < threadsCount; i++) { threads[i] = Task.Run(delegate () { bool lockTaken = false; slock.TryEnter(ref lockTaken); if (lockTaken) { // Increment succeeded counter Interlocked.Increment(ref succeeded); slock.Exit(useMemoryBarrier); } else { // Increment failed counter Interlocked.Increment(ref failed); } }); } // Wait all threads for (int i = 0; i < threadsCount; i++) { threads[i].Wait(); } // succeeded + failed must be equal to the threads count. Assert.Equal(threadsCount, succeeded + failed); } } /// <summary> /// Test SpinLock.TryEnter(Timespan) by generating random timespan milliseconds /// </summary> /// <param name="threadsCount">Number of threads that call enter/exit</param> /// <returns>True if succeeded, false otherwise</returns> private static void RunSpinLockTest2_TryEnter(int threadsCount, bool enableThreadIDs) { for (int j = 0; j < 2; j++) { bool useMemoryBarrier = j == 0; Task[] threads = new Task[threadsCount]; SpinLock slock = new SpinLock(enableThreadIDs); int succeeded = 0; int failed = 0; // Run threads for (int i = 0; i < threadsCount; i++) { threads[i] = new Task(delegate (object x) { // Generate random timespan bool lockTaken = false; TimeSpan time = TimeSpan.FromMilliseconds(20); slock.TryEnter(time, ref lockTaken); if (lockTaken) { // add some delay in the critical section Task.WaitAll(Task.Delay(15)); Interlocked.Increment(ref succeeded); slock.Exit(useMemoryBarrier); } else { // Failed to get the lock within the timeout Interlocked.Increment(ref failed); } }, i); threads[i].Start(TaskScheduler.Default); } // Wait all threads for (int i = 0; i < threadsCount; i++) { threads[i].Wait(); } // succeeded + failed must be equal to the threads count. Assert.Equal(threadsCount, succeeded + failed); } } /// <summary> /// Test TryEnter invalid cases /// </summary> /// <returns>True if succeeded, false otherwise</returns> private static void RunSpinLockTest3_TryEnter(bool enableThreadIDs) { SpinLock slock = new SpinLock(enableThreadIDs); bool lockTaken = false; #region Recursive lock if (enableThreadIDs) // only valid if thread IDs are on { // Test recursive locks slock.Enter(ref lockTaken); Assert.True(lockTaken); Assert.Throws<LockRecursionException>(() => { bool dummy = false; slock.Enter(ref dummy); }); slock.Exit(); Assert.False(slock.IsHeldByCurrentThread); } #endregion #region timeout > int.max // Test invalid argument handling, too long timeout Assert.Throws<ArgumentOutOfRangeException>(() => { bool lt = false; slock.TryEnter(TimeSpan.MaxValue, ref lt); }); #endregion timeout > int.max #region Timeout > int.max // Test invalid argument handling, timeout < -1 Assert.Throws<ArgumentOutOfRangeException>(() => { bool lt = false; slock.TryEnter(-2, ref lt); }); #endregion Timeout > int.max } /// <summary> /// Test Exit /// </summary> /// <returns>True if succeeded, false otherwise</returns> private static void RunSpinLockTest4_Exit(bool enableThreadIDs) { SpinLock slock = new SpinLock(enableThreadIDs); bool lockTaken = false; slock.Enter(ref lockTaken); slock.Exit(); if (enableThreadIDs) { Assert.False(slock.IsHeldByCurrentThread); Assert.Throws<SynchronizationLockException>(() => slock.Exit(true)); Assert.Throws<SynchronizationLockException>(() => slock.Exit(false)); } else { Assert.False(slock.IsHeld); } } [Fact] public static void RunSpinLockTestExceptions() { SpinLock slock = new SpinLock(); bool isTaken = true; Assert.Throws<ArgumentException>(() => slock.Enter(ref isTaken)); // Failure Case: Enter didn't throw AE when isTaken is true slock = new SpinLock(false); Assert.Throws<InvalidOperationException>(() => { bool iHeld = slock.IsHeldByCurrentThread; }); // Failure Case: IsHeldByCurrentThread didn't throw IOE when the thread tracking is disabled } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.IO; using System.Text; using System.Collections; #if CLR_2_0 || CLR_4_0 using System.Collections.Generic; #endif namespace NUnitLite.Runner { /// <summary> /// The CommandLineOptions class parses and holds the values of /// any options entered at the command line. /// </summary> public class CommandLineOptions { private string optionChars; private static string NL = NUnit.Env.NewLine; private int port = -1; private bool wait = false; private bool noheader = false; private bool help = false; private bool full = false; private bool explore = false; private bool labelTestsInOutput = false; private string exploreFile; private string resultFile; private string resultFormat; private string outFile; private string includeCategory; private string excludeCategory; private bool error = false; private StringList tests = new StringList(); private StringList invalidOptions = new StringList(); private StringList parameters = new StringList(); #region Properties /// <summary> /// Gets a value indicating whether the 'wait' option was used. /// </summary> public bool Wait { get { return wait; } } /// <summary> /// Gets a value indicating whether the 'nologo' option was used. /// </summary> public bool NoHeader { get { return noheader; } } /// <summary> /// Gets a value indicating whether the 'help' option was used. /// </summary> public bool ShowHelp { get { return help; } } /// <summary> /// Gets a list of all tests specified on the command line /// </summary> public string[] Tests { get { return (string[])tests.ToArray(); } } /// <summary> /// Gets a value indicating whether a full report should be displayed /// </summary> public bool Full { get { return full; } } /// <summary> /// Gets a value indicating whether tests should be listed /// rather than run. /// </summary> public bool Explore { get { return explore; } } /// <summary> /// Gets the name of the file to be used for listing tests /// </summary> public string ExploreFile { get { return ExpandToFullPath(exploreFile.Length < 1 ? "tests.xml" : exploreFile); } } /// <summary> /// Gets the name of the file to be used for test results /// </summary> public string ResultFile { get { return ExpandToFullPath(resultFile); } } /// <summary> /// Gets the format to be used for test results /// </summary> public string ResultFormat { get { return resultFormat; } } /// <summary> /// Gets the full path of the file to be used for output /// </summary> public string OutFile { get { return ExpandToFullPath(outFile); } } /// <summary> /// The port to create a TCP connection to and write test output /// </summary> /// <value>The port.</value> public int Port { get { return port; } } /// <summary> /// Gets the list of categories to include /// </summary> public string Include { get { return includeCategory; } } /// <summary> /// Gets the list of categories to exclude /// </summary> public string Exclude { get { return excludeCategory; } } /// <summary> /// Gets a flag indicating whether each test should /// be labeled in the output. /// </summary> public bool LabelTestsInOutput { get { return labelTestsInOutput; } } private string ExpandToFullPath(string path) { if (path == null) return null; #if NETCF return Path.Combine(NUnit.Env.DocumentFolder, path); #else return Path.GetFullPath(path); #endif } /// <summary> /// Gets the test count /// </summary> public int TestCount { get { return tests.Count; } } #endregion /// <summary> /// Construct a CommandLineOptions object using default option chars /// </summary> public CommandLineOptions() { this.optionChars = System.IO.Path.DirectorySeparatorChar == '/' ? "-" : "/-"; } /// <summary> /// Construct a CommandLineOptions object using specified option chars /// </summary> /// <param name="optionChars"></param> public CommandLineOptions(string optionChars) { this.optionChars = optionChars; } /// <summary> /// Parse command arguments and initialize option settings accordingly /// </summary> /// <param name="args">The argument list</param> public void Parse(params string[] args) { foreach( string arg in args ) { if (optionChars.IndexOf(arg[0]) >= 0 ) ProcessOption(arg); else ProcessParameter(arg); } } /// <summary> /// Gets the parameters provided on the commandline /// </summary> public string[] Parameters { get { return (string[])parameters.ToArray(); } } private void ProcessOption(string opt) { int pos = opt.IndexOfAny( new char[] { ':', '=' } ); string val = string.Empty; if (pos >= 0) { val = opt.Substring(pos + 1); opt = opt.Substring(0, pos); } switch (opt.Substring(1)) { case "wait": wait = true; break; case "port": port = int.Parse (val); break; case "noheader": case "noh": noheader = true; break; case "help": case "h": help = true; break; case "run": case "test": tests.Add(val); break; case "full": full = true; break; case "explore": explore = true; exploreFile = val; break; case "xml": case "result": resultFile = ExpandToFullPath (val); break; case "format": resultFormat = val; if (resultFormat != "nunit3" && resultFormat != "nunit2") error = true; break; case "out": outFile = val; break; case "labels": labelTestsInOutput = true; break; case "include": includeCategory = val; break; case "exclude": excludeCategory = val; break; default: error = true; invalidOptions.Add(opt); break; } } private void ProcessParameter(string param) { parameters.Add(param); } /// <summary> /// Gets a value indicating whether there was an error in parsing the options. /// </summary> /// <value><c>true</c> if error; otherwise, <c>false</c>.</value> public bool Error { get { return error; } } /// <summary> /// Gets the error message. /// </summary> /// <value>The error message.</value> public string ErrorMessage { get { StringBuilder sb = new StringBuilder(); foreach (string opt in invalidOptions) sb.Append( "Invalid option: " + opt + NL ); if (resultFormat != null && resultFormat != "nunit3" && resultFormat != "nunit2") sb.Append("Invalid result format: " + resultFormat + NL); return sb.ToString(); } } /// <summary> /// Gets the help text. /// </summary> /// <value>The help text.</value> public string HelpText { get { StringBuilder sb = new StringBuilder(); #if PocketPC || WindowsCE || NETCF || SILVERLIGHT string name = "NUnitLite"; #else string name = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; #endif sb.Append("Usage: " + name + " [assemblies] [options]" + NL + NL); sb.Append("Runs a set of NUnitLite tests from the console." + NL + NL); sb.Append("You may specify one or more test assemblies by name, without a path or" + NL); sb.Append("extension. They must be in the same in the same directory as the exe" + NL); sb.Append("or on the probing path. If no assemblies are provided, tests in the" + NL); sb.Append("executing assembly itself are run." + NL + NL); sb.Append("Options:" + NL); sb.Append(" -test:testname Provides the name of a test to run. This option may be" + NL); sb.Append(" repeated. If no test names are given, all tests are run." + NL + NL); sb.Append(" -out:FILE File to which output is redirected. If this option is not" + NL); sb.Append(" used, output is to the Console, which means it is lost" + NL); sb.Append(" on devices without a Console." + NL + NL); sb.Append(" -full Prints full report of all test results." + NL + NL); sb.Append(" -result:FILE File to which the xml test result is written." + NL + NL); sb.Append(" -format:FORMAT Format in which the result is to be written. FORMAT must be" + NL); sb.Append(" either nunit3 or nunit2. The default is nunit3." + NL + NL); sb.Append(" -explore:FILE If provided, this option indicates that the tests" + NL); sb.Append(" should be listed rather than executed. They are listed" + NL); sb.Append(" to the specified file in XML format." + NL); sb.Append(" -help,-h Displays this help" + NL + NL); sb.Append(" -noheader,-noh Suppresses display of the initial message" + NL + NL); sb.Append(" -labels Displays the name of each test when it starts" + NL + NL); sb.Append(" -wait Waits for a key press before exiting" + NL + NL); sb.Append("Notes:" + NL); sb.Append(" * File names may be listed by themselves, with a relative path or " + NL); sb.Append(" using an absolute path. Any relative path is based on the current " + NL); sb.Append(" directory or on the Documents folder if running on a under the " +NL); sb.Append(" compact framework." + NL + NL); if (System.IO.Path.DirectorySeparatorChar != '/') sb.Append(" * On Windows, options may be prefixed by a '/' character if desired" + NL + NL); sb.Append(" * Options that take values may use an equal sign or a colon" + NL); sb.Append(" to separate the option from its value." + NL + NL); return sb.ToString(); } } #if CLR_2_0 || CLR_4_0 class StringList : List<string> { } #else class StringList : ArrayList { public new string[] ToArray() { return (string[])ToArray(typeof(string)); } } #endif } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Collections { [ContractClass(typeof(CDictionary))] public interface IDictionary : ICollection, IEnumerable { // Summary: // Gets a value indicating whether the System.Collections.IDictionary object // has a fixed size. // // Returns: // true if the System.Collections.IDictionary object has a fixed size; otherwise, // false. bool IsFixedSize { get; } // // Summary: // Gets a value indicating whether the System.Collections.IDictionary object // is read-only. // // Returns: // true if the System.Collections.IDictionary object is read-only; otherwise, // false. bool IsReadOnly { get; } // // Summary: // Gets an System.Collections.ICollection object containing the keys of the // System.Collections.IDictionary object. // // Returns: // An System.Collections.ICollection object containing the keys of the System.Collections.IDictionary // object. [Pure] [Reads(ReadsAttribute.Reads.Owned)] ICollection Keys { get; } // // Summary: // Gets an System.Collections.ICollection object containing the values in the // System.Collections.IDictionary object. // // Returns: // An System.Collections.ICollection object containing the values in the System.Collections.IDictionary // object. [Pure] [Reads(ReadsAttribute.Reads.Owned)] ICollection Values { get; } // Summary: // Gets or sets the element with the specified key. // // Parameters: // key: // The key of the element to get or set. // // Returns: // The element with the specified key. // // Exceptions: // System.NotSupportedException: // The property is set and the System.Collections.IDictionary object is read-only.-or- // The property is set, key does not exist in the collection, and the System.Collections.IDictionary // has a fixed size. // // System.ArgumentNullException: // key is null. object this[object key] { get; set; } // Summary: // Adds an element with the provided key and value to the System.Collections.IDictionary // object. // // Parameters: // value: // The System.Object to use as the value of the element to add. // // key: // The System.Object to use as the key of the element to add. // // Exceptions: // System.ArgumentException: // An element with the same key already exists in the System.Collections.IDictionary // object. // // System.ArgumentNullException: // key is null. // // System.NotSupportedException: // The System.Collections.IDictionary is read-only.-or- The System.Collections.IDictionary // has a fixed size. [WriteConfined] void Add(object key, object value); // // Summary: // Removes all elements from the System.Collections.IDictionary object. // // Exceptions: // System.NotSupportedException: // The System.Collections.IDictionary object is read-only. [WriteConfined] void Clear(); // // Summary: // Determines whether the System.Collections.IDictionary object contains an // element with the specified key. // // Parameters: // key: // The key to locate in the System.Collections.IDictionary object. // // Returns: // true if the System.Collections.IDictionary contains an element with the key; // otherwise, false. // // Exceptions: // System.ArgumentNullException: // key is null. [Pure] bool Contains(object key); // // Summary: // Returns an System.Collections.IDictionaryEnumerator object for the System.Collections.IDictionary // object. // // Returns: // An System.Collections.IDictionaryEnumerator object for the System.Collections.IDictionary // object. [Pure] [GlobalAccess(false)] [Escapes(true, false)] [return: Fresh] new IDictionaryEnumerator GetEnumerator(); // // Summary: // Removes the element with the specified key from the System.Collections.IDictionary // object. // // Parameters: // key: // The key of the element to remove. // // Exceptions: // System.NotSupportedException: // The System.Collections.IDictionary object is read-only.-or- The System.Collections.IDictionary // has a fixed size. // // System.ArgumentNullException: // key is null. [WriteConfined] void Remove(object key); } [ContractClassFor(typeof(IDictionary))] abstract class CDictionary : IDictionary { #region IDictionary Members bool IDictionary.IsFixedSize { get { throw new global::System.NotImplementedException(); } } bool IDictionary.IsReadOnly { get { throw new global::System.NotImplementedException(); } } ICollection IDictionary.Keys { get { Contract.Ensures(Contract.Result<ICollection>() != null); throw new global::System.NotImplementedException(); } } ICollection IDictionary.Values { get { Contract.Ensures(Contract.Result<ICollection>() != null); throw new global::System.NotImplementedException(); } } object IDictionary.this[object key] { get { Contract.Requires(key != null); throw new global::System.NotImplementedException(); } set { Contract.Requires(key != null); throw new global::System.NotImplementedException(); } } void IDictionary.Add(object key, object value) { Contract.Requires(key != null); throw new global::System.NotImplementedException(); } void IDictionary.Clear() { throw new global::System.NotImplementedException(); } [Pure] bool IDictionary.Contains(object key) { Contract.Requires(key != null); throw new global::System.NotImplementedException(); } [Pure] IDictionaryEnumerator IDictionary.GetEnumerator() { Contract.Ensures(Contract.Result<IDictionaryEnumerator>() != null); throw new global::System.NotImplementedException(); } void IDictionary.Remove(object key) { Contract.Requires(key != null); throw new global::System.NotImplementedException(); } #endregion #region ICollection Members int ICollection.Count { [Pure] get { throw new global::System.NotImplementedException(); } } bool ICollection.IsSynchronized { get { throw new global::System.NotImplementedException(); } } object ICollection.SyncRoot { get { throw new global::System.NotImplementedException(); } } void ICollection.CopyTo(Array array, int index) { throw new global::System.NotImplementedException(); } #endregion #region IEnumerable Members [Pure] IEnumerator IEnumerable.GetEnumerator() { throw new global::System.NotImplementedException(); } #endregion #region IEnumerable Members object[] IEnumerable.Model { get { throw new NotImplementedException(); } } #endregion } }
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.TestProtos { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class UnitTestCSharpOptionsProtoFile { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_protobuf_unittest_OptionsMessage__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.OptionsMessage, global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Builder> internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static UnitTestCSharpOptionsProtoFile() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci1nb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfY3NoYXJwX29wdGlvbnMucHJv", "dG8SEXByb3RvYnVmX3VuaXR0ZXN0GiRnb29nbGUvcHJvdG9idWYvY3NoYXJw", "X29wdGlvbnMucHJvdG8iXgoOT3B0aW9uc01lc3NhZ2USDgoGbm9ybWFsGAEg", "ASgJEhcKD29wdGlvbnNfbWVzc2FnZRgCIAEoCRIjCgpjdXN0b21pemVkGAMg", "ASgJQg/CPgwKCkN1c3RvbU5hbWVCRsI+QwohR29vZ2xlLlByb3RvY29sQnVm", "ZmVycy5UZXN0UHJvdG9zEh5Vbml0VGVzdENTaGFycE9wdGlvbnNQcm90b0Zp", "bGU=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_protobuf_unittest_OptionsMessage__Descriptor = Descriptor.MessageTypes[0]; internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.OptionsMessage, global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Builder>(internal__static_protobuf_unittest_OptionsMessage__Descriptor, new string[] { "Normal", "OptionsMessage_", "CustomName", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor, }, assigner); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class OptionsMessage : pb::GeneratedMessage<OptionsMessage, OptionsMessage.Builder> { private OptionsMessage() { } private static readonly OptionsMessage defaultInstance = new OptionsMessage().MakeReadOnly(); private static readonly string[] _optionsMessageFieldNames = new string[] { "customized", "normal", "options_message" }; private static readonly uint[] _optionsMessageFieldTags = new uint[] { 26, 10, 18 }; public static OptionsMessage DefaultInstance { get { return defaultInstance; } } public override OptionsMessage DefaultInstanceForType { get { return DefaultInstance; } } protected override OptionsMessage ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.internal__static_protobuf_unittest_OptionsMessage__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<OptionsMessage, OptionsMessage.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.internal__static_protobuf_unittest_OptionsMessage__FieldAccessorTable; } } public const int NormalFieldNumber = 1; private bool hasNormal; private string normal_ = ""; public bool HasNormal { get { return hasNormal; } } public string Normal { get { return normal_; } } public const int OptionsMessage_FieldNumber = 2; private bool hasOptionsMessage_; private string optionsMessage_ = ""; public bool HasOptionsMessage_ { get { return hasOptionsMessage_; } } public string OptionsMessage_ { get { return optionsMessage_; } } public const int CustomNameFieldNumber = 3; private bool hasCustomName; private string customized_ = ""; public bool HasCustomName { get { return hasCustomName; } } public string CustomName { get { return customized_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _optionsMessageFieldNames; if (hasNormal) { output.WriteString(1, field_names[1], Normal); } if (hasOptionsMessage_) { output.WriteString(2, field_names[2], OptionsMessage_); } if (hasCustomName) { output.WriteString(3, field_names[0], CustomName); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasNormal) { size += pb::CodedOutputStream.ComputeStringSize(1, Normal); } if (hasOptionsMessage_) { size += pb::CodedOutputStream.ComputeStringSize(2, OptionsMessage_); } if (hasCustomName) { size += pb::CodedOutputStream.ComputeStringSize(3, CustomName); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static OptionsMessage ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static OptionsMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static OptionsMessage ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static OptionsMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static OptionsMessage ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static OptionsMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static OptionsMessage ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static OptionsMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static OptionsMessage ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static OptionsMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private OptionsMessage MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(OptionsMessage prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<OptionsMessage, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(OptionsMessage cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private OptionsMessage result; private OptionsMessage PrepareBuilder() { if (resultIsReadOnly) { OptionsMessage original = result; result = new OptionsMessage(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override OptionsMessage MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.TestProtos.OptionsMessage.Descriptor; } } public override OptionsMessage DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.OptionsMessage.DefaultInstance; } } public override OptionsMessage BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is OptionsMessage) { return MergeFrom((OptionsMessage) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(OptionsMessage other) { if (other == global::Google.ProtocolBuffers.TestProtos.OptionsMessage.DefaultInstance) return this; PrepareBuilder(); if (other.HasNormal) { Normal = other.Normal; } if (other.HasOptionsMessage_) { OptionsMessage_ = other.OptionsMessage_; } if (other.HasCustomName) { CustomName = other.CustomName; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_optionsMessageFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _optionsMessageFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasNormal = input.ReadString(ref result.normal_); break; } case 18: { result.hasOptionsMessage_ = input.ReadString(ref result.optionsMessage_); break; } case 26: { result.hasCustomName = input.ReadString(ref result.customized_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasNormal { get { return result.hasNormal; } } public string Normal { get { return result.Normal; } set { SetNormal(value); } } public Builder SetNormal(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasNormal = true; result.normal_ = value; return this; } public Builder ClearNormal() { PrepareBuilder(); result.hasNormal = false; result.normal_ = ""; return this; } public bool HasOptionsMessage_ { get { return result.hasOptionsMessage_; } } public string OptionsMessage_ { get { return result.OptionsMessage_; } set { SetOptionsMessage_(value); } } public Builder SetOptionsMessage_(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasOptionsMessage_ = true; result.optionsMessage_ = value; return this; } public Builder ClearOptionsMessage_() { PrepareBuilder(); result.hasOptionsMessage_ = false; result.optionsMessage_ = ""; return this; } public bool HasCustomName { get { return result.hasCustomName; } } public string CustomName { get { return result.CustomName; } set { SetCustomName(value); } } public Builder SetCustomName(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasCustomName = true; result.customized_ = value; return this; } public Builder ClearCustomName() { PrepareBuilder(); result.hasCustomName = false; result.customized_ = ""; return this; } } static OptionsMessage() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestCSharpOptionsProtoFile.Descriptor, null); } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Text; using com.calitha.goldparser; namespace Epi.Core.EnterInterpreter.Rules { public class Rule_Value : EnterRule { public string Id = null; string Namespace = null; object value = null; int Index0 = -1; object Index1 = null; //object ReturnResult = null; public Rule_Value(Rule_Context pContext, Token pToken) : base(pContext) { /* ::= Identifier | <Literal> | Boolean | '(' <Expr List> ')' */ if (pToken is NonterminalToken) { NonterminalToken T = (NonterminalToken)pToken; if (T.Tokens.Length == 1) { DateTime dateTime_temp; switch (T.Symbol.ToString()) { case "<GridFieldId>": /*<GridFieldId> ::= Identifier'[' <Number>',' Identifier ']' | Identifier '[' <Number> ',' <Number> ']' | Identifier '[' <Number> ',' <Literal_String> ']'*/ this.Id = this.GetCommandElement(T.Tokens, 0); int Int_temp; if (int.TryParse(this.GetCommandElement(T.Tokens, 2), out Int_temp)) { this.Index0 = Int_temp; } if (int.TryParse(this.GetCommandElement(T.Tokens, 4), out Int_temp)) { this.Index1 = Int_temp; } else { //this.Index1 = this.GetCommandElement(T.Tokens, 4); this.Index1 = new Rule_Value(this.Context, T.Tokens[4]); } break; case "<Qualified ID>": case "Identifier": this.Id = this.GetCommandElement(T.Tokens, 0); break; case "<FunctionCall>": this.value = EnterRule.BuildStatments(pContext, T.Tokens[0]); break; case "<Literal>": this.value = this.GetCommandElement(T.Tokens, 0).Trim('"'); break; case "<Literal_String>": case "String": this.value = this.GetCommandElement(T.Tokens, 0).Trim('"'); break; case "<Literal_Char>": case "CharLiteral": this.value = this.GetCommandElement(T.Tokens, 0).Trim('\''); break; case "Boolean": string string_temp = this.GetCommandElement(T.Tokens, 0); if (string_temp == "(+)" || string_temp.ToLowerInvariant() == "true" || string_temp.ToLowerInvariant() == "yes") { this.value = true; } else if (string_temp == "(-)" || string_temp.ToLowerInvariant() == "false" || string_temp.ToLowerInvariant() == "no") { this.value = false; } else if (string_temp == "(.)") { this.value = null; } break; case "<Decimal_Number>": case "<Number>": case "<Real_Number>": case "<Hex_Number>": case "DecLiteral": case "RealLiteral": case "HexLiteral": double Decimal_temp; // if (double.TryParse(this.GetCommandElement(T.Tokens, 0), out Decimal_temp)) if (double.TryParse(this.GetCommandElement(T.Tokens, 0), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out Decimal_temp)) { this.value = Decimal_temp; } break; case "<Literal_Date>": case "Date": if (DateTime.TryParse(this.GetCommandElement(T.Tokens, 0), out dateTime_temp)) { DateTime dt = new DateTime(dateTime_temp.Year, dateTime_temp.Month, dateTime_temp.Day); this.value = dt; } else { this.value = null; } break; case "<Literal_Time>": case "<Literal_Date_Time>": case "Time": case "Date Time": if (DateTime.TryParse(this.GetCommandElement(T.Tokens, 0), out dateTime_temp)) { this.value = dateTime_temp; } break; case "<Value>": this.value = new Rule_Value(this.Context, T.Tokens[0]); break; default: this.value = this.GetCommandElement(T.Tokens, 0); break; } } else { //this.value = new Rule_ExprList(pContext, (NonterminalToken)T.Tokens[1]); if (T.Tokens.Length == 0) { this.value = EnterRule.BuildStatments(pContext, T); } else if (T.Symbol.ToString() == "<Fully_Qualified_Id>" || T.Symbol.ToString() == "<Qualified ID>") { string[] temp = this.ExtractTokens(T.Tokens).Split(' '); this.Namespace = temp[0]; this.Id = temp[2]; } else if (T.Symbol.ToString() == "<GridFieldId>") { /*<GridFieldId> ::= Identifier'[' <Number>',' Identifier ']' | Identifier '[' <Number> ',' <Number> ']' | Identifier '[' <Number> ',' <Literal_String> ']'*/ this.Id = this.GetCommandElement(T.Tokens, 0); int Int_temp; if (int.TryParse(this.GetCommandElement(T.Tokens, 2), out Int_temp)) { this.Index0 = Int_temp; } if (int.TryParse(this.GetCommandElement(T.Tokens, 4), out Int_temp)) { this.Index1 = Int_temp; } else { //this.Index1 = this.GetCommandElement(T.Tokens, 4); this.Index1 = new Rule_Value(this.Context, T.Tokens[4]); } } else { this.value = EnterRule.BuildStatments(pContext, T.Tokens[1]); } } } else { TerminalToken TT = (TerminalToken)pToken; DateTime dateTime_temp; switch (TT.Symbol.ToString()) { case "<GridFieldId>": ///*<GridFieldId> ::= Identifier'[' <Number>',' Identifier ']' //| Identifier '[' <Number> ',' <Number> ']' //| Identifier '[' <Number> ',' <Literal_String> ']'*/ //this.Id = this.GetCommandElement(T.Tokens, 0); //int Int_temp; //if (int.TryParse(this.GetCommandElement(T.Tokens, 2), out Int_temp)) //{ // this.Index0 = Int_temp; //} //if (int.TryParse(this.GetCommandElement(T.Tokens, 4), out Int_temp)) //{ // this.Index1 = Int_temp; //} //else //{ // this.Index1 = this.GetCommandElement(T.Tokens, 4); //} //break; case "Identifier": this.Id = TT.Text; break; case "<Literal>": this.value = TT.Text.Trim('"'); break; case "<Literal_String>": case "String": this.value = TT.Text.Trim('"'); break; case "<Literal_Char>": case "CharLiteral": this.value = TT.Text.Trim('\''); break; case "Boolean": string string_temp = TT.Text; if (string_temp == "(+)" || string_temp.ToLowerInvariant() == "true" || string_temp.ToLowerInvariant() == "yes") { this.value = true; } else if (string_temp == "(-)" || string_temp.ToLowerInvariant() == "false" || string_temp.ToLowerInvariant() == "no") { this.value = false; } else if (string_temp == "(.)") { this.value = null; } break; case "<Decimal_Number>": case "<Number>": case "<Real_Number>": case "<Hex_Number>": case "DecLiteral": case "RealLiteral": case "HexLiteral": double Decimal_temp; if (double.TryParse(TT.Text, out Decimal_temp)) { this.value = Decimal_temp; } break; case "<Literal_Date>": case "Date": if (DateTime.TryParse(TT.Text, out dateTime_temp)) { DateTime dt = new DateTime(dateTime_temp.Year, dateTime_temp.Month, dateTime_temp.Day); this.value = dt; } else { this.value = null; } break; case "<Literal_Time>": case "<Literal_Date_Time>": case "Time": case "Date Time": if (DateTime.TryParse(TT.Text, out dateTime_temp)) { this.value = dateTime_temp; } break; default: this.value = TT.Text; break; } } if (this.Id == null && this.value == null) { } if (this.value != null && this.value.Equals("END-IF")) { } } public Rule_Value(string pValue) { this.value = pValue; } /// <summary> /// performs execution of retrieving the value of a variable or expression /// </summary> /// <returns>object</returns> public override object Execute() { object result = null; if (this.Id != null) { EpiInfo.Plugin.IVariable var; EpiInfo.Plugin.DataType dataType = EpiInfo.Plugin.DataType.Unknown; string dataValue = string.Empty; var = Context.CurrentScope.Resolve(this.Id, this.Namespace); if (var != null && !(var.VariableScope == EpiInfo.Plugin.VariableScope.DataSource)) { dataType = var.DataType; dataValue = var.Expression; } else { if (this.Context.EnterCheckCodeInterface != null) { EpiInfo.Plugin.DataType dt = EpiInfo.Plugin.DataType.Unknown; if (this.Index0 == -1) { this.Context.EnterCheckCodeInterface.TryGetFieldInfo(this.Id, out dt, out dataValue); dataType = (EpiInfo.Plugin.DataType)dt; } else { if (this.Index1 is Rule_Value) { this.Index1 = ((Rule_Value)this.Index1).Execute(); } EpiInfo.Plugin.IVariable iv = this.Context.EnterCheckCodeInterface.GetGridValue(this.Id, this.Index0, this.Index1); dataValue = iv.Expression; dataType = iv.DataType; } } } result = ConvertEpiDataTypeToSystemObject(dataType, dataValue); } else { if (value is EnterRule) { result = ((EnterRule)value).Execute(); } else { result = value; } } return result; } private object ConvertEpiDataTypeToSystemObject(EpiInfo.Plugin.DataType dataType, string dataValue) { object result = null; if (dataValue != null) { DateTime dateTime; switch (dataType) { case EpiInfo.Plugin.DataType.Boolean: case EpiInfo.Plugin.DataType.YesNo: result = new Boolean(); if (dataValue == "(+)" || dataValue.ToLowerInvariant() == "true" || dataValue == "1" || dataValue.ToLowerInvariant() == "yes") result = true; else if (dataValue == "(-)" || dataValue.ToLowerInvariant() == "false" || dataValue == "0" || dataValue.ToLowerInvariant() == "no") result = false; else result = null; break; case EpiInfo.Plugin.DataType.Number: double num; if (double.TryParse(dataValue, out num)) result = num; else result = null; break; case EpiInfo.Plugin.DataType.Date: if (DateTime.TryParse(dataValue, out dateTime)) { DateTime dt = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day); result = dt; } else { result = null; } break; case EpiInfo.Plugin.DataType.DateTime: case EpiInfo.Plugin.DataType.Time: if (DateTime.TryParse(dataValue, out dateTime)) { result = dateTime; } else { result = null; } break; case EpiInfo.Plugin.DataType.PhoneNumber: case EpiInfo.Plugin.DataType.GUID: case EpiInfo.Plugin.DataType.Text: if (dataValue != null) result = dataValue.Trim('\"'); else result = null; break; case EpiInfo.Plugin.DataType.Unknown: default: double double_compare; DateTime DateTime_compare; bool bool_compare; if (double.TryParse(dataValue, out double_compare)) { result = double_compare; } else if (DateTime.TryParse(dataValue, out DateTime_compare)) { result = DateTime_compare; } else if (bool.TryParse(dataValue, out bool_compare)) { result = bool_compare; } else { result = dataValue; } break; } } return result; } private object ParseDataStrings(object subject) { object result = null; if (subject is Rule_ExprList) { result = ((Rule_ExprList)subject).Execute(); } else if (subject is Rule_FunctionCall) { result = ((Rule_FunctionCall)subject).Execute(); } else if (subject is String) { Double number; DateTime dateTime; result = ((String)subject).Trim('\"'); //removing the "1" and "0" conditions here because an expression like 1 + 0 was evaluating as two booleans //if ((String)subject == "1" || (String)subject == "(+)" || ((String)subject).ToLowerInvariant() == "true") if ((String)subject == "(+)" || ((String)subject).ToLowerInvariant() == "true" || ((String)subject).ToLowerInvariant() == "yes") { result = new Boolean(); result = true; } //else if ((String)subject == "0" || (String)subject == "(-)" || ((String)subject).ToLowerInvariant() == "false") else if ((String)subject == "(-)" || ((String)subject).ToLowerInvariant() == "false" || ((String)subject).ToLowerInvariant() == "no") { result = new Boolean(); result = false; } else if ((String)subject == "(.)") { result = null; } else if (Double.TryParse(result.ToString(), out number)) { result = number; } else if (DateTime.TryParse(result.ToString(), out dateTime)) { result = dateTime; } } return result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MyWebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* * 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.core.model.condition; using org.javarosa.core.model.data; using org.javarosa.core.model.data.helper; using org.javarosa.core.model.instance; using org.javarosa.core.util.externalizable; using org.javarosa.xform.util; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace org.javarosa.xpath.expr{ public class XPathPathExpr : XPathExpression { public const int INIT_CONTEXT_ROOT = 0; public const int INIT_CONTEXT_RELATIVE = 1; public const int INIT_CONTEXT_EXPR = 2; public int init_context; public XPathStep[] steps; //for INIT_CONTEXT_EXPR only public XPathFilterExpr filtExpr; public XPathPathExpr () { } //for deserialization public XPathPathExpr (int init_context, XPathStep[] steps) { this.init_context = init_context; this.steps = steps; } public XPathPathExpr (XPathFilterExpr filtExpr, XPathStep[] steps): this(INIT_CONTEXT_EXPR, steps) { this.filtExpr = filtExpr; } public TreeReference getReference () { return getReference(false); } /** * translate an xpath path reference into a TreeReference * TreeReferences only support a subset of true xpath paths; restrictions are: * simple child name tests 'child::name', '.', and '..' allowed only * no predicates * all '..' steps must come before anything else */ public TreeReference getReference (Boolean allowPredicates) { TreeReference ref_ = new TreeReference(); Boolean parentsAllowed; switch (init_context) { case XPathPathExpr.INIT_CONTEXT_ROOT: ref_.setRefLevel(TreeReference.REF_ABSOLUTE); parentsAllowed = false; break; case XPathPathExpr.INIT_CONTEXT_RELATIVE: ref_.setRefLevel(0); parentsAllowed = true; break; default: throw new XPathUnsupportedException("filter expression"); } for (int i = 0; i < steps.Length; i++) { XPathStep step = steps[i]; if (!allowPredicates && step.predicates.Length > 0) { throw new XPathUnsupportedException("predicates"); } if (step.axis == XPathStep.AXIS_SELF) { if (step.test != XPathStep.TEST_TYPE_NODE) { throw new XPathUnsupportedException("step other than 'child::name', '.', '..'"); } } else if (step.axis == XPathStep.AXIS_PARENT) { if (!parentsAllowed || step.test != XPathStep.TEST_TYPE_NODE) { throw new XPathUnsupportedException("step other than 'child::name', '.', '..'"); } else { ref_.incrementRefLevel(); } } else if (step.axis == XPathStep.AXIS_ATTRIBUTE) { if (step.test == XPathStep.TEST_NAME) { ref_.add(step.name.ToString(), TreeReference.INDEX_ATTRIBUTE); parentsAllowed = false; //TODO: Can you step back from an attribute, or should this always be //the last step? } else { throw new XPathUnsupportedException("attribute step other than 'attribute::name"); } }else if (step.axis == XPathStep.AXIS_CHILD) { if (step.test == XPathStep.TEST_NAME) { ref_.add(step.name.ToString(), TreeReference.INDEX_UNBOUND); parentsAllowed = false; } else if(step.test == XPathStep.TEST_NAME_WILDCARD) { ref_.add(TreeReference.NAME_WILDCARD, TreeReference.INDEX_UNBOUND); parentsAllowed = false; } else { throw new XPathUnsupportedException("step other than 'child::name', '.', '..'"); } } else { throw new XPathUnsupportedException("step other than 'child::name', '.', '..'"); } } return ref_; } public override object eval(FormInstance m, EvaluationContext evalContext) { TreeReference genericRef = getReference(); if (genericRef.isAbsolute() && m.getTemplatePath(genericRef) == null) { throw new XPathTypeMismatchException("Node " + genericRef.toString() + " does not exist!"); } TreeReference ref_ = genericRef.contextualize(evalContext.ContextRef); List<TreeReference> nodesetRefs = m.expandReference(ref_); //to fix conditions based on non-relevant data, filter the nodeset by relevancy for (int i = 0; i < nodesetRefs.Count; i++) { if (!m.resolveReference((TreeReference)nodesetRefs[i]).isRelevant()) { nodesetRefs.RemoveAt(i); i--; } } return new XPathNodeset(nodesetRefs, m, evalContext); } // // boolean nodeset = forceNodeset; // if (!nodeset) { // //is this a nodeset? it is if the ref contains any unbound multiplicities AND the unbound nodes are repeatable // //the way i'm calculating this sucks; there has got to be an easier way to find out if a node is repeatable // TreeReference repeatTestRef = TreeReference.rootRef(); // for (int i = 0; i < ref.size(); i++) { // repeatTestRef.add(ref.getName(i), ref.getMultiplicity(i)); // if (ref.getMultiplicity(i) == TreeReference.INDEX_UNBOUND) { // if (m.getTemplate(repeatTestRef) != null) { // nodeset = true; // break; // } // } // } // } public static Object getRefValue (FormInstance model, EvaluationContext ec, TreeReference ref_) { if (ec.isConstraint && ref_.Equals(ec.ContextRef)) { //ITEMSET TODO: need to update this; for itemset/copy constraints, need to simulate a whole xml sub-tree here return unpackValue(ec.candidateValue); } else { TreeElement node = model.resolveReference(ref_); if (node == null) { //shouldn't happen -- only existent nodes should be in nodeset throw new XPathTypeMismatchException("Node " + ref_.toString() + " does not exist!"); } return unpackValue(node.isRelevant() ? node.getValue() : null); } } public static Object unpackValue (IAnswerData val) { if (val == null) { return ""; } else if (val is UncastData) { return val.Value; } else if (val is IntegerData) { return ( Double)(((int)val.Value)); } else if (val is LongData) { return( Double)(((long)val.Value)); } else if (val is DecimalData) { return val.Value; } else if (val is StringData) { return val.Value; } else if (val is SelectOneData) { return ((Selection)val.Value).Value; } else if (val is SelectMultiData) { return (new XFormAnswerDataSerializer()).serializeAnswerData(val); } else if (val is DateData) { return val.Value; } else if (val is BooleanData) { return val.Value; } else { Console.WriteLine("warning: unrecognized data type in xpath expr: " + val.GetType().Name); return val.Value; //is this a good idea? } } public String toString () { StringBuilder sb = new StringBuilder(); sb.Append("{path-expr:"); switch (init_context) { case INIT_CONTEXT_ROOT: sb.Append("abs"); break; case INIT_CONTEXT_RELATIVE: sb.Append("rel"); break; case INIT_CONTEXT_EXPR: sb.Append(filtExpr.toString()); break; } sb.Append(",{"); for (int i = 0; i < steps.Length; i++) { sb.Append(steps[i].ToString()); if (i < steps.Length - 1) sb.Append(","); } sb.Append("}}"); return sb.ToString(); } public Boolean equals (Object o) { if (o is XPathPathExpr) { XPathPathExpr x = (XPathPathExpr)o; //Shortcuts for easily comparable values if(init_context != x.init_context || steps.Length != x.steps.Length) { return false; } return ExtUtil.arrayEquals(steps, x.steps) && (init_context == INIT_CONTEXT_EXPR ? filtExpr.equals(x.filtExpr) : true); } else { return false; } } public void readExternal(BinaryReader in_, PrototypeFactory pf) { init_context = ExtUtil.readInt(in_); if (init_context == INIT_CONTEXT_EXPR) { filtExpr = (XPathFilterExpr)ExtUtil.read(in_, typeof(XPathFilterExpr), pf); } ArrayList v = (ArrayList)ExtUtil.read(in_, new ExtWrapList(typeof(XPathStep)), pf); steps = new XPathStep[v.Count]; for (int i = 0; i < steps.Length; i++) steps[i] = (XPathStep)v[i]; } public void writeExternal(BinaryWriter out_) { ExtUtil.writeNumeric(out_, init_context); if (init_context == INIT_CONTEXT_EXPR) { ExtUtil.write(out_, filtExpr); } ArrayList v = new ArrayList(); for (int i = 0; i < steps.Length; i++) v.Add(steps[i]); ExtUtil.write(out_, new ExtWrapList(v)); } public static XPathPathExpr fromRef (TreeReference out_) { XPathPathExpr path = new XPathPathExpr(); path.init_context = (out_.isAbsolute() ? INIT_CONTEXT_ROOT : INIT_CONTEXT_RELATIVE); path.steps = new XPathStep[out_.size()]; for (int i = 0; i < path.steps.Length; i++) { if (out_.getName(i).Equals(TreeReference.NAME_WILDCARD)) { path.steps[i] = new XPathStep(XPathStep.AXIS_CHILD, XPathStep.TEST_NAME_WILDCARD); } else { path.steps[i] = new XPathStep(XPathStep.AXIS_CHILD, new XPathQName(out_.getName(i))); } } return path; } public Object pivot (FormInstance model, EvaluationContext evalContext, List<Object> pivots, Object sentinal) { TreeReference out_ = this.getReference(); //Either concretely the sentinal, or "." if (out_.Equals(sentinal) || (out_.getRefLevel() == 0)) { return sentinal; } else { return this.eval(model, evalContext); } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using DiscUtils.Partitions; /// <summary> /// VolumeManager interprets partitions and other on-disk structures (possibly combining multiple disks). /// </summary> /// <remarks> /// <para>Although file systems commonly are placed directly within partitions on a disk, in some /// cases a logical volume manager / logical disk manager may be used, to combine disk regions in multiple /// ways for data redundancy or other purposes.</para> /// </remarks> public sealed class VolumeManager : MarshalByRefObject { private static List<LogicalVolumeFactory> s_logicalVolumeFactories; private List<VirtualDisk> _disks; private bool _needScan; private Dictionary<string, PhysicalVolumeInfo> _physicalVolumes; private Dictionary<string, LogicalVolumeInfo> _logicalVolumes; /// <summary> /// Initializes a new instance of the VolumeManager class. /// </summary> public VolumeManager() { _disks = new List<VirtualDisk>(); _physicalVolumes = new Dictionary<string, PhysicalVolumeInfo>(); _logicalVolumes = new Dictionary<string, LogicalVolumeInfo>(); } /// <summary> /// Initializes a new instance of the VolumeManager class. /// </summary> /// <param name="initialDisk">The initial disk to add.</param> public VolumeManager(VirtualDisk initialDisk) : this() { AddDisk(initialDisk); } /// <summary> /// Initializes a new instance of the VolumeManager class. /// </summary> /// <param name="initialDiskContent">Content of the initial disk to add.</param> public VolumeManager(Stream initialDiskContent) : this() { AddDisk(initialDiskContent); } private static List<LogicalVolumeFactory> LogicalVolumeFactories { get { if (s_logicalVolumeFactories == null) { List<LogicalVolumeFactory> factories = new List<LogicalVolumeFactory>(); foreach (var type in typeof(VolumeManager).Assembly.GetTypes()) { foreach (LogicalVolumeFactoryAttribute attr in Attribute.GetCustomAttributes(type, typeof(LogicalVolumeFactoryAttribute), false)) { factories.Add((LogicalVolumeFactory)Activator.CreateInstance(type)); } } s_logicalVolumeFactories = factories; } return s_logicalVolumeFactories; } } /// <summary> /// Gets the physical volumes held on a disk. /// </summary> /// <param name="diskContent">The contents of the disk to inspect</param> /// <returns>An array of volumes</returns> /// <remarks> /// <para>By preference, use the form of this method that takes a disk parameter.</para> /// <para>If the disk isn't partitioned, this method returns the entire disk contents /// as a single volume.</para> /// </remarks> public static PhysicalVolumeInfo[] GetPhysicalVolumes(Stream diskContent) { return GetPhysicalVolumes(new Raw.Disk(diskContent, Ownership.None)); } /// <summary> /// Gets the physical volumes held on a disk. /// </summary> /// <param name="disk">The disk to inspect</param> /// <returns>An array of volumes</returns> /// <remarks>If the disk isn't partitioned, this method returns the entire disk contents /// as a single volume.</remarks> public static PhysicalVolumeInfo[] GetPhysicalVolumes(VirtualDisk disk) { return new VolumeManager(disk).GetPhysicalVolumes(); } /// <summary> /// Adds a disk to the volume manager. /// </summary> /// <param name="disk">The disk to add</param> /// <returns>The GUID the volume manager will use to identify the disk</returns> public string AddDisk(VirtualDisk disk) { _needScan = true; int ordinal = _disks.Count; _disks.Add(disk); return GetDiskId(ordinal); } /// <summary> /// Adds a disk to the volume manager. /// </summary> /// <param name="content">The contents of the disk to add</param> /// <returns>The GUID the volume manager will use to identify the disk</returns> public string AddDisk(Stream content) { return AddDisk(new Raw.Disk(content, Ownership.None)); } /// <summary> /// Gets the physical volumes from all disks added to this volume manager. /// </summary> /// <returns>An array of physical volumes</returns> public PhysicalVolumeInfo[] GetPhysicalVolumes() { if (_needScan) { Scan(); } return new List<PhysicalVolumeInfo>(_physicalVolumes.Values).ToArray(); } /// <summary> /// Gets the logical volumes from all disks added to this volume manager. /// </summary> /// <returns>An array of logical volumes</returns> public LogicalVolumeInfo[] GetLogicalVolumes() { if (_needScan) { Scan(); } return new List<LogicalVolumeInfo>(_logicalVolumes.Values).ToArray(); } /// <summary> /// Gets a particular volume, based on it's identity. /// </summary> /// <param name="identity">The volume's identity</param> /// <returns>The volume information for the volume, or returns <c>null</c></returns> public VolumeInfo GetVolume(string identity) { if (_needScan) { Scan(); } PhysicalVolumeInfo pvi; if (_physicalVolumes.TryGetValue(identity, out pvi)) { return pvi; } LogicalVolumeInfo lvi; if (_logicalVolumes.TryGetValue(identity, out lvi)) { return lvi; } return null; } private static void MapPhysicalVolumes(IEnumerable<PhysicalVolumeInfo> physicalVols, Dictionary<string, LogicalVolumeInfo> result) { foreach (var physicalVol in physicalVols) { LogicalVolumeInfo lvi = new LogicalVolumeInfo( physicalVol.PartitionIdentity, physicalVol, physicalVol.Open, physicalVol.Length, physicalVol.BiosType, LogicalVolumeStatus.Healthy); result.Add(lvi.Identity, lvi); } } /// <summary> /// Scans all of the disks for their physical and logical volumes. /// </summary> private void Scan() { Dictionary<string, PhysicalVolumeInfo> newPhysicalVolumes = ScanForPhysicalVolumes(); Dictionary<string, LogicalVolumeInfo> newLogicalVolumes = ScanForLogicalVolumes(newPhysicalVolumes.Values); _physicalVolumes = newPhysicalVolumes; _logicalVolumes = newLogicalVolumes; _needScan = false; } private Dictionary<string, LogicalVolumeInfo> ScanForLogicalVolumes(IEnumerable<PhysicalVolumeInfo> physicalVols) { List<PhysicalVolumeInfo> unhandledPhysical = new List<PhysicalVolumeInfo>(); Dictionary<string, LogicalVolumeInfo> result = new Dictionary<string, LogicalVolumeInfo>(); foreach (PhysicalVolumeInfo pvi in physicalVols) { bool handled = false; foreach (var volFactory in LogicalVolumeFactories) { if (volFactory.HandlesPhysicalVolume(pvi)) { handled = true; break; } } if (!handled) { unhandledPhysical.Add(pvi); } } MapPhysicalVolumes(unhandledPhysical, result); foreach (var volFactory in LogicalVolumeFactories) { volFactory.MapDisks(_disks, result); } return result; } private Dictionary<string, PhysicalVolumeInfo> ScanForPhysicalVolumes() { Dictionary<string, PhysicalVolumeInfo> result = new Dictionary<string, PhysicalVolumeInfo>(); // First scan physical volumes for (int i = 0; i < _disks.Count; ++i) { VirtualDisk disk = _disks[i]; string diskId = GetDiskId(i); if (PartitionTable.IsPartitioned(disk.Content)) { foreach (var table in PartitionTable.GetPartitionTables(disk.Content)) { foreach (var part in table.Partitions) { PhysicalVolumeInfo pvi = new PhysicalVolumeInfo(diskId, disk, part); result.Add(pvi.Identity, pvi); } } } else { PhysicalVolumeInfo pvi = new PhysicalVolumeInfo(diskId, disk); result.Add(pvi.Identity, pvi); } } return result; } private string GetDiskId(int ordinal) { VirtualDisk disk = _disks[ordinal]; if (disk.IsPartitioned) { Guid guid = disk.Partitions.DiskGuid; if (guid != Guid.Empty) { return "DG" + guid.ToString("B"); } } int sig = disk.Signature; if (sig != 0) { return "DS" + sig.ToString("X8", CultureInfo.InvariantCulture); } return "DO" + ordinal; } } }
using System; using Flame.Build; using Flame.Compiler; using Flame.Compiler.Expressions; using Flame.Compiler.Statements; namespace Flame.LLVM { /// <summary> /// Describes how the back-end interfaces with the garbage collector. /// </summary> public abstract class GCDescription { /// <summary> /// Creates an expression that allocates an object of the given size. /// </summary> /// <param name="Size">The size of the object to allocate, in bytes.</param> /// <returns>An expression that allocates an object and returns a pointer to it.</returns> public abstract IExpression Allocate(IExpression Size); /// <summary> /// Registers a finalizer for the given garbage-collected object. /// </summary> /// <param name="Pointer">A pointer to a garbage-collected object.</param> /// <param name="Finalizer">The finalizer method to register.</param> /// <returns>A statement that registers a finalizer.</returns> public abstract IStatement RegisterFinalizer(IExpression Pointer, IMethod Finalizer); } /// <summary> /// The default GC description, which relies on user-defined methods to work. /// </summary> public sealed class ExternalGCDescription : GCDescription { /// <summary> /// Creates a GC description from the given allocation method. /// </summary> /// <param name="AllocateMethod"> /// A method that allocates data. It must have signature `static void*(ulong)`. /// </param> /// <param name="RegisterFinalizerMethod"> /// A method that registers a finalizer for an object. /// </param> public ExternalGCDescription(Lazy<IMethod> AllocateMethod, Lazy<IMethod> RegisterFinalizerMethod) { this.allocMethod = AllocateMethod; this.registerFinalizerMethod = RegisterFinalizerMethod; } /// <summary> /// Creates a GC description from the given binder and log. /// </summary> /// <param name="Binder">The binder to find types with.</param> /// <param name="Log">The log to use when an error is to be reported.</param> public ExternalGCDescription(IBinder Binder, ICompilerLog Log) { var methodFinder = new ExternalGCMethodFinder(Binder, Log); this.allocMethod = methodFinder.AllocateMethod; this.registerFinalizerMethod = methodFinder.RegisterFinalizerMethod; } private Lazy<IMethod> allocMethod; private Lazy<IMethod> registerFinalizerMethod; /// <summary> /// Gets the method that allocates data. It must have signature `static void*(ulong)`. /// </summary> /// <returns>The allocation method.</returns> public IMethod AllocateMethod => allocMethod.Value; /// <summary> /// Gets the method that registers finalizers. It must have signature /// `static void(void*, void(void*))' /// </summary> public IMethod RegisterFinalizerMethod => registerFinalizerMethod.Value; /// <inheritdoc/> public override IExpression Allocate(IExpression Size) { return new InvocationExpression(AllocateMethod, null, new IExpression[] { Size }); } /// <inheritdoc/> public override IStatement RegisterFinalizer(IExpression Pointer, IMethod Finalizer) { if (RegisterFinalizerMethod == null) { return EmptyStatement.Instance; } else { return new ExpressionStatement( new InvocationExpression( RegisterFinalizerMethod, null, new IExpression[] { Pointer, new GetMethodExpression(Finalizer, null, Operator.GetDelegate) })); } } } /// <summary> /// A helper class that finds user-defined GC methods. /// </summary> internal sealed class ExternalGCMethodFinder { /// <summary> /// Creates a GC method finder from the given binder and log. /// </summary> /// <param name="Binder">The binder to find types with.</param> /// <param name="Log">The log to use when an error is to be reported.</param> public ExternalGCMethodFinder(IBinder Binder, ICompilerLog Log) { this.Binder = Binder; this.Log = Log; this.GCType = new Lazy<IType>(GetGCType); this.AllocateMethod = new Lazy<IMethod>(GetAllocateMethod); this.RegisterFinalizerMethod = new Lazy<IMethod>(GetRegisterFinalizerMethod); } /// <summary> /// Gets the binder to use. /// </summary> /// <returns>The binder.</returns> public IBinder Binder { get; private set; } /// <summary> /// Gets the compiler log for this GC method finder. /// </summary> /// <returns>The compiler log.</returns> public ICompilerLog Log { get; private set; } /// <summary> /// Gets the runtime GC implementation type for this method finder. /// </summary> /// <returns>The runtime GC type.</returns> public Lazy<IType> GCType { get; private set; } /// <summary> /// Gets the allocation method for this method finder. /// </summary> /// <returns>The allocation method.</returns> public Lazy<IMethod> AllocateMethod { get; private set; } /// <summary> /// Gets the finalizer registration method for this method founder. /// </summary> /// <returns>The finalizer registration method.</returns> public Lazy<IMethod> RegisterFinalizerMethod { get; private set; } // The GC type is called "__compiler_rt.GC". private static readonly QualifiedName GCTypeName = new SimpleName("GC") .Qualify( new SimpleName("__compiler_rt") .Qualify()); // The allocation function's unqualified name is "Allocate". private const string AllocateMethodName = "Allocate"; private const string RegisterFinalizerMethodName = "RegisterFinalizer"; private IType GetGCType() { var gcType = Binder.BindType(GCTypeName); if (gcType == null) { Log.LogError( new LogEntry( "missing runtime type", "cannot find runtime type '" + GCTypeName.ToString() + "', which must be present for garbage collection to work.")); } return gcType; } private IMethod GetAllocateMethod() { var gcType = GCType.Value; if (gcType == null) return null; var method = gcType.GetMethod( new SimpleName(AllocateMethodName), true, PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer), new IType[] { PrimitiveTypes.UInt64 }); if (method == null) { Log.LogError( new LogEntry( "missing runtime method", "cannot find runtime method 'static void* " + new SimpleName(AllocateMethodName).Qualify(GCTypeName).ToString() + "(ulong)', which must be present for garbage collection to work.")); } return method; } private static IMethod GetStaticMethodNamed(IType Type, string Name) { IMethod result = null; var name = new SimpleName(Name); foreach (var method in Type.Methods) { if (method.Name.Equals(name) && method.IsStatic) { result = method; } } return result; } private IMethod GetRegisterFinalizerMethod() { var gcType = GCType.Value; if (gcType == null) return null; // Search for a method with signature // 'static T RegisterFinalizer(...)'. var result = GetStaticMethodNamed(gcType, RegisterFinalizerMethodName); if (result == null) { Log.LogError( new LogEntry( "missing runtime method", "cannot find runtime method 'static void " + new SimpleName(RegisterFinalizerMethodName).Qualify(GCTypeName).ToString() + "(void*, void(void*))', which must be present for finalizers to work.")); } return result; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Northwind { /// <summary> /// Strongly-typed collection for the ProductCategoryMap class. /// </summary> [Serializable] public partial class ProductCategoryMapCollection : ActiveList<ProductCategoryMap, ProductCategoryMapCollection> { public ProductCategoryMapCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ProductCategoryMapCollection</returns> public ProductCategoryMapCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { ProductCategoryMap o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Product_Category_Map table. /// </summary> [Serializable] public partial class ProductCategoryMap : ActiveRecord<ProductCategoryMap>, IActiveRecord { #region .ctors and Default Settings public ProductCategoryMap() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public ProductCategoryMap(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public ProductCategoryMap(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public ProductCategoryMap(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Product_Category_Map", TableType.Table, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema); colvarCategoryID.ColumnName = "CategoryID"; colvarCategoryID.DataType = DbType.Int32; colvarCategoryID.MaxLength = 0; colvarCategoryID.AutoIncrement = false; colvarCategoryID.IsNullable = false; colvarCategoryID.IsPrimaryKey = true; colvarCategoryID.IsForeignKey = true; colvarCategoryID.IsReadOnly = false; colvarCategoryID.DefaultSetting = @""; colvarCategoryID.ForeignKeyTableName = "Categories"; schema.Columns.Add(colvarCategoryID); TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema); colvarProductID.ColumnName = "ProductID"; colvarProductID.DataType = DbType.Int32; colvarProductID.MaxLength = 0; colvarProductID.AutoIncrement = false; colvarProductID.IsNullable = false; colvarProductID.IsPrimaryKey = true; colvarProductID.IsForeignKey = true; colvarProductID.IsReadOnly = false; colvarProductID.DefaultSetting = @""; colvarProductID.ForeignKeyTableName = "Products"; schema.Columns.Add(colvarProductID); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("Product_Category_Map",schema); } } #endregion #region Props [XmlAttribute("CategoryID")] [Bindable(true)] public int CategoryID { get { return GetColumnValue<int>(Columns.CategoryID); } set { SetColumnValue(Columns.CategoryID, value); } } [XmlAttribute("ProductID")] [Bindable(true)] public int ProductID { get { return GetColumnValue<int>(Columns.ProductID); } set { SetColumnValue(Columns.ProductID, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a Category ActiveRecord object related to this ProductCategoryMap /// /// </summary> public Northwind.Category Category { get { return Northwind.Category.FetchByID(this.CategoryID); } set { SetColumnValue("CategoryID", value.CategoryID); } } /// <summary> /// Returns a Product ActiveRecord object related to this ProductCategoryMap /// /// </summary> public Northwind.Product Product { get { return Northwind.Product.FetchByID(this.ProductID); } set { SetColumnValue("ProductID", value.ProductID); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varCategoryID,int varProductID) { ProductCategoryMap item = new ProductCategoryMap(); item.CategoryID = varCategoryID; item.ProductID = varProductID; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varCategoryID,int varProductID) { ProductCategoryMap item = new ProductCategoryMap(); item.CategoryID = varCategoryID; item.ProductID = varProductID; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn CategoryIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn ProductIDColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string CategoryID = @"CategoryID"; public static string ProductID = @"ProductID"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Parsing; namespace Microsoft.PythonTools.Debugger { class PythonStackFrame { private int _lineNo; // mutates on set next line private readonly string _frameName, _filename; private readonly int _argCount, _frameId; private readonly int _startLine, _endLine; private PythonEvaluationResult[] _variables; private readonly PythonThread _thread; private readonly FrameKind _kind; public PythonStackFrame(PythonThread thread, string frameName, string filename, int startLine, int endLine, int lineNo, int argCount, int frameId, FrameKind kind) { _thread = thread; _frameName = frameName; _filename = filename; _argCount = argCount; _lineNo = lineNo; _frameId = frameId; _startLine = startLine; _endLine = endLine; _kind = kind; } /// <summary> /// The line nubmer where the current function/class/module starts /// </summary> public int StartLine { get { return _startLine; } } /// <summary> /// The line number where the current function/class/module ends. /// </summary> public int EndLine { get { return _endLine; } } public PythonThread Thread { get { return _thread; } } public int LineNo { get { return _lineNo; } set { _lineNo = value; } } public string FunctionName { get { return _frameName; } } public string FileName { get { return _thread.Process.MapFile(_filename, toDebuggee: false); } } public FrameKind Kind { get { return _kind; } } /// <summary> /// Gets the ID of the frame. Frame 0 is the currently executing frame, 1 is the caller of the currently executing frame, etc... /// </summary> public int FrameId { get { return _frameId; } } internal void SetVariables(PythonEvaluationResult[] variables) { _variables = variables; } public IList<PythonEvaluationResult> Locals { get { PythonEvaluationResult[] res = new PythonEvaluationResult[_variables.Length - _argCount]; for (int i = _argCount; i < _variables.Length; i++) { res[i - _argCount] = _variables[i]; } return res; } } public IList<PythonEvaluationResult> Parameters { get { PythonEvaluationResult[] res = new PythonEvaluationResult[_argCount]; for (int i = 0; i < _argCount; i++) { res[i] = _variables[i]; } return res; } } /// <summary> /// Attempts to parse the given text. Returns true if the text is a valid expression. Returns false if the text is not /// a valid expression and assigns the error messages produced to errorMsg. /// </summary> public virtual bool TryParseText(string text, out string errorMsg) { CollectingErrorSink errorSink = new CollectingErrorSink(); Parser parser = Parser.CreateParser(new StringReader(text), _thread.Process.LanguageVersion, new ParserOptions() { ErrorSink = errorSink }); var ast = parser.ParseSingleStatement(); if (errorSink.Errors.Count > 0) { StringBuilder msg = new StringBuilder(); foreach (var error in errorSink.Errors) { msg.Append(error.Message); msg.Append(Environment.NewLine); } errorMsg = msg.ToString(); return false; } errorMsg = null; return true; } /// <summary> /// Executes the given text against this stack frame. /// </summary> public Task ExecuteTextAsync(string text, Action<PythonEvaluationResult> completion, CancellationToken ct) { return ExecuteTextAsync(text, PythonEvaluationResultReprKind.Normal, completion, ct); } public Task ExecuteTextAsync(string text, PythonEvaluationResultReprKind reprKind, Action<PythonEvaluationResult> completion, CancellationToken ct) { return _thread.Process.ExecuteTextAsync(text, reprKind, this, false, completion, ct); } public async Task<PythonEvaluationResult> ExecuteTextAsync(string text, PythonEvaluationResultReprKind reprKind = PythonEvaluationResultReprKind.Normal, CancellationToken ct = default(CancellationToken)) { var tcs = new TaskCompletionSource<PythonEvaluationResult>(); var cancellationRegistration = ct.Register(() => tcs.TrySetCanceled()); EventHandler<ProcessExitedEventArgs> processExited = delegate { tcs.TrySetCanceled(); }; _thread.Process.ProcessExited += processExited; try { await ExecuteTextAsync(text, reprKind, result => tcs.TrySetResult(result), ct); return await tcs.Task; } finally { _thread.Process.ProcessExited -= processExited; cancellationRegistration.Dispose(); } } /// <summary> /// Sets the line number that this current frame is executing. Returns true /// if the line was successfully set or false if the line number cannot be changed /// to this line. /// </summary> public Task<bool> SetLineNumber(int lineNo, CancellationToken ct) { return _thread.Process.SetLineNumberAsync(this, lineNo, ct); } public string GetQualifiedFunctionName() { return GetQualifiedFunctionName(_thread.Process, FileName, LineNo, FunctionName); } public static string GetQualifiedFunctionName(PythonProcess process, string filename, int lineNo, string functionName) { var ast = process.GetAst(filename); if (ast == null) { return functionName; } return QualifiedFunctionNameWalker.GetDisplayName( lineNo, functionName, ast, (a, n) => string.IsNullOrEmpty(a) ? n : Strings.DebugStackFrameNameInName.FormatUI(n, a) ); } } class DjangoStackFrame : PythonStackFrame { private readonly string _sourceFile; private readonly int _sourceLine; public DjangoStackFrame(PythonThread thread, string frameName, string filename, int startLine, int endLine, int lineNo, int argCount, int frameId, string sourceFile, int sourceLine) : base(thread, frameName, filename, startLine, endLine, lineNo, argCount, frameId, FrameKind.Django) { _sourceFile = sourceFile; _sourceLine = sourceLine; } /// <summary> /// The source .py file which implements the template logic. The normal filename is the /// name of the template it's self. /// </summary> public string SourceFile { get { return _sourceFile; } } /// <summary> /// The line in the source .py file which implements the template logic. /// </summary> public int SourceLine { get { return _sourceLine; } } } }
// -------------------------------------------------------------------------------------------- // <copyright file="DbFunctions.cs" company="Effort Team"> // Copyright (C) Effort Team // // 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> // -------------------------------------------------------------------------------------------- namespace Effort.Internal.DbCommandTreeTransformation { using System; using System.Linq; using System.Reflection; using Effort.Internal.Common; using System.Globalization; internal class DbFunctions { #region Math public static decimal? Truncate(decimal? input) { if (!input.HasValue) { return null; } return Math.Truncate(input.Value); } public static double? Truncate(double? input) { if (!input.HasValue) { return null; } return Math.Truncate(input.Value); } public static decimal? Ceiling(decimal? input) { if (!input.HasValue) { return null; } return Math.Ceiling(input.Value); } public static double? Ceiling(double? input) { if (!input.HasValue) { return null; } return Math.Ceiling(input.Value); } public static decimal? Floor(decimal? input) { if (!input.HasValue) { return null; } return Math.Floor(input.Value); } public static double? Floor(double? input) { if (!input.HasValue) { return null; } return Math.Floor(input.Value); } public static decimal? Round(decimal? input) { if (!input.HasValue) { return null; } return Math.Round(input.Value); } public static double? Round(double? input) { if (!input.HasValue) { return null; } return Math.Round(input.Value); } public static decimal? Round(decimal? input, int? decimals) { if (!input.HasValue || !decimals.HasValue) { return null; } return Math.Round(input.Value, decimals.Value); } public static double? Round(double? input, int? digits) { if (!input.HasValue || !digits.HasValue) { return null; } return Math.Round(input.Value, digits.Value); } public static double? Pow(double? x, double? y) { if (!x.HasValue || !y.HasValue) { return null; } return Math.Pow(x.Value, y.Value); } public static double? Abs(double? input) { if (!input.HasValue) { return null; } return Math.Abs(input.Value); } public static decimal? Abs(decimal? input) { if (!input.HasValue) { return null; } return Math.Abs(input.Value); } public static long? Abs(long? input) { if (!input.HasValue) { return null; } return Math.Abs(input.Value); } public static int? Abs(int? input) { if (!input.HasValue) { return null; } return Math.Abs(input.Value); } public static short? Abs(short? input) { if (!input.HasValue) { return null; } return Math.Abs(input.Value); } public static sbyte? Abs(sbyte? input) { if (!input.HasValue) { return null; } return Math.Abs(input.Value); } #endregion #region String public static string Concat(string a, string b) { if (a == null || b == null) { return null; } return String.Concat(a, b); } public static bool? Contains(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture return a.Contains(b); } public static string Left(string a, int? count) { if (a == null || count == null) { return null; } // TODO: culture return a.Substring(0, count.Value); } public static string Right(string a, int? count) { if (a == null || count == null) { return null; } // TODO: culture return a.Substring(a.Length - count.Value); } public static string ToUpper(string data) { if (data == null) { return null; } // TODO: culture? return data.ToUpper(); } public static string ToLower(string data) { if (data == null) { return null; } // TODO: culture? return data.ToLower(); } public static int? IndexOf(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture? return b.IndexOf(a) + 1; } public static string ReverseString(string data) { if (data == null) { return null; } return new string(data.ToCharArray().Reverse().ToArray()); } public static string Substring(string data, int? begin, int? length) { if (data == null || !begin.HasValue || !length.HasValue) { return null; } return data.Substring(begin.Value - 1, length.Value); } public static string Trim(string data) { if (data == null) { return null; } return data.Trim(); } public static string LTrim(string data) { if (data == null) { return null; } return data.TrimStart(); } public static string RTrim(string data) { if (data == null) { return null; } return data.TrimEnd(); } public static int? Length(string data) { if (data == null) { return null; } return data.Length; } // need case sensitive ?? public static string Replace(string data, string oldValue, string newValue) { if (data == null || oldValue == null || newValue == null) { return null; } return data.Replace(oldValue, newValue); } public static bool? StartsWith(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture return b.StartsWith(a); } public static bool? EndsWith(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture return b.EndsWith(a); } // see "private Expression CreateStringComparison(Expression left, Expression right, DbExpressionKind kind)", for case sensitive. internal static int CompareTo(string a, string b) { if (a == null && b == null) { return 0; } if (a == null || b == null) { return -1; } return a.CompareTo(b); } public static bool? ContainsCaseInsensitive(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture return a.ToLowerInvariant().Contains(b.ToLowerInvariant()); } public static int? IndexOfCaseInsensitive(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture? return b.IndexOf(a, StringComparison.OrdinalIgnoreCase) + 1; } public static bool? StartsWithCaseInsensitive(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture return b.StartsWith(a, StringComparison.OrdinalIgnoreCase); } public static bool? EndsWithCaseInsensitive(string a, string b) { if (a == null || b == null) { return null; } // TODO: culture return b.EndsWith(a, StringComparison.OrdinalIgnoreCase); } #endregion #region Datetime public static DateTime? CurrentDateTime() { return DateTime.Now; } public static DateTime? CurrentUtcDateTime() { return DateTime.UtcNow; } public static DateTime? CreateDateTime( int? year, int? month, int? day, int? hour, int? minute, int? second) { if (!year.HasValue || !month.HasValue || !day.HasValue || !hour.HasValue || !minute.HasValue || !second.HasValue) { return null; } return new DateTime( year.Value, month.Value, day.Value, hour.Value, minute.Value, second.Value); } public static int? GetYear(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Year; } public static int? GetMonth(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Month; } public static int? GetDay(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Day; } public static int? GetHour(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Hour; } public static int? GetMinute(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Minute; } public static int? GetSecond(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Second; } public static int? GetMillisecond(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Millisecond; } public static DateTime? AddYears(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddYears(value.Value); } public static DateTime? AddMonths(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddMonths(value.Value); } public static DateTime? AddDays(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddDays(value.Value); } public static DateTime? AddHours(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddHours(value.Value); } public static DateTime? AddMinutes(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddMinutes(value.Value); } public static DateTime? AddSeconds(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddSeconds(value.Value); } public static DateTime? AddMilliseconds(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddMilliseconds(value.Value); } public static DateTime? AddMicroseconds(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddTicks(value.Value * 10); } public static DateTime? AddNanoseconds(DateTime? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddTicks(value.Value / 100); } public static int? DiffYears(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return val2.Value.Year - val1.Value.Year; } public static int? DiffMonths(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (val2.Value.Year - val1.Value.Year) * 12 + (val2.Value.Month - val1.Value.Month); } public static int? DiffDays(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalDays); } public static int? DiffHours(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalHours); } public static int? DiffMinutes(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalMinutes); } public static int? DiffSeconds(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalSeconds); } public static int? DiffMilliseconds(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalMilliseconds); } public static int? DiffMicroseconds(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).Ticks / 10); } public static int? DiffNanoseconds(DateTime? val1, DateTime? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).Ticks * 100); } public static DateTime? TruncateTime(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.Date; } public static int? DayOfYear(DateTime? date) { if (!date.HasValue) { return null; } return date.Value.DayOfYear; } #endregion #region DateTimeOffset public static DateTimeOffset? CurrentDateTimeOffset() { return DateTimeOffset.Now; } public static DateTimeOffset? CreateDateTimeOffset( int? year, int? month, int? day, int? hour, int? minute, int? second, int? offsetMinutes) { if (!year.HasValue || !month.HasValue || !day.HasValue || !hour.HasValue || !minute.HasValue || !second.HasValue || !offsetMinutes.HasValue) { return null; } return new DateTimeOffset( year.Value, month.Value, day.Value, hour.Value, minute.Value, second.Value, TimeSpan.FromMinutes(offsetMinutes.Value)); } public static int? GetYear(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.Year; } public static int? GetMonth(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.Month; } public static int? GetDay(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.Day; } public static int? GetHour(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.Hour; } public static int? GetMinute(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.Minute; } public static int? GetSecond(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.Second; } public static int? GetMillisecond(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.Millisecond; } public static DateTimeOffset? AddYears(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddYears(value.Value); } public static DateTimeOffset? AddMonths(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddMonths(value.Value); } public static DateTimeOffset? AddDays(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddDays(value.Value); } public static DateTimeOffset? AddHours(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddHours(value.Value); } public static DateTimeOffset? AddMinutes(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddMinutes(value.Value); } public static DateTimeOffset? AddSeconds(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddSeconds(value.Value); } public static DateTimeOffset? AddMilliseconds(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddMilliseconds(value.Value); } public static DateTimeOffset? AddMicroseconds(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddTicks(value.Value * 10); } public static DateTimeOffset? AddNanoseconds(DateTimeOffset? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.AddTicks(value.Value / 100); } public static int? DiffYears(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return val2.Value.Year - val1.Value.Year; } public static int? DiffMonths(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (val2.Value.Year - val1.Value.Year) * 12 + (val2.Value.Month - val1.Value.Month); } public static int? DiffDays(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalDays); } public static int? DiffHours(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalHours); } public static int? DiffMinutes(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalMinutes); } public static int? DiffSeconds(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalSeconds); } public static int? DiffMilliseconds(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalMilliseconds); } public static int? DiffMicroseconds(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).Ticks / 10); } public static int? DiffNanoseconds(DateTimeOffset? val1, DateTimeOffset? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).Ticks * 100); } public static DateTimeOffset? TruncateTime(DateTimeOffset? date) { if (!date.HasValue) { return null; } return new DateTimeOffset(date.Value.Date, date.Value.Offset); } public static int? DayOfYear(DateTimeOffset? date) { if (!date.HasValue) { return null; } return date.Value.DayOfYear; } public static int? GetTotalOffsetMinutes(DateTimeOffset? date) { if (!date.HasValue) { return null; } return (int)date.Value.Offset.TotalMinutes; } #endregion #region Guid internal static int CompareTo(Guid? a, Guid? b) { if (a == null && b == null) { return 0; } if (a == null || b == null) { return -1; } return a.Value.CompareTo(b.Value); } #endregion #region Time public static TimeSpan? CreateTime( int? hour, int? minute, int? second) { if (!hour.HasValue || !minute.HasValue || !second.HasValue) { return null; } return new TimeSpan(hour.Value, minute.Value, second.Value); } public static int? GetHour(TimeSpan? time) { if (!time.HasValue) { return null; } return time.Value.Hours; } public static int? GetMinute(TimeSpan? time) { if (!time.HasValue) { return null; } return time.Value.Minutes; } public static int? GetSecond(TimeSpan? time) { if (!time.HasValue) { return null; } return time.Value.Seconds; } public static int? GetMillisecond(TimeSpan? time) { if (!time.HasValue) { return null; } return time.Value.Milliseconds; } public static TimeSpan? AddHours(TimeSpan? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.Add(TimeSpan.FromHours(value.Value)); } public static TimeSpan? AddMinutes(TimeSpan? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.Add(TimeSpan.FromMinutes(value.Value)); } public static TimeSpan? AddSeconds(TimeSpan? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.Add(TimeSpan.FromSeconds(value.Value)); } public static TimeSpan? AddMilliseconds(TimeSpan? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.Add(TimeSpan.FromMilliseconds(value.Value)); } public static TimeSpan? AddMicroseconds(TimeSpan? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.Add(TimeSpan.FromTicks(value.Value * 10)); } public static TimeSpan? AddNanoseconds(TimeSpan? date, int? value) { if (!date.HasValue || !value.HasValue) { return null; } return date.Value.Add(TimeSpan.FromTicks(value.Value / 100)); } public static int? DiffHours(TimeSpan? val1, TimeSpan? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalHours); } public static int? DiffMinutes(TimeSpan? val1, TimeSpan? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalMinutes); } public static int? DiffSeconds(TimeSpan? val1, TimeSpan? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalSeconds); } public static int? DiffMilliseconds(TimeSpan? val1, TimeSpan? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).TotalMilliseconds); } public static int? DiffMicroseconds(TimeSpan? val1, TimeSpan? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).Ticks / 10); } public static int? DiffNanoseconds(TimeSpan? val1, TimeSpan? val2) { if (!val1.HasValue || !val2.HasValue) { return null; } return (int)((val2.Value - val1.Value).Ticks * 100); } #endregion public static string ToString(object obj) { var format = CultureInfo.InvariantCulture; return String.Format(format, "{0}", obj); } public static T? TryParse<T>(string s) where T : struct { var format = CultureInfo.InvariantCulture; try { return (T)Convert.ChangeType(s, typeof(T), format); } catch { return null; } } } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces; using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes; using CyPhyGUIs; using System.Windows.Forms; using Microsoft.Win32; namespace CyPhy2SystemC { /// <summary> /// This class implements the necessary COM interfaces for a GME interpreter component. /// </summary> [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyPhy2SystemCInterpreter : IMgaComponentEx, IGMEVersionInfo, ICyPhyInterpreter { /// <summary> /// Contains information about the GUI event that initiated the invocation. /// </summary> public enum ComponentStartMode { GME_MAIN_START = 0, // Not used by GME GME_BROWSER_START = 1, // Right click in the GME Tree Browser window GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window GME_EMBEDDED_START = 3, // Not used by GME GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window GME_ICON_START = 32, // Not used by GME GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME } /// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); } /// <summary> /// The main entry point of the interpreter. A transaction is already open, /// GMEConsole is available. A general try-catch block catches all the exceptions /// coming from this function, you don't need to add it. For more information, see InvokeEx. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> /// <param name="currentobj">The model open in the active tab in GME. Its value is null if no model is open (no GME modeling windows open). </param> /// <param name="selectedobjs"> /// A collection for the selected model elements. It is never null. /// If the interpreter is invoked by the context menu of the GME Tree Browser, then the selected items in the tree browser. Folders /// are never passed (they are not FCOs). /// If the interpreter is invoked by clicking on the toolbar icon or the context menu of the modeling window, then the selected items /// in the active GME modeling window. If nothing is selected, the collection is empty (contains zero elements). /// </param> /// <param name="startMode">Contains information about the GUI event that initiated the invocation.</param> [ComVisible(false)] public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // TODO: Add your interpreter code GMEConsole.Out.WriteLine("Running interpreter..."); // Get RootFolder IMgaFolder rootFolder = project.RootFolder; GMEConsole.Out.WriteLine(rootFolder.Name); // To use the domain-specific API: // Create another project with the same name as the paradigm name // Copy the paradigm .mga file to the directory containing the new project // In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator) // Add a Reference in this project to the other project // Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file // if (currentobj.Meta.Name == "KindName") // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj); } #region IMgaComponentEx Members MgaGateway MgaGateway { get; set; } GMEConsole GMEConsole { get; set; } public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { // Need to call this interpreter in the same way as the MasterInterpreter will call it. // initialize main parameters var parameters = new InterpreterMainParameters() { Project = project, CurrentFCO = currentobj, SelectedFCOs = selectedobjs, StartModeParam = param }; this.mainParameters = parameters; parameters.ProjectDirectory = Path.GetDirectoryName(currentobj.Project.ProjectConnStr.Substring("MGA=".Length)); // set up the output directory MgaGateway.PerformInTransaction(delegate { string outputDirName = project.Name; if (currentobj != null) { outputDirName = currentobj.Name; } parameters.OutputDirectory = Path.GetFullPath(Path.Combine( parameters.ProjectDirectory, "results", outputDirName)); //this.Parameters.PackageName = SystemC.Factory.GetModifiedName(currentobj.Name); }); PreConfigArgs preConfigArgs = new PreConfigArgs(); preConfigArgs.ProjectDirectory = parameters.ProjectDirectory; // call the preconfiguration with no parameters and get preconfig var preConfig = this.PreConfig(preConfigArgs); // get previous GUI config var previousConfig = META.ComComponent.DeserializeConfiguration( parameters.ProjectDirectory, typeof(CyPhy2SystemC_Settings), this.ComponentProgID); // get interpreter config through GUI var config = this.DoGUIConfiguration(preConfig, previousConfig); if (config == null) { GMEConsole.Warning.WriteLine("Operation cancelled by the user."); return; } // if config is valid save it and update it on the file system META.ComComponent.SerializeConfiguration(parameters.ProjectDirectory, config, this.ComponentProgID); // assign the new configuration to mainParameters parameters.config = config; // call the main (ICyPhyComponent) function this.Main(parameters); } catch (Exception ex) { GMEConsole.Error.WriteLine("Interpretation failed {0}<br>{1}", ex.Message, ex.StackTrace); } finally { if (MgaGateway != null && MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } } private ComponentStartMode Convert(int param) { switch (param) { case (int)ComponentStartMode.GME_BGCONTEXT_START: return ComponentStartMode.GME_BGCONTEXT_START; case (int)ComponentStartMode.GME_BROWSER_START: return ComponentStartMode.GME_BROWSER_START; case (int)ComponentStartMode.GME_CONTEXT_START: return ComponentStartMode.GME_CONTEXT_START; case (int)ComponentStartMode.GME_EMBEDDED_START: return ComponentStartMode.GME_EMBEDDED_START; case (int)ComponentStartMode.GME_ICON_START: return ComponentStartMode.GME_ICON_START; case (int)ComponentStartMode.GME_MAIN_START: return ComponentStartMode.GME_MAIN_START; case (int)ComponentStartMode.GME_MENU_START: return ComponentStartMode.GME_MENU_START; case (int)ComponentStartMode.GME_SILENT_MODE: return ComponentStartMode.GME_SILENT_MODE; } return ComponentStartMode.GME_SILENT_MODE; } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion #region CyPhyGUIs /// <summary> /// Result of the latest run of this interpreter. /// </summary> private InterpreterResult result = new InterpreterResult(); /// <summary> /// Parameter of this run. /// </summary> private IInterpreterMainParameters mainParameters { get; set; } /// <summary> /// Output directory where all files must be generated /// </summary> private string OutputDirectory { get { return this.mainParameters.OutputDirectory; } } private void UpdateSuccess(string message, bool success) { this.result.Success = this.result.Success && success; this.runtime.Enqueue(new Tuple<string, TimeSpan>(message, DateTime.Now - this.startTime)); if (success) { GMEConsole.Info.WriteLine("{0} : OK", message); } else { GMEConsole.Error.WriteLine("{0} : FAILED", message); } } /// <summary> /// Name of the log file. (It is not a full path) /// </summary> private string LogFileFilename { get; set; } /// <summary> /// Full path to the log file. /// </summary> private string LogFilePath { get { return Path.Combine(this.result.LogFileDirectory, this.LogFileFilename); } } /// <summary> /// ProgId of the configuration class of this interpreter. /// </summary> public string InterpreterConfigurationProgId { get { return (typeof(CyPhy2SystemC_Settings).GetCustomAttributes(typeof(ProgIdAttribute), false)[0] as ProgIdAttribute).Value; } } /// <summary> /// Preconfig gets called first. No transaction is open, but one may be opened. /// In this function model may be processed and some object ids get serialized /// and returned as preconfiguration (project-wise configuration). /// </summary> /// <param name="preConfigParameters"></param> /// <returns>Null if no configuration is required by the DoGUIConfig.</returns> public IInterpreterPreConfiguration PreConfig(IPreConfigParameters preConfigParameters) { //var preConfig = new CyPhy2SystemC_v2PreConfiguration() //{ // ProjectDirectory = preConfigParameters.ProjectDirectory //}; //return preConfig; return null; } /// <summary> /// Shows a form for the user to select/change settings through a GUI. All interactive /// GUI operations MUST happen within this function scope. /// </summary> /// <param name="preConfig">Result of PreConfig</param> /// <param name="previousConfig">Previous configuration to initialize the GUI.</param> /// <returns>Null if operation is cancelled by the user. Otherwise returns with a new /// configuration object.</returns> public IInterpreterConfiguration DoGUIConfiguration( IInterpreterPreConfiguration preConfig, IInterpreterConfiguration previousConfig) { #pragma warning disable 0219 DialogResult ok = DialogResult.Cancel; #pragma warning restore 0219 var settings = previousConfig as CyPhy2SystemC_Settings; if (settings == null) { settings = new CyPhy2SystemC_Settings(); } RegistryKey vc_full; RegistryKey vc_express; using (var hklm_32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) using (vc_full = hklm_32.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\Setup\VC")) using (vc_express = hklm_32.OpenSubKey(@"SOFTWARE\Microsoft\VCExpress\10.0\Setup\VC")) { if (vc_full == null && vc_express == null) { string msg = "Visual Studio 2010 or Visual C++ 2010 Express is not detected on your system. One of the two is required to run CyPhy2SystemC.\n\nAttempt to run CyPhy2SystemC anyway?"; if (MessageBox.Show(msg, "CyPhy2SystemC", MessageBoxButtons.YesNo) == DialogResult.No) { return null; } } } //using (MainForm mf = new MainForm(settings, (preConfig as CyPhy2SystemC_v2PreConfiguration).ProjectDirectory)) //{ // show main form // ok = mf.ShowDialog(); //} //if (ok == DialogResult.OK) { return settings; } //return null; } private Queue<Tuple<string, TimeSpan>> runtime = new Queue<Tuple<string, TimeSpan>>(); private DateTime startTime = DateTime.Now; /// <summary> /// No GUI and interactive elements are allowed within this function. /// </summary> /// <param name="parameters">Main parameters for this run and GUI configuration.</param> /// <returns>Result of the run, which contains a success flag.</returns> public IInterpreterResult Main(IInterpreterMainParameters parameters) { this.runtime.Clear(); this.mainParameters = parameters; var configSuccess = this.mainParameters != null; this.UpdateSuccess("Configuration", configSuccess); this.result.Labels = "SystemC"; this.result.LogFileDirectory = Path.Combine(this.mainParameters.ProjectDirectory, "log"); this.LogFileFilename = this.ComponentName + "." + System.Diagnostics.Process.GetCurrentProcess().Id + ".log"; try { META.Logger.AddFileListener(this.LogFilePath, this.ComponentName, this.mainParameters.Project); } catch (Exception ex) // logger construction may fail, which should be an ignorable exception { GMEConsole.Warning.WriteLine("Error in Logger construction: {0}", ex.Message); } try { MgaGateway.PerformInTransaction(delegate { this.WorkInMainTransaction(); }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: true ); this.PrintRuntimeStatistics(); if (this.result.Success) { GMEConsole.Info.WriteLine("Generated files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>", this.mainParameters.OutputDirectory); GMEConsole.Info.WriteLine("SystemC Composer has finished. [SUCCESS: {0}, Labels: {1}]", this.result.Success, this.result.Labels); } else { GMEConsole.Error.WriteLine("SystemC Composer failed! See error messages above."); } } catch (Exception ex) { GMEConsole.Error.WriteLine("Exception: {0}<br> {1}", ex.Message, ex.StackTrace); } finally { if (MgaGateway != null && MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } META.Logger.RemoveFileListener(this.ComponentName); //var SystemCSettings = this.mainParameters.config as CyPhy2SystemC_Settings; return this.result; } private void PrintRuntimeStatistics() { GMEConsole.Info.WriteLine("======================================================"); GMEConsole.Info.WriteLine("Start time: {0}", this.startTime); foreach (var time in this.runtime) { GMEConsole.Info.WriteLine("{0} = {1}", time.Item1, time.Item2); } GMEConsole.Info.WriteLine("======================================================"); } #endregion #region Dependent Interpreters private bool CallElaborator( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, bool expand = true) { try { // call elaborator and expand the references Type t = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate"); IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx; elaborator.Initialize(project); if (expand) { elaborator.ComponentParameter["automated_expand"] = "true"; } else { elaborator.ComponentParameter["automated_collapse"] = "true"; } GMEConsole.Info.WriteLine("Elaborating model..."); System.Windows.Forms.Application.DoEvents(); elaborator.InvokeEx(project, currentobj, selectedobjs, param); CyPhyCOMInterfaces.IMgaTraceability traceability = elaborator.ComponentParameter["traceability"] as CyPhyCOMInterfaces.IMgaTraceability; this.result.Traceability = new META.MgaTraceability(); if (traceability != null) { traceability.CopyTo(this.result.Traceability); } GMEConsole.Info.WriteLine("Elaboration is done."); System.Windows.Forms.Application.DoEvents(); // TODO: get exception message(s) from elaborator string msgs = elaborator.ComponentParameter["exception"] as string; if (string.IsNullOrWhiteSpace(msgs) == false) { GMEConsole.Error.WriteLine("Elaborator exception occurred: {0}", msgs); System.Windows.Forms.Application.DoEvents(); throw new Exception(msgs); } } catch (Exception ex) { GMEConsole.Error.WriteLine(ex); return false; } return true; } private MgaFCO SurrogateMaster( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, bool expand = true) { MgaFolder f = currentobj.ParentFolder; if (f == null) { throw new Exception("Testbench does not have a TestFolder parent!"); } MgaFolder fNew = f.CreateFolder(f.MetaFolder); fNew.Name = currentobj.Name + DateTime.Now.ToString(" (MM-dd-yyyy HH:mm:ss)"); MgaFCO newTestbench = fNew.CopyFCODisp(currentobj); //newTestbench.Name += " TestName"; return newTestbench; } #endregion #region CyPhy2SystemC Specific code /// <summary> /// This function does the job. CyPhy2SystemC translation. /// </summary> private void WorkInMainTransaction() { this.result.Success = true; // 1) check model, if fails return success = false // Make attached library paths available for Checker //GMEConsole.Info.WriteLine("Checking rules..."); //Rules.Checker.GMEConsole = GMEConsole; //var checker = new Rules.Checker(this.mainParameters); //var successRules = checker.Check(this.result.Traceability); //this.UpdateSuccess("Model check", successRules); //if (this.result.Success == false) //{ // checker.PrintDetails(); // return; //} // surrogate the master interpreter's role - till we figure out a way to hook into the master interp //{ // MgaFCO newCurrent = this.SurrogateMaster(this.mainParameters.Project, this.mainParameters.CurrentFCO, this.mainParameters.SelectedFCOs, // this.mainParameters.StartModeParam); // var newParameters = new InterpreterMainParameters() // { // Project = this.mainParameters.Project, // CurrentFCO = newCurrent, // SelectedFCOs = this.mainParameters.SelectedFCOs, // StartModeParam = this.mainParameters.StartModeParam, // config = this.mainParameters.config, // OutputDirectory = this.mainParameters.OutputDirectory, // ProjectDirectory = this.mainParameters.ProjectDirectory // }; // this.mainParameters = newParameters; //} // 2) try to call dependencies - elaborate, cyber, Bond Graph interpreter var elaboratorSuccess = this.CallElaborator(this.mainParameters.Project, this.mainParameters.CurrentFCO, this.mainParameters.SelectedFCOs, this.mainParameters.StartModeParam); this.UpdateSuccess("Elaborator", elaboratorSuccess); bool successTranslation = true; try { // Generate SystemC source code and projects SystemC.CodeGenerator.GMEConsole = GMEConsole; var systemCCodeGenerator = new SystemC.CodeGenerator(this.mainParameters); systemCCodeGenerator.GenerateSystemCCode(); successTranslation = true; // Generate build and test job String p_vcsln = Path.Combine(OutputDirectory, "SystemCTestBench.sln"); String p_cmd = Path.Combine(OutputDirectory, "build.cmd"); String sim_exe_name = "Release\\SystemCTestBench.exe"; String p_exe = Path.Combine(OutputDirectory, sim_exe_name); // See if "msbuild" is in path. // If not, check the registry to try to get a path for it. // Used this technique to get registry key: http://stackoverflow.com/a/445323 String s_RUNCMD = "@ECHO OFF" + Environment.NewLine + "setlocal ENABLEEXTENSIONS" + Environment.NewLine + "set KEY_NAME=\"HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0\"" + Environment.NewLine + "set VALUE_NAME=\"MSBuildToolsPath\"" + Environment.NewLine + "FOR /F \"usebackq skip=2 tokens=1-3\" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (" + Environment.NewLine + " set ValueName=%%A" + Environment.NewLine + " set ValueType=%%B" + Environment.NewLine + " set ValueValue=%%C" + Environment.NewLine + " set _msbuild=%%Cmsbuild.exe" + Environment.NewLine + ")" + Environment.NewLine + String.Format("%_msbuild% {0} /p:Configuration=Release;VCTargetsPath=\"C:\\Program Files (x86)\\MSBuild\\Microsoft.Cpp\\v4.0\"\\ /p:Platform=Win32 /m", Path.GetFileName(p_vcsln)) + Environment.NewLine + "EXIT /b %errorlevel%" + Environment.NewLine; File.WriteAllText(p_cmd, s_RUNCMD); File.WriteAllText(Path.Combine(OutputDirectory, "run_simulation.cmd"), "@ECHO OFF" + Environment.NewLine + "PUSHD %~dp0" + Environment.NewLine + sim_exe_name + Environment.NewLine + "ECHO Press any key to exit" + Environment.NewLine + "PAUSE >nul" + Environment.NewLine); this.result.RunCommand = Path.GetFileName(p_cmd); } catch (Exception ex) { GMEConsole.Error.WriteLine(ex); successTranslation = false; } this.UpdateSuccess("SystemC translation", successTranslation); } #endregion } }
// <copyright file="BindingTests.cs" company="MIT License"> // Licensed under the MIT License. See LICENSE file in the project root for license information. // </copyright> namespace SmallBasic.Tests.Compiler { using System.Threading.Tasks; using FluentAssertions; using SmallBasic.Compiler; using SmallBasic.Compiler.Diagnostics; using Xunit; public sealed class BindingTests : IClassFixture<CultureFixture> { [Fact] public void CallingNonexistentSubroutine() { new SmallBasicCompilation("test()").VerifyDiagnostics( // test() // ^^^^^^ // This expression is not a valid submodule or method to be called. new Diagnostic(DiagnosticCode.UnsupportedInvocationBaseExpression, ((0, 0), (0, 5)))); } [Fact] public void ItReportsInForLoopFromExpression() { new SmallBasicCompilation(@" For x = TextWindow.WriteLine("""") To 5 EndFor").VerifyDiagnostics( // For x = TextWindow.WriteLine("") To 5 // ^^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 8), (1, 31)))); } [Fact] public void ItReportsInForLoopToExpression() { new SmallBasicCompilation(@" For x = 1 To TextWindow.WriteLine("""") EndFor").VerifyDiagnostics( // For x = 1 To TextWindow.WriteLine("") // ^^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 13), (1, 36)))); } [Fact] public void ItReportsInForLoopStepExpression() { new SmallBasicCompilation(@" For x = 1 To 5 Step TextWindow.WriteLine("""") EndFor").VerifyDiagnostics( // For x = 1 To 5 Step TextWindow.WriteLine("") // ^^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 20), (1, 43)))); } [Fact] public void ItReportsNonValueInIfStatementExpression() { new SmallBasicCompilation(@" If TextWindow.WriteLine("""") Then EndIf").VerifyDiagnostics( // If TextWindow.WriteLine("") Then // ^^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 3), (1, 26)))); } [Fact] public void ItReportsNonValueInIfElseStatementExpression() { new SmallBasicCompilation(@" If ""True"" Then ElseIf TextWindow.WriteLine("""") Then EndIf").VerifyDiagnostics( // ElseIf TextWindow.WriteLine("") Then // ^^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((2, 7), (2, 30)))); } [Fact] public void ItReportsNonValueInWhileStatementExpression() { new SmallBasicCompilation(@" While TextWindow.WriteLine("""") EndWhile").VerifyDiagnostics( // While TextWindow.WriteLine("") // ^^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 6), (1, 29)))); } [Fact] public void ItReportsMultipleSubModulesWithTheSameName() { new SmallBasicCompilation(@" Sub x EndSub Sub y EndSub Sub x EndSub").VerifyDiagnostics( // Sub x // ^ // A submodule with the same name 'x' is already defined in the same program. new Diagnostic(DiagnosticCode.TwoSubModulesWithTheSameName, ((5, 4), (5, 4)), "x")); } [Fact] public void ItReportsAssigningNonSubModuleToEvent() { new SmallBasicCompilation(@" Sub x EndSub Controls.ButtonClicked = x Controls.ButtonClicked = y").VerifyDiagnostics( // Controls.ButtonClicked = y // ^^^^^^^^^^^^^^^^^^^^^^ // You can only assign submodules to events. new Diagnostic(DiagnosticCode.AssigningNonSubModuleToEvent, ((5, 0), (5, 21)))); } [Fact] public void ItReportsPassingArgumentsToModules() { new SmallBasicCompilation(@" Sub x EndSub x(0)").VerifyDiagnostics( // x(0) // ^^^^ // You are passing '1' arguments to this method, while it expects '0' arguments. new Diagnostic(DiagnosticCode.UnexpectedArgumentsCount, ((4, 0), (4, 3)), "1", "0")); } [Fact] public void ItReportsGoToNonExistentLabel() { new SmallBasicCompilation(@" label1: GoTo label1 GoTo label2").VerifyDiagnostics( // GoTo label2 // ^^^^^^ // The label 'label2' is not defined in the same module. new Diagnostic(DiagnosticCode.GoToUndefinedLabel, ((3, 5), (3, 10)), "label2")); } [Fact] public void ItReportsGoToLabelInMainModuleToLabelInSubModule() { new SmallBasicCompilation(@" Sub x label1: EndSub GoTo label1").VerifyDiagnostics( // GoTo label1 // ^^^^^^ // The label 'label1' is not defined in the same module. new Diagnostic(DiagnosticCode.GoToUndefinedLabel, ((4, 5), (4, 10)), "label1")); } [Fact] public void ItReportsGoToLabelInSubModuleToLabelInMainModule() { new SmallBasicCompilation(@" Sub x GoTo label1 EndSub label1:").VerifyDiagnostics( // GoTo label1 // ^^^^^^ // The label 'label1' is not defined in the same module. new Diagnostic(DiagnosticCode.GoToUndefinedLabel, ((2, 9), (2, 14)), "label1")); } [Fact] public void ItReportsDuplicateLabelsInMainModule() { new SmallBasicCompilation(@" label1: label1: Sub x label1: EndSub").VerifyDiagnostics( // label1: // ^^^^^^ // A label with the same name 'label1' is already defined. new Diagnostic(DiagnosticCode.TwoLabelsWithTheSameName, ((2, 0), (2, 5)), "label1")); } [Fact] public void ItReportsDuplicateLabelsInSubModule() { new SmallBasicCompilation(@" label1: Sub x label1: label1: EndSub").VerifyDiagnostics( // label1: // ^^^^^^ // A label with the same name 'label1' is already defined. new Diagnostic(DiagnosticCode.TwoLabelsWithTheSameName, ((4, 4), (4, 9)), "label1")); } [Fact] public void ItReportsOnlyOneErrorOnExpressionsThatHaveMultipleErrors() { new SmallBasicCompilation(@" TextWindow.WriteLine() = 5").VerifyDiagnostics( // TextWindow.WriteLine() = 5 // ^^^^^^^^^^^^^^^^^^^^^^ // You are passing '0' arguments to this method, while it expects '1' arguments. new Diagnostic(DiagnosticCode.UnexpectedArgumentsCount, ((1, 0), (1, 21)), "0", "1")); new SmallBasicCompilation(@" TextWindow.WriteLine(4) = 5").VerifyDiagnostics( // TextWindow.WriteLine(4) = 5 // ^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 0), (1, 22)))); } [Fact] public void ItReportsStandAloneVariables() { new SmallBasicCompilation(@" x").VerifyDiagnostics( // x // ^ // This expression returns a result. Did you mean to assign it to a variable? new Diagnostic(DiagnosticCode.UnassignedExpressionStatement, ((1, 0), (1, 0)))); } [Fact] public void ItReportsStandAloneExpressions() { new SmallBasicCompilation(@" x and y").VerifyDiagnostics( // x and y // ^^^^^^^ // This expression returns a result. Did you mean to assign it to a variable? new Diagnostic(DiagnosticCode.UnassignedExpressionStatement, ((1, 0), (1, 6)))); } [Fact] public void ItReportsStandAloneLibrary() { new SmallBasicCompilation(@" TextWindow").VerifyDiagnostics( // TextWindow // ^^^^^^^^^^ // This expression is not a valid statement. new Diagnostic(DiagnosticCode.InvalidExpressionStatement, ((1, 0), (1, 9)))); } [Fact] public void ItReportsStandAloneLibraryMethod() { new SmallBasicCompilation(@" TextWindow.WriteLine").VerifyDiagnostics( // TextWindow.WriteLine // ^^^^^^^^^^^^^^^^^^^^ // This expression is not a valid statement. new Diagnostic(DiagnosticCode.InvalidExpressionStatement, ((1, 0), (1, 19)))); } [Fact] public void ItReportsStandAloneSubModule() { new SmallBasicCompilation(@" Sub x EndSub x").VerifyDiagnostics( // x // ^ // This expression is not a valid statement. new Diagnostic(DiagnosticCode.InvalidExpressionStatement, ((3, 0), (3, 0)))); } [Fact] public void ItReportsArrayAccessIntoLibraryType() { new SmallBasicCompilation(@" x = TextWindow[0]").VerifyDiagnostics( // x = TextWindow[0] // ^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 4), (1, 13)))); } [Fact] public void ItReportsArrayAccessIntoLibraryMethod() { new SmallBasicCompilation(@" x = TextWindow.WriteLine[0]").VerifyDiagnostics( // x = TextWindow.WriteLine[0] // ^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 4), (1, 23)))); } [Fact] public void ItReportsArrayAccessIntoLibraryProperty() { new SmallBasicCompilation(@" x = Clock.Time[0]").VerifyDiagnostics( // x = Clock.Time[0] // ^^^^^^^^^^ // This expression is not a valid array. new Diagnostic(DiagnosticCode.UnsupportedArrayBaseExpression, ((1, 4), (1, 13)))); } [Fact] public void ItReportsArrayAccessIntoLibraryEvent() { new SmallBasicCompilation(@" x = Controls.ButtonClicked[0]").VerifyDiagnostics( // x = Controls.ButtonClicked[0] // ^^^^^^^^^^^^^^^^^^^^^^ // This expression is not a valid array. new Diagnostic(DiagnosticCode.UnsupportedArrayBaseExpression, ((1, 4), (1, 25)))); } [Fact] public void ItReportsIndexerExpressionWithoutValue() { new SmallBasicCompilation(@" x = y[TextWindow]").VerifyDiagnostics( // x = y[TextWindow] // ^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 6), (1, 15)))); } [Fact] public void ItReportsArgumentExpressionWithoutValue() { new SmallBasicCompilation(@" TextWindow.WriteLine(TextWindow)").VerifyDiagnostics( // TextWindow.WriteLine(TextWindow) // ^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 21), (1, 30)))); } [Fact] public void ItReportsInvalidArgumentCountForMethodInvocations() { new SmallBasicCompilation(@" TextWindow.WriteLine(1, 2)").VerifyDiagnostics( // TextWindow.WriteLine(1, 2) // ^^^^^^^^^^^^^^^^^^^^^^^^^^ // You are passing '2' arguments to this method, while it expects '1' arguments. new Diagnostic(DiagnosticCode.UnexpectedArgumentsCount, ((1, 0), (1, 25)), "2", "1")); } [Fact] public void ItReportsInvokingNonMethods() { new SmallBasicCompilation(@" TextWindow.WriteLine(1)()").VerifyDiagnostics( // TextWindow.WriteLine(1)() // ^^^^^^^^^^^^^^^^^^^^^^^^^ // This expression is not a valid submodule or method to be called. new Diagnostic(DiagnosticCode.UnsupportedInvocationBaseExpression, ((1, 0), (1, 24)))); } [Fact] public void ItReportsMemberAccessToNonLibraries() { new SmallBasicCompilation(@" x = y.z").VerifyDiagnostics( // x = y.z // ^ // You can only use dot access with a library. Did you mean to use an existing library instead? new Diagnostic(DiagnosticCode.UnsupportedDotBaseExpression, ((1, 4), (1, 4)))); } [Fact] public void ItReportsNonExistentLibraryMembers() { new SmallBasicCompilation(@" x = TextWindow.Anything").VerifyDiagnostics( // x = TextWindow.Anything // ^^^^^^^^^^^^^^^^^^^ // The library 'TextWindow' has no member named 'Anything'. new Diagnostic(DiagnosticCode.LibraryMemberNotFound, ((1, 4), (1, 22)), "TextWindow", "Anything")); } [Fact] public void ItReportsAssigningToLibraryMethodInvocation() { new SmallBasicCompilation(@" TextWindow.WriteLine(0) = 5").VerifyDiagnostics( // TextWindow.WriteLine(0) = 5 // ^^^^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 0), (1, 22)))); } [Fact] public void ItReportsAssigningToPropertyWithoutASetter() { new SmallBasicCompilation(@" Clock.Time = 5").VerifyDiagnostics( // Clock.Time = 5 // ^^^^^^^^^^ // Property 'Clock.Time' cannot be assigned to. It is ready only. new Diagnostic(DiagnosticCode.PropertyHasNoSetter, ((1, 0), (1, 9)), "Clock", "Time")); } [Fact] public void ItReportsAssigningToBinaryExpression() { new SmallBasicCompilation(@" x and y = 5").VerifyDiagnostics( // x and y = 5 // ^^^^^^^^^^^ // This expression returns a result. Did you mean to assign it to a variable? new Diagnostic(DiagnosticCode.UnassignedExpressionStatement, ((1, 0), (1, 10)))); } [Fact] public void ItReportsAssigningToLibraryType() { new SmallBasicCompilation(@" TextWindow = 5").VerifyDiagnostics( // TextWindow = 5 // ^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 0), (1, 9)))); } [Fact] public void ItReportsAssigningToLibraryMethod() { new SmallBasicCompilation(@" TextWindow.WriteLine = 5").VerifyDiagnostics( // TextWindow.WriteLine = 5 // ^^^^^^^^^^^^^^^^^^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((1, 0), (1, 19)))); } [Fact] public void ItReportsAssigningToSubModuleInvocation() { new SmallBasicCompilation(@" Sub x EndSub x() = 5").VerifyDiagnostics( // x() = 5 // ^^^ // This expression must have a value to be used here. new Diagnostic(DiagnosticCode.ExpectedExpressionWithAValue, ((3, 0), (3, 2)))); } [Fact] public void ItReportsDeprecatedMethods() { new SmallBasicCompilation(@" x = Program.GetArgument(0)").VerifyDiagnostics( // x = Program.GetArgument(0) // ^^^^^^^^^^^^^^^^^^^ // The library member 'Program.GetArgument' was available in older versions only, and has not been made available in this version yet. new Diagnostic(DiagnosticCode.LibraryMemberDeprecatedFromOlderVersion, ((1, 4), (1, 22)), "Program", "GetArgument")); } [Fact] public void ItReportsDesktopFunctionsInEditor() { new SmallBasicCompilation(@" File.DeleteFile(""a.txt"")", isRunningOnDesktop: true).VerifyDiagnostics(); new SmallBasicCompilation(@" File.DeleteFile(""a.txt"")", isRunningOnDesktop: false).VerifyDiagnostics( // File.DeleteFile("a.txt") // ^^^^^^^^^^^^^^^ // The library member 'File.DeleteFile' cannot be used in the online editor. Please download the desktop editor to use it. new Diagnostic(DiagnosticCode.LibraryMemberNeedsDesktop, ((1, 0), (1, 14)), "File", "DeleteFile")); } } }
using System; using System.Collections.Generic; using System.Linq; using NetGore.Collections; namespace NetGore { /// <summary> /// Base class for a filter for a text filter. Instantiable derived classes must include an empty constructor. /// All <see cref="TextFilter"/>s implement a case-insensitive filtering. /// </summary> public abstract class TextFilter { /// <summary> /// The text filter instances with their name as the key. /// </summary> static readonly Dictionary<string, TextFilter> _filterInstancesByName = new Dictionary<string, TextFilter>(StringComparer.Ordinal); string _filterString = null; bool _passAll = true; /// <summary> /// Initializes the <see cref="TextFilter"/> class. /// </summary> static TextFilter() { new TypeFactory(CreateTypeFilter(), FactoryTypeAdded); } /// <summary> /// Initializes a new instance of the <see cref="TextFilter"/> class. /// </summary> protected TextFilter() { Invert = false; } /// <summary> /// Gets the display name of the filter. /// </summary> public string DisplayName { get { return DisplayNameInternal; } } /// <summary> /// When overridden in the derived class, gets the unique name of this <see cref="TextFilter"/> implementation. /// This value must be costant for every instance of this filter, and must be unique for the <see cref="Type"/>. /// </summary> protected abstract string DisplayNameInternal { get; } /// <summary> /// Gets the string currently being used as the filter. /// </summary> public string FilterString { get { return _filterString; } } /// <summary> /// Gets the name of all the valid text filters. /// </summary> public static IEnumerable<string> GetFilterNames { get { return _filterInstancesByName.Keys; } } /// <summary> /// Gets or sets if the filter results are to be inverted. If false, only the items that match the filter /// will be returned when filter. If true, only items that do NOT match the filter will be returned. Default /// is false. /// </summary> public bool Invert { get; set; } /// <summary> /// Gets the filter to use for filtering the types. /// </summary> /// <returns>The filter to use for filtering the types.</returns> static Func<Type, bool> CreateTypeFilter() { var filterCreator = new TypeFilterCreator { IsClass = true, IsAbstract = false, Subclass = typeof(TextFilter), ConstructorParameters = Type.EmptyTypes, RequireConstructor = true }; return filterCreator.GetFilter(); } /// <summary> /// Creates a deep copy of the filter. /// </summary> /// <returns>A deep copy of the filter.</returns> public TextFilter DeepCopy() { return DeepCopyInternal(); } /// <summary> /// When overridden in the derived class, creates a deep copy of this filter. /// </summary> /// <returns>The deep copy of this filter.</returns> protected abstract TextFilter DeepCopyInternal(); /// <summary> /// Handles when a <see cref="TextFilter"/> type is added to the factory. /// </summary> /// <param name="factory">The factory.</param> /// <param name="e">The <see cref="NetGore.Collections.TypeFactoryLoadedEventArgs"/> instance containing the event data.</param> /// <exception cref="TypeException">Duplicate text filter names found.</exception> static void FactoryTypeAdded(TypeFactory factory, TypeFactoryLoadedEventArgs e) { var instance = (TextFilter)TypeFactory.GetTypeInstance(e.LoadedType); var key = instance.DisplayName; // Ensure the name is not already in use if (_filterInstancesByName.ContainsKey(key)) { const string errmsg = "A text filter with the name `{0}` already exists!"; throw new TypeException(string.Format(errmsg, key), e.LoadedType); } // Add the instace _filterInstancesByName.Add(key, instance); } /// <summary> /// When overridden in the derived class, checks if the given <paramref name="text"/> passes the filter. /// </summary> /// <param name="text">The text to test the filter on.</param> /// <returns>True if the <paramref name="text"/> passes the filter; otherwise false.</returns> protected abstract bool FilterInternal(string text); /// <summary> /// Gets the items that pass the filter. /// </summary> /// <typeparam name="T">The type of items.</typeparam> /// <param name="items">The items to pass through the text filter.</param> /// <returns>The items that passed the filter.</returns> public IEnumerable<T> FilterItems<T>(IEnumerable<T> items) { if (_passAll) return items; return items.Where(x => FilterInternal(x.ToString())); } /// <summary> /// Gets the items that pass the filter. /// </summary> /// <typeparam name="T">The type of items.</typeparam> /// <param name="items">The items to pass through the text filter.</param> /// <param name="textSelector">The func used to select the string for the corresponding item. /// The default method is to just use <see cref="object.ToString"/>.</param> /// <returns>The items that passed the filter.</returns> public IEnumerable<T> FilterItems<T>(IEnumerable<T> items, Func<T, string> textSelector) { if (_passAll) return items; return items.Where(x => FilterInternal(textSelector(x))); } /// <summary> /// Gets the items that pass the filter. /// </summary> /// <param name="items">The items to pass through the text filter.</param> /// <returns>The items that passed the filter.</returns> public IEnumerable<string> FilterItems(IEnumerable<string> items) { if (_passAll) return items; return items.Where(FilterInternal); } /// <summary> /// Tries to create a <see cref="TextFilter"/> instance by its unique name. /// </summary> /// <param name="name">The name of the text filter to create the instance of.</param> /// <returns>The instance of the filter with the given <paramref name="name"/>, or null if the /// <paramref name="name"/> is invalid.</returns> public static TextFilter TryCreateInstance(string name) { TextFilter instance; if (_filterInstancesByName.TryGetValue(name, out instance)) return instance.DeepCopy(); return null; } /// <summary> /// Tries to set the filter. /// </summary> /// <param name="filter">The filter string. If null or empty, all items sent to the filter /// will pass and this method will return true.</param> /// <returns>True if the filter was successfully set; otherwise false.</returns> public bool TrySetFilter(string filter) { // Check for the same filter if (StringComparer.OrdinalIgnoreCase.Equals(_filterString, filter)) return true; _filterString = filter; // Check for an empty filter if (string.IsNullOrEmpty(filter)) { _passAll = true; return true; } _passAll = false; // Try to set the filter return TrySetFilterInternal(filter); } /// <summary> /// When overridden in the derived class, tries to set the filter. /// </summary> /// <param name="filter">The filter to try to use. This value will never be a null or empty string.</param> /// <returns>True if the filter was successfully set; otherwise false.</returns> protected abstract bool TrySetFilterInternal(string filter); } }
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Kooboo.CMS.Content.Models; using Kooboo.Runtime.Serialization; using System.IO; using Kooboo.CMS.Content.Caching; using Kooboo.CMS.Caching; using Aliyun.OSS; using Kooboo.Web.Script.Serialization; using Kooboo.HealthMonitoring; using Kooboo.IO; namespace Kooboo.CMS.Content.Persistence.QcloudCOS { public static class MediaFolders { static System.Threading.ReaderWriterLockSlim locker = new System.Threading.ReaderWriterLockSlim(); public static void AddFolder(MediaFolder folder) { locker.EnterWriteLock(); try { var folders = GetList(folder.Repository); var name = folder.FullName.Trim('~'); if (!folders.ContainsKey(name)) { folder.UtcCreationDate = DateTime.UtcNow; folders[name] = folder; SaveList(folder.Repository, folders); } } finally { locker.ExitWriteLock(); } } public static MediaFolder GetFolder(MediaFolder dummy) { locker.EnterReadLock(); try { var folders = GetList(dummy.Repository); if (folders.ContainsKey(dummy.FullName)) { return ToMediaFolder(dummy.Repository, dummy.FullName, folders[dummy.FullName]); } return null; } finally { locker.ExitReadLock(); } } public static void RemoveFolder(MediaFolder folder) { locker.EnterWriteLock(); try { var storeList = GetList(folder.Repository); var mediaFolders = ToMediaFolders(folder.Repository, storeList); if (storeList.ContainsKey(folder.FullName)) { storeList.Remove(folder.FullName); foreach (var item in mediaFolders) { if (item.Parent == folder) { if (storeList.ContainsKey(item.FullName)) { storeList.Remove(item.FullName); } } } } SaveList(folder.Repository, storeList); } finally { locker.ExitWriteLock(); } } public static void UpdateFolder(MediaFolder folder) { locker.EnterWriteLock(); try { var folders = GetList(folder.Repository); folders[folder.FullName] = folder; SaveList(folder.Repository, folders); } finally { locker.ExitWriteLock(); } } public static void RenameFolder(MediaFolder @new, MediaFolder old) { locker.EnterWriteLock(); try { var folders = GetList(old.Repository); var keys = folders.Keys.ToList(); foreach (var key in keys) { if (key.StartsWith(old.FullName + "~")) { var newKey = @new.FullName + key.Substring(old.FullName.Length); folders.Add(newKey, folders[key]); folders.Remove(key); } } if (folders.ContainsKey(old.FullName) && !folders.ContainsKey(@new.FullName)) { folders.Add(@new.FullName, @new); folders.Remove(@old.FullName); SaveList(@new.Repository, folders); } } finally { locker.ExitWriteLock(); } } public static IEnumerable<MediaFolder> RootFolders(Repository repository) { locker.EnterReadLock(); try { return ToMediaFolders(repository, GetList(repository)).Where(it => it.Parent == null); } finally { locker.ExitReadLock(); } } public static IEnumerable<MediaFolder> ChildFolders(MediaFolder parent) { locker.EnterReadLock(); try { var query = ToMediaFolders(parent.Repository, GetList(parent.Repository)); //loop bug in azure query = query.Where(it => (parent == null && it.Parent == null) || (it.Parent != null && it.Parent.UUID == parent.UUID)); return query; } finally { locker.ExitReadLock(); } } private static IEnumerable<MediaFolder> ToMediaFolders(Repository repository, Dictionary<string, MediaFolder> folders) { return folders.Select(it => ToMediaFolder(repository, it.Key, it.Value)).ToArray(); } private static MediaFolder ToMediaFolder(Repository repository, string fullName, MediaFolder folderProperties) { return new MediaFolder(repository, fullName) { DisplayName = folderProperties.DisplayName, UserId = folderProperties.UserId, UtcCreationDate = folderProperties.UtcCreationDate, AllowedExtensions = folderProperties.AllowedExtensions }; } public static Dictionary<string, MediaFolder> GetList(Repository repository) { var account = OssAccountHelper.GetOssClientBucket(repository); var mediaFolders = repository .ObjectCache() .GetCache($"Aliyun-OSS-MediaFolders-Cachings-{repository.Name}", () => { Dictionary<string, MediaFolder> folders = null; try { byte[] data = null; var jsonConfigName = $"{MediaBlobHelper.MediaDirectoryName}.{repository.Name}.json".ToLower(); var xmlConfigName = $"{MediaBlobHelper.MediaDirectoryName}.{repository.Name}.xml".ToLower(); if (account.Item1.DoesObjectExist(account.Item2, jsonConfigName)) { data = account.Item1.GetObjectData(account.Item2, jsonConfigName); if (data != null && data.Length > 0) { var json = Encoding.UTF8.GetString(data); folders = JsonHelper.Deserialize<Dictionary<string, MediaFolder>>(json); } } else if (account.Item1.DoesObjectExist(account.Item2, xmlConfigName)) { data = account.Item1.GetObjectData(account.Item2, xmlConfigName); if (data != null && data.Length > 0) { var xml = Encoding.UTF8.GetString(data); folders = DataContractSerializationHelper.DeserializeFromXml<Dictionary<string, MediaFolder>>(xml); SaveList(repository, folders); account.Item1.DeleteObject(account.Item2, xmlConfigName); } } } catch (Exception ex) { Log.LogException(ex); } if (folders == null) { folders = new Dictionary<string, MediaFolder>(); } return new Dictionary<string, MediaFolder>(folders, StringComparer.OrdinalIgnoreCase); }); return mediaFolders; } private static void SaveList(Repository repository, Dictionary<string, MediaFolder> folders) { var account = OssAccountHelper.GetOssClientBucket(repository); var container = MediaBlobHelper.InitializeRepositoryContainer(repository); var jsonConfigName = $"{MediaBlobHelper.MediaDirectoryName}.{repository.Name}.json".ToLower(); if (folders != null && folders.Count > 0) { var json = JsonHelper.ToJSON(folders); var bytes = Encoding.UTF8.GetBytes(json); using (var stream = new MemoryStream(bytes)) { stream.Position = 0; var meta = new ObjectMetadata { ContentType = IOUtility.MimeType(jsonConfigName) }; account.Item1.PutObject(account.Item2, jsonConfigName, stream, meta); } } else { account.Item1.DeleteObject(account.Item2, jsonConfigName); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.NotificationHubs { using Microsoft.Rest.Azure; using Models; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Checks the availability of the given service namespace across all /// Azure subscriptions. This is useful because the domain name is /// created based on the service namespace name. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" /> /// </summary> /// <param name='parameters'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CheckAvailabilityResult>> CheckAvailabilityWithHttpMessagesAsync(CheckAvailabilityParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates/Updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Patches the existing namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to patch a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> PatchWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespacePatchParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns the description for the specified namespace. /// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets an authorization rule for a namespace by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. If resourceGroupName value is null /// the method lists all the namespaces within subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Regenerates the Primary/Secondary Keys to the Namespace /// Authorization Rule /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the Namespace Authorization Rule /// Key. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Logging; namespace QuantConnect.Scheduling { /// <summary> /// Real time self scheduling event /// </summary> public class ScheduledEvent : IDisposable { /// <summary> /// Gets the default time before market close end of trading day events will fire /// </summary> public static readonly TimeSpan SecurityEndOfDayDelta = TimeSpan.FromMinutes(10); /// <summary> /// Gets the default time before midnight end of day events will fire /// </summary> public static readonly TimeSpan AlgorithmEndOfDayDelta = TimeSpan.FromMinutes(2); private bool _needsMoveNext; private bool _endOfScheduledEvents; private readonly string _name; private readonly Action<string, DateTime> _callback; private readonly IEnumerator<DateTime> _orderedEventUtcTimes; /// <summary> /// Event that fires each time this scheduled event happens /// </summary> public event Action<string, DateTime> EventFired; /// <summary> /// Gets or sets whether this event is enabled /// </summary> public bool Enabled { get; set; } /// <summary> /// Gets or sets whether this event will log each time it fires /// </summary> internal bool IsLoggingEnabled { get; set; } /// <summary> /// Gets the next time this scheduled event will fire in UTC /// </summary> public DateTime NextEventUtcTime { get { return _endOfScheduledEvents ? DateTime.MaxValue : _orderedEventUtcTimes.Current; } } /// <summary> /// Gets an identifier for this event /// </summary> public string Name { get { return _name; } } /// <summary> /// Initalizes a new instance of the <see cref="ScheduledEvent"/> class /// </summary> /// <param name="name">An identifier for this event</param> /// <param name="eventUtcTime">The date time the event should fire</param> /// <param name="callback">Delegate to be called when the event time passes</param> public ScheduledEvent(string name, DateTime eventUtcTime, Action<string, DateTime> callback = null) : this(name, new[] { eventUtcTime }.AsEnumerable().GetEnumerator(), callback) { } /// <summary> /// Initalizes a new instance of the <see cref="ScheduledEvent"/> class /// </summary> /// <param name="name">An identifier for this event</param> /// <param name="orderedEventUtcTimes">An enumerable that emits event times</param> /// <param name="callback">Delegate to be called each time an event passes</param> public ScheduledEvent(string name, IEnumerable<DateTime> orderedEventUtcTimes, Action<string, DateTime> callback = null) : this(name, orderedEventUtcTimes.GetEnumerator(), callback) { } /// <summary> /// Initalizes a new instance of the <see cref="ScheduledEvent"/> class /// </summary> /// <param name="name">An identifier for this event</param> /// <param name="orderedEventUtcTimes">An enumerator that emits event times</param> /// <param name="callback">Delegate to be called each time an event passes</param> public ScheduledEvent(string name, IEnumerator<DateTime> orderedEventUtcTimes, Action<string, DateTime> callback = null) { _name = name; _callback = callback; _orderedEventUtcTimes = orderedEventUtcTimes; // prime the pump _endOfScheduledEvents = !_orderedEventUtcTimes.MoveNext(); Enabled = true; } /// <summary> /// Scans this event and fires the callback if an event happened /// </summary> /// <param name="utcTime">The current time in UTC</param> internal void Scan(DateTime utcTime) { if (_endOfScheduledEvents) { return; } do { if (_needsMoveNext) { // if we've passed an event or are just priming the pump, we need to move next if (!_orderedEventUtcTimes.MoveNext()) { if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Completed scheduled events.", Name)); } _endOfScheduledEvents = true; return; } if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Next event: {1} UTC", Name, _orderedEventUtcTimes.Current.ToString(DateFormat.UI))); } } // if time has passed our event if (utcTime >= _orderedEventUtcTimes.Current) { if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Firing at {1} UTC Scheduled at {2} UTC", Name, utcTime.ToString(DateFormat.UI), _orderedEventUtcTimes.Current.ToString(DateFormat.UI)) ); } // fire the event OnEventFired(_orderedEventUtcTimes.Current); _needsMoveNext = true; } else { // we haven't passed the event time yet, so keep waiting on this Current _needsMoveNext = false; } } // keep checking events until we pass the current time, this will fire // all 'skipped' events back to back in order, perhaps this should be handled // in the real time handler while (_needsMoveNext); } /// <summary> /// Fast forwards this schedule to the specified time without invoking the events /// </summary> /// <param name="utcTime">Frontier time</param> internal void SkipEventsUntil(DateTime utcTime) { // check if our next event is in the past if (utcTime < _orderedEventUtcTimes.Current) return; while (_orderedEventUtcTimes.MoveNext()) { // zoom through the enumerator until we get to the desired time if (utcTime <= _orderedEventUtcTimes.Current) { // pump is primed and ready to go _needsMoveNext = false; if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Skipped events before {1}. Next event: {2}", Name, utcTime.ToString(DateFormat.UI), _orderedEventUtcTimes.Current.ToString(DateFormat.UI) )); } return; } } if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Exhausted event stream during skip until {1}", Name, utcTime.ToString(DateFormat.UI) )); } _endOfScheduledEvents = true; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> void IDisposable.Dispose() { _orderedEventUtcTimes.Dispose(); } /// <summary> /// Event invocator for the <see cref="EventFired"/> event /// </summary> /// <param name="triggerTime">The event's time in UTC</param> protected void OnEventFired(DateTime triggerTime) { // don't fire the event if we're turned off if (!Enabled) return; if (_callback != null) { _callback(_name, _orderedEventUtcTimes.Current); } var handler = EventFired; if (handler != null) handler(_name, triggerTime); } } }
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 ElasticsearchWorkshop.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
//------------------------------------------------------------------------------ // <copyright file="PasswordPolicyService.cs"> // Copyright (c) 2014-present Andrea Di Giorgi // // 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> // <author>Andrea Di Giorgi</author> // <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Liferay.SDK.Service.V62.PasswordPolicy { public class PasswordPolicyService : ServiceBase { public PasswordPolicyService(ISession session) : base(session) { } public async Task<dynamic> AddPasswordPolicyAsync(string name, string description, bool changeable, bool changeRequired, long minAge, bool checkSyntax, bool allowDictionaryWords, int minAlphanumeric, int minLength, int minLowerCase, int minNumbers, int minSymbols, int minUpperCase, bool history, int historyCount, bool expireable, long maxAge, long warningTime, int graceLimit, bool lockout, int maxFailure, long lockoutDuration, long resetFailureCount, long resetTicketMaxAge) { var _parameters = new JsonObject(); _parameters.Add("name", name); _parameters.Add("description", description); _parameters.Add("changeable", changeable); _parameters.Add("changeRequired", changeRequired); _parameters.Add("minAge", minAge); _parameters.Add("checkSyntax", checkSyntax); _parameters.Add("allowDictionaryWords", allowDictionaryWords); _parameters.Add("minAlphanumeric", minAlphanumeric); _parameters.Add("minLength", minLength); _parameters.Add("minLowerCase", minLowerCase); _parameters.Add("minNumbers", minNumbers); _parameters.Add("minSymbols", minSymbols); _parameters.Add("minUpperCase", minUpperCase); _parameters.Add("history", history); _parameters.Add("historyCount", historyCount); _parameters.Add("expireable", expireable); _parameters.Add("maxAge", maxAge); _parameters.Add("warningTime", warningTime); _parameters.Add("graceLimit", graceLimit); _parameters.Add("lockout", lockout); _parameters.Add("maxFailure", maxFailure); _parameters.Add("lockoutDuration", lockoutDuration); _parameters.Add("resetFailureCount", resetFailureCount); _parameters.Add("resetTicketMaxAge", resetTicketMaxAge); var _command = new JsonObject() { { "/passwordpolicy/add-password-policy", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> AddPasswordPolicyAsync(string name, string description, bool changeable, bool changeRequired, long minAge, bool checkSyntax, bool allowDictionaryWords, int minAlphanumeric, int minLength, int minLowerCase, int minNumbers, int minSymbols, int minUpperCase, string regex, bool history, int historyCount, bool expireable, long maxAge, long warningTime, int graceLimit, bool lockout, int maxFailure, long lockoutDuration, long resetFailureCount, long resetTicketMaxAge, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("name", name); _parameters.Add("description", description); _parameters.Add("changeable", changeable); _parameters.Add("changeRequired", changeRequired); _parameters.Add("minAge", minAge); _parameters.Add("checkSyntax", checkSyntax); _parameters.Add("allowDictionaryWords", allowDictionaryWords); _parameters.Add("minAlphanumeric", minAlphanumeric); _parameters.Add("minLength", minLength); _parameters.Add("minLowerCase", minLowerCase); _parameters.Add("minNumbers", minNumbers); _parameters.Add("minSymbols", minSymbols); _parameters.Add("minUpperCase", minUpperCase); _parameters.Add("regex", regex); _parameters.Add("history", history); _parameters.Add("historyCount", historyCount); _parameters.Add("expireable", expireable); _parameters.Add("maxAge", maxAge); _parameters.Add("warningTime", warningTime); _parameters.Add("graceLimit", graceLimit); _parameters.Add("lockout", lockout); _parameters.Add("maxFailure", maxFailure); _parameters.Add("lockoutDuration", lockoutDuration); _parameters.Add("resetFailureCount", resetFailureCount); _parameters.Add("resetTicketMaxAge", resetTicketMaxAge); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/passwordpolicy/add-password-policy", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task DeletePasswordPolicyAsync(long passwordPolicyId) { var _parameters = new JsonObject(); _parameters.Add("passwordPolicyId", passwordPolicyId); var _command = new JsonObject() { { "/passwordpolicy/delete-password-policy", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<dynamic> UpdatePasswordPolicyAsync(long passwordPolicyId, string name, string description, bool changeable, bool changeRequired, long minAge, bool checkSyntax, bool allowDictionaryWords, int minAlphanumeric, int minLength, int minLowerCase, int minNumbers, int minSymbols, int minUpperCase, bool history, int historyCount, bool expireable, long maxAge, long warningTime, int graceLimit, bool lockout, int maxFailure, long lockoutDuration, long resetFailureCount, long resetTicketMaxAge) { var _parameters = new JsonObject(); _parameters.Add("passwordPolicyId", passwordPolicyId); _parameters.Add("name", name); _parameters.Add("description", description); _parameters.Add("changeable", changeable); _parameters.Add("changeRequired", changeRequired); _parameters.Add("minAge", minAge); _parameters.Add("checkSyntax", checkSyntax); _parameters.Add("allowDictionaryWords", allowDictionaryWords); _parameters.Add("minAlphanumeric", minAlphanumeric); _parameters.Add("minLength", minLength); _parameters.Add("minLowerCase", minLowerCase); _parameters.Add("minNumbers", minNumbers); _parameters.Add("minSymbols", minSymbols); _parameters.Add("minUpperCase", minUpperCase); _parameters.Add("history", history); _parameters.Add("historyCount", historyCount); _parameters.Add("expireable", expireable); _parameters.Add("maxAge", maxAge); _parameters.Add("warningTime", warningTime); _parameters.Add("graceLimit", graceLimit); _parameters.Add("lockout", lockout); _parameters.Add("maxFailure", maxFailure); _parameters.Add("lockoutDuration", lockoutDuration); _parameters.Add("resetFailureCount", resetFailureCount); _parameters.Add("resetTicketMaxAge", resetTicketMaxAge); var _command = new JsonObject() { { "/passwordpolicy/update-password-policy", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> UpdatePasswordPolicyAsync(long passwordPolicyId, string name, string description, bool changeable, bool changeRequired, long minAge, bool checkSyntax, bool allowDictionaryWords, int minAlphanumeric, int minLength, int minLowerCase, int minNumbers, int minSymbols, int minUpperCase, string regex, bool history, int historyCount, bool expireable, long maxAge, long warningTime, int graceLimit, bool lockout, int maxFailure, long lockoutDuration, long resetFailureCount, long resetTicketMaxAge, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("passwordPolicyId", passwordPolicyId); _parameters.Add("name", name); _parameters.Add("description", description); _parameters.Add("changeable", changeable); _parameters.Add("changeRequired", changeRequired); _parameters.Add("minAge", minAge); _parameters.Add("checkSyntax", checkSyntax); _parameters.Add("allowDictionaryWords", allowDictionaryWords); _parameters.Add("minAlphanumeric", minAlphanumeric); _parameters.Add("minLength", minLength); _parameters.Add("minLowerCase", minLowerCase); _parameters.Add("minNumbers", minNumbers); _parameters.Add("minSymbols", minSymbols); _parameters.Add("minUpperCase", minUpperCase); _parameters.Add("regex", regex); _parameters.Add("history", history); _parameters.Add("historyCount", historyCount); _parameters.Add("expireable", expireable); _parameters.Add("maxAge", maxAge); _parameters.Add("warningTime", warningTime); _parameters.Add("graceLimit", graceLimit); _parameters.Add("lockout", lockout); _parameters.Add("maxFailure", maxFailure); _parameters.Add("lockoutDuration", lockoutDuration); _parameters.Add("resetFailureCount", resetFailureCount); _parameters.Add("resetTicketMaxAge", resetTicketMaxAge); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/passwordpolicy/update-password-policy", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Quilt4.Service.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.UtcNow }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.UtcNow) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; using Internal.Runtime.CompilerServices; namespace System.Globalization { internal partial class CalendarData { private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { Debug.Assert(!GlobalizationMode.Invariant); bool ret = true; uint useOverrides = this.bUseUserOverrides ? 0 : CAL_NOUSEROVERRIDE; // // Windows doesn't support some calendars right now, so remap those. // switch (calendarId) { case CalendarId.JAPANESELUNISOLAR: // Data looks like Japanese calendarId = CalendarId.JAPAN; break; case CalendarId.JULIAN: // Data looks like gregorian US case CalendarId.CHINESELUNISOLAR: // Algorithmic, so actual data is irrelevent case CalendarId.SAKA: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_CHN: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_KOR: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_ROKUYOU: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.KOREANLUNISOLAR: // Algorithmic, so actual data is irrelevent case CalendarId.TAIWANLUNISOLAR: // Algorithmic, so actual data is irrelevent calendarId = CalendarId.GREGORIAN_US; break; } // // Special handling for some special calendar due to OS limitation. // This includes calendar like Taiwan calendar, UmAlQura calendar, etc. // CheckSpecialCalendar(ref calendarId, ref localeName); // Numbers ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_ITWODIGITYEARMAX | useOverrides, out this.iTwoDigitYearMax); // Strings ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SCALNAME, out this.sNativeName); ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SMONTHDAY | useOverrides, out this.sMonthDay); // String Arrays // Formats ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates); ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates); // Get the YearMonth pattern. ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths); // Day & Month Names // These are all single calType entries, 1 per day, so we have to make 7 or 13 calls to collect all the names // Day // Note that we're off-by-one since managed starts on sunday and windows starts on monday ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SDAYNAME7, out this.saDayNames); ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SABBREVDAYNAME7, out this.saAbbrevDayNames); // Month names ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1, out this.saMonthNames); ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1, out this.saAbbrevMonthNames); // // The following LCTYPE are not supported in some platforms. If the call fails, // don't return a failure. // GetCalendarDayInfo(localeName, calendarId, CAL_SSHORTESTDAYNAME7, out this.saSuperShortDayNames); // Gregorian may have genitive month names if (calendarId == CalendarId.GREGORIAN) { GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saMonthGenitiveNames); GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saAbbrevMonthGenitiveNames); } // Calendar Parts Names // This doesn't get always get localized names for gregorian (not available in windows < 7) // so: eg: coreclr on win < 7 won't get these CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames); CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames); // // Calendar Era Info // Note that calendar era data (offsets, etc) is hard coded for each calendar since this // data is implementation specific and not dynamic (except perhaps Japanese) // // Clean up the escaping of the formats this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates); this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates); this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths); this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay); return ret; } // Get native two digit year max internal static int GetTwoDigitYearMax(CalendarId calendarId) { if (GlobalizationMode.Invariant) { return Invariant.iTwoDigitYearMax; } int twoDigitYearMax = -1; if (!CallGetCalendarInfoEx(null, calendarId, (uint)CAL_ITWODIGITYEARMAX, out twoDigitYearMax)) { twoDigitYearMax = -1; } return twoDigitYearMax; } // Call native side to figure out which calendars are allowed internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); EnumCalendarsData data = new EnumCalendarsData(); data.userOverride = 0; data.calendars = new List<int>(); // First call GetLocaleInfo if necessary if (useUserOverride) { // They want user overrides, see if the user calendar matches the input calendar int userCalendar = CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE); // If we got a default, then use it as the first calendar if (userCalendar != 0) { data.userOverride = userCalendar; data.calendars.Add(userCalendar); } } unsafe { Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, Unsafe.AsPointer(ref data)); } // Copy to the output array for (int i = 0; i < Math.Min(calendars.Length, data.calendars.Count); i++) calendars[i] = (CalendarId)data.calendars[i]; // Now we have a list of data, return the count return data.calendars.Count; } private static bool SystemSupportsTaiwaneseCalendar() { Debug.Assert(!GlobalizationMode.Invariant); string data; // Taiwanese calendar get listed as one of the optional zh-TW calendars only when having zh-TW UI return CallGetCalendarInfoEx("zh-TW", CalendarId.TAIWAN, CAL_SCALNAME, out data); } // PAL Layer ends here private const uint CAL_RETURN_NUMBER = 0x20000000; private const uint CAL_RETURN_GENITIVE_NAMES = 0x10000000; private const uint CAL_NOUSEROVERRIDE = 0x80000000; private const uint CAL_SCALNAME = 0x00000002; private const uint CAL_SMONTHDAY = 0x00000038; private const uint CAL_SSHORTDATE = 0x00000005; private const uint CAL_SLONGDATE = 0x00000006; private const uint CAL_SYEARMONTH = 0x0000002f; private const uint CAL_SDAYNAME7 = 0x0000000d; private const uint CAL_SABBREVDAYNAME7 = 0x00000014; private const uint CAL_SMONTHNAME1 = 0x00000015; private const uint CAL_SABBREVMONTHNAME1 = 0x00000022; private const uint CAL_SSHORTESTDAYNAME7 = 0x00000037; private const uint CAL_SERASTRING = 0x00000004; private const uint CAL_SABBREVERASTRING = 0x00000039; private const uint CAL_ICALINTVALUE = 0x00000001; private const uint CAL_ITWODIGITYEARMAX = 0x00000030; private const uint ENUM_ALL_CALENDARS = 0xffffffff; private const uint LOCALE_SSHORTDATE = 0x0000001F; private const uint LOCALE_SLONGDATE = 0x00000020; private const uint LOCALE_SYEARMONTH = 0x00001006; private const uint LOCALE_ICALENDARTYPE = 0x00001009; //////////////////////////////////////////////////////////////////////// // // For calendars like Gregorain US/Taiwan/UmAlQura, they are not available // in all OS or all localized versions of OS. // If OS does not support these calendars, we will fallback by using the // appropriate fallback calendar and locale combination to retrieve data from OS. // // Parameters: // __deref_inout pCalendarInt: // Pointer to the calendar ID. This will be updated to new fallback calendar ID if needed. // __in_out pLocaleNameStackBuffer // Pointer to the StackSString object which holds the locale name to be checked. // This will be updated to new fallback locale name if needed. // //////////////////////////////////////////////////////////////////////// private static void CheckSpecialCalendar(ref CalendarId calendar, ref string localeName) { string data; // Gregorian-US isn't always available in the OS, however it is the same for all locales switch (calendar) { case CalendarId.GREGORIAN_US: // See if this works if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data)) { // Failed, set it to a locale (fa-IR) that's alway has Gregorian US available in the OS localeName = "fa-IR"; } // See if that works if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data)) { // Failed again, just use en-US with the gregorian calendar localeName = "en-US"; calendar = CalendarId.GREGORIAN; } break; case CalendarId.TAIWAN: // Taiwan calendar data is not always in all language version of OS due to Geopolical reasons. // It is only available in zh-TW localized versions of Windows. // Let's check if OS supports it. If not, fallback to Greogrian localized for Taiwan calendar. if (!SystemSupportsTaiwaneseCalendar()) { calendar = CalendarId.GREGORIAN; } break; } } private static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out int data) { return (Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | CAL_RETURN_NUMBER, IntPtr.Zero, 0, out data) != 0); } private static unsafe bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out string data) { const int BUFFER_LENGTH = 80; // The maximum size for values returned from GetCalendarInfoEx is 80 characters. char* buffer = stackalloc char[BUFFER_LENGTH]; int ret = Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType, (IntPtr)buffer, BUFFER_LENGTH, IntPtr.Zero); if (ret > 0) { if (buffer[ret - 1] == '\0') { ret--; // don't include the null termination in the string } data = new string(buffer, 0, ret); return true; } data = ""; return false; } // Context for EnumCalendarInfoExEx callback. private struct EnumData { public string userOverride; public List<string> strings; } // EnumCalendarInfoExEx callback itself. // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumCalendarInfoCallback(char* lpCalendarInfoString, uint calendar, IntPtr pReserved, void* lParam) { ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam); try { string calendarInfo = new string(lpCalendarInfoString); // If we had a user override, check to make sure this differs if (context.userOverride != calendarInfo) context.strings.Add(calendarInfo); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[] data) { EnumData context = new EnumData(); context.userOverride = null; context.strings = new List<string>(); // First call GetLocaleInfo if necessary if (((lcType != 0) && ((lcType & CAL_NOUSEROVERRIDE) == 0)) && // Get user locale, see if it matches localeName. // Note that they should match exactly, including letter case GetUserDefaultLocaleName() == localeName) { // They want user overrides, see if the user calendar matches the input calendar CalendarId userCalendar = (CalendarId)CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE); // If the calendars were the same, see if the locales were the same if (userCalendar == calendar) { // They matched, get the user override since locale & calendar match string res = CultureData.GetLocaleInfoEx(localeName, lcType); // if it succeeded remember the override for the later callers if (res != null) { // Remember this was the override (so we can look for duplicates later in the enum function) context.userOverride = res; // Add to the result strings. context.strings.Add(res); } } } unsafe { // Now call the enumeration API. Work is done by our callback function Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, Unsafe.AsPointer(ref context)); } // Now we have a list of data, fail if we didn't find anything. if (context.strings.Count == 0) { data = null; return false; } string[] output = context.strings.ToArray(); if (calType == CAL_SABBREVERASTRING || calType == CAL_SERASTRING) { // Eras are enumerated backwards. (oldest era name first, but // Japanese calendar has newest era first in array, and is only // calendar with multiple eras) Array.Reverse(output, 0, output.Length); } data = output; return true; } //////////////////////////////////////////////////////////////////////// // // Get the native day names // // NOTE: There's a disparity between .NET & windows day orders, the input day should // start with Sunday // // Parameters: // OUT pOutputStrings The output string[] value. // //////////////////////////////////////////////////////////////////////// private static bool GetCalendarDayInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { bool result = true; // // We'll need a new array of 7 items // string[] results = new string[7]; // Get each one of them for (int i = 0; i < 7; i++, calType++) { result &= CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]); // On the first iteration we need to go from CAL_SDAYNAME7 to CAL_SDAYNAME1, so subtract 7 before the ++ happens // This is because the framework starts on sunday and windows starts on monday when counting days if (i == 0) calType -= 7; } outputStrings = results; return result; } //////////////////////////////////////////////////////////////////////// // // Get the native month names // // Parameters: // OUT pOutputStrings The output string[] value. // //////////////////////////////////////////////////////////////////////// private static bool GetCalendarMonthInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { // // We'll need a new array of 13 items // string[] results = new string[13]; // Get each one of them for (int i = 0; i < 13; i++, calType++) { if (!CallGetCalendarInfoEx(localeName, calendar, calType, out results[i])) results[i] = ""; } outputStrings = results; return true; } // // struct to help our calendar data enumaration callback // private struct EnumCalendarsData { public int userOverride; // user override value (if found) public List<int> calendars; // list of calendars found so far } // [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumCalendarsCallback(char* lpCalendarInfoString, uint calendar, IntPtr reserved, void* lParam) { ref EnumCalendarsData context = ref Unsafe.As<byte, EnumCalendarsData>(ref *(byte*)lParam); try { // If we had a user override, check to make sure this differs if (context.userOverride != calendar) context.calendars.Add((int)calendar); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private static unsafe string GetUserDefaultLocaleName() { Debug.Assert(!GlobalizationMode.Invariant); int result; char* localeName = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH]; result = CultureData.GetLocaleInfoEx(Interop.Kernel32.LOCALE_NAME_USER_DEFAULT, Interop.Kernel32.LOCALE_SNAME, localeName, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH); return result <= 0 ? "" : new string(localeName, 0, result - 1); // exclude the null termination } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Xunit; namespace System.Tests { public class ByteTests { [Fact] public static void Ctor_Empty() { var b = new byte(); Assert.Equal(0, b); } [Fact] public static void Ctor_Value() { byte b = 41; Assert.Equal(41, b); } [Fact] public static void MaxValue() { Assert.Equal(0xFF, byte.MaxValue); } [Fact] public static void MinValue() { Assert.Equal(0, byte.MinValue); } [Theory] [InlineData((byte)234, (byte)234, 0)] [InlineData((byte)234, byte.MinValue, 1)] [InlineData((byte)234, (byte)123, 1)] [InlineData((byte)234, (byte)235, -1)] [InlineData((byte)234, byte.MaxValue, -1)] [InlineData((byte)234, null, 1)] public void CompareTo_Other_ReturnsExpected(byte i, object value, int expected) { if (value is byte byteValue) { Assert.Equal(expected, Math.Sign(i.CompareTo(byteValue))); } Assert.Equal(expected, Math.Sign(i.CompareTo(value))); } [Theory] [InlineData("a")] [InlineData(234)] public void CompareTo_ObjectNotByte_ThrowsArgumentException(object value) { AssertExtensions.Throws<ArgumentException>(null, () => ((byte)123).CompareTo(value)); } [Theory] [InlineData((byte)78, (byte)78, true)] [InlineData((byte)78, (byte)0, false)] [InlineData((byte)0, (byte)0, true)] [InlineData((byte)78, null, false)] [InlineData((byte)78, "78", false)] [InlineData((byte)78, 78, false)] public static void Equals(byte b, object obj, bool expected) { if (obj is byte b2) { Assert.Equal(expected, b.Equals(b2)); Assert.Equal(expected, b.GetHashCode().Equals(b2.GetHashCode())); Assert.Equal(b, b.GetHashCode()); } Assert.Equal(expected, b.Equals(obj)); } [Fact] public void GetTypeCode_Invoke_ReturnsByte() { Assert.Equal(TypeCode.Byte, ((byte)1).GetTypeCode()); } public static IEnumerable<object[]> ToString_TestData() { foreach (NumberFormatInfo emptyFormat in new[] { null, NumberFormatInfo.CurrentInfo }) { yield return new object[] { (byte)0, "G", emptyFormat, "0" }; yield return new object[] { (byte)123, "G", emptyFormat, "123" }; yield return new object[] { byte.MaxValue, "G", emptyFormat, "255" }; yield return new object[] { (byte)123, "D", emptyFormat, "123" }; yield return new object[] { (byte)123, "D99", emptyFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123" }; yield return new object[] { (byte)0x24, "x", emptyFormat, "24" }; yield return new object[] { (byte)24, "N", emptyFormat, string.Format("{0:N}", 24.00) }; } var customFormat = new NumberFormatInfo() { NegativeSign = "#", NumberDecimalSeparator = "~", NumberGroupSeparator = "*", PositiveSign = "&", NumberDecimalDigits = 2, PercentSymbol = "@", PercentGroupSeparator = ",", PercentDecimalSeparator = ".", PercentDecimalDigits = 5 }; yield return new object[] { (byte)24, "N", customFormat, "24~00" }; yield return new object[] { (byte)123, "E", customFormat, "1~230000E&002" }; yield return new object[] { (byte)123, "F", customFormat, "123~00" }; yield return new object[] { (byte)123, "P", customFormat, "12,300.00000 @" }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(byte b, string format, IFormatProvider provider, string expected) { // Format is case insensitive string upperFormat = format.ToUpperInvariant(); string lowerFormat = format.ToLowerInvariant(); string upperExpected = expected.ToUpperInvariant(); string lowerExpected = expected.ToLowerInvariant(); bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo); if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G") { if (isDefaultProvider) { Assert.Equal(upperExpected, b.ToString()); Assert.Equal(upperExpected, b.ToString((IFormatProvider)null)); } Assert.Equal(upperExpected, b.ToString(provider)); } if (isDefaultProvider) { Assert.Equal(upperExpected, b.ToString(upperFormat)); Assert.Equal(lowerExpected, b.ToString(lowerFormat)); Assert.Equal(upperExpected, b.ToString(upperFormat, null)); Assert.Equal(lowerExpected, b.ToString(lowerFormat, null)); } Assert.Equal(upperExpected, b.ToString(upperFormat, provider)); Assert.Equal(lowerExpected, b.ToString(lowerFormat, provider)); } [Fact] public static void ToString_InvalidFormat_ThrowsFormatException() { byte b = 123; Assert.Throws<FormatException>(() => b.ToString("r")); // Invalid format Assert.Throws<FormatException>(() => b.ToString("r", null)); // Invalid format Assert.Throws<FormatException>(() => b.ToString("R")); // Invalid format Assert.Throws<FormatException>(() => b.ToString("R", null)); // Invalid format Assert.Throws<FormatException>(() => b.ToString("Y")); // Invalid format Assert.Throws<FormatException>(() => b.ToString("Y", null)); // Invalid format } public static IEnumerable<object[]> Parse_Valid_TestData() { NumberStyles defaultStyle = NumberStyles.Integer; NumberFormatInfo emptyFormat = new NumberFormatInfo(); NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.CurrencySymbol = "$"; yield return new object[] { "0", defaultStyle, null, (byte)0 }; yield return new object[] { "123", defaultStyle, null, (byte)123 }; yield return new object[] { "+123", defaultStyle, null, (byte)123 }; yield return new object[] { " 123 ", defaultStyle, null, (byte)123 }; yield return new object[] { "255", defaultStyle, null, (byte)255 }; yield return new object[] { "12", NumberStyles.HexNumber, null, (byte)0x12 }; yield return new object[] { "10", NumberStyles.AllowThousands, null, (byte)10 }; yield return new object[] { "123", defaultStyle, emptyFormat, (byte)123 }; yield return new object[] { "123", NumberStyles.Any, emptyFormat, (byte)123 }; yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (byte)0x12 }; yield return new object[] { "ab", NumberStyles.HexNumber, emptyFormat, (byte)0xab }; yield return new object[] { "AB", NumberStyles.HexNumber, null, (byte)0xab }; yield return new object[] { "$100", NumberStyles.Currency, customFormat, (byte)100 }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, byte expected) { byte result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.True(byte.TryParse(value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, byte.Parse(value)); } // Default provider if (provider == null) { Assert.Equal(expected, byte.Parse(value, style)); // Substitute default NumberFormatInfo Assert.True(byte.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(expected, result); Assert.Equal(expected, byte.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Equal(expected, byte.Parse(value, provider)); } // Full overloads Assert.True(byte.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, byte.Parse(value, style, provider)); } public static IEnumerable<object[]> Parse_Invalid_TestData() { // Include the test data for wider primitives. foreach (object[] widerTests in UInt16Tests.Parse_Invalid_TestData()) { yield return widerTests; } // > max value yield return new object[] { "256", NumberStyles.Integer, null, typeof(OverflowException) }; yield return new object[] { "100", NumberStyles.HexNumber, null, typeof(OverflowException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { byte result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.False(byte.TryParse(value, out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => byte.Parse(value)); } // Default provider if (provider == null) { Assert.Throws(exceptionType, () => byte.Parse(value, style)); // Substitute default NumberFormatInfo Assert.False(byte.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => byte.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Throws(exceptionType, () => byte.Parse(value, provider)); } // Full overloads Assert.False(byte.TryParse(value, style, provider, out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => byte.Parse(value, style, provider)); } [Theory] [InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)] [InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")] public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName) { byte result = 0; AssertExtensions.Throws<ArgumentException>(paramName, () => byte.TryParse("1", style, null, out result)); Assert.Equal(default(byte), result); AssertExtensions.Throws<ArgumentException>(paramName, () => byte.Parse("1", style)); AssertExtensions.Throws<ArgumentException>(paramName, () => byte.Parse("1", style, null)); } public static IEnumerable<object[]> Parse_ValidWithOffsetCount_TestData() { foreach (object[] inputs in Parse_Valid_TestData()) { yield return new object[] { inputs[0], 0, ((string)inputs[0]).Length, inputs[1], inputs[2], inputs[3] }; } yield return new object[] { "123", 0, 2, NumberStyles.Integer, null, (byte)12 }; yield return new object[] { "+123", 0, 2, NumberStyles.Integer, null, (byte)1 }; yield return new object[] { "+123", 1, 3, NumberStyles.Integer, null, (byte)123 }; yield return new object[] { " 123 ", 4, 1, NumberStyles.Integer, null, (byte)3 }; yield return new object[] { "12", 1, 1, NumberStyles.HexNumber, null, (byte)0x2 }; yield return new object[] { "10", 0, 1, NumberStyles.AllowThousands, null, (byte)1 }; yield return new object[] { "$100", 0, 2, NumberStyles.Currency, new NumberFormatInfo() { CurrencySymbol = "$" }, (byte)1 }; } [Theory] [MemberData(nameof(Parse_ValidWithOffsetCount_TestData))] public static void Parse_Span_Valid(string value, int offset, int count, NumberStyles style, IFormatProvider provider, byte expected) { byte result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.True(byte.TryParse(value.AsSpan(offset, count), out result)); Assert.Equal(expected, result); } Assert.Equal(expected, byte.Parse(value.AsSpan(offset, count), style, provider)); Assert.True(byte.TryParse(value.AsSpan(offset, count), style, provider, out result)); Assert.Equal(expected, result); } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Span_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (value != null) { byte result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.False(byte.TryParse(value.AsSpan(), out result)); Assert.Equal(0u, result); } Assert.Throws(exceptionType, () => byte.Parse(value.AsSpan(), style, provider)); Assert.False(byte.TryParse(value.AsSpan(), style, provider, out result)); Assert.Equal(0u, result); } } [Theory] [MemberData(nameof(ToString_TestData))] public static void TryFormat(byte i, string format, IFormatProvider provider, string expected) { char[] actual; int charsWritten; // Just right actual = new char[expected.Length]; Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(actual)); // Longer than needed actual = new char[expected.Length + 1]; Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(actual, 0, charsWritten)); // Too short if (expected.Length > 0) { actual = new char[expected.Length - 1]; Assert.False(i.TryFormat(actual.AsSpan(), out charsWritten, format, provider)); Assert.Equal(0, charsWritten); } if (format != null) { // Upper format actual = new char[expected.Length]; Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format.ToUpperInvariant(), provider)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected.ToUpperInvariant(), new string(actual)); // Lower format actual = new char[expected.Length]; Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten, format.ToLowerInvariant(), provider)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected.ToLowerInvariant(), new string(actual)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using Ductus.FluentDocker.Common; using Ductus.FluentDocker.Executors; using Ductus.FluentDocker.Extensions.Utils; using Ductus.FluentDocker.Model.Common; using Ductus.FluentDocker.Model.Containers; namespace Ductus.FluentDocker.Extensions { public static class CommandExtensions { private static IPAddress _cachedDockerIpAddress; private static SudoMechanism _sudoMechanism = SudoMechanism.None; private static string _sudoPassword; private static string _defaultShell = "bash"; private static DockerBinariesResolver _binaryResolver = new DockerBinariesResolver(_sudoMechanism, _sudoPassword); /// <summary> /// Reads a <see cref="ConsoleStream{T}" /> until <see cref="ConsoleStream{T}.IsFinished" /> is set to true /// or a timeout occurred on a read. /// </summary> /// <typeparam name="T">The type of returned items in the console stream.</typeparam> /// <param name="stream">The stream to read from.</param> /// <param name="millisTimeout"> /// The amount of time to wait on a single <see cref="ConsoleStream{T}.TryRead" /> before returning. /// </param> /// <returns>A list of items read from the console stream.</returns> public static IList<T> ReadToEnd<T>(this ConsoleStream<T> stream, int millisTimeout = 5000) where T : class { var list = new List<T>(); while (!stream.IsFinished) { var line = stream.TryRead(millisTimeout); if (null == line) break; list.Add(line); } return list; } /// <summary> /// Changes the default shell when <see cref="SudoMechanism"/> is either NoPassword or Password. /// </summary> /// <param name="shell">The new default shell to use.</param> /// <remarks> /// By default FluentDocker uses bash. /// </remarks> public static void AsDefaultShell(this string shell) { _defaultShell = shell; } /// <summary> /// Gets the shell to use when <see cref="SudoMechanism"/> is either NoPassword or Password. /// </summary> public static string DefaultShell => _defaultShell; /// <summary> /// Sets the sudo mechanism on subsequent commands. /// </summary> /// <param name="sudo">The wanted sudo mechanism.</param> /// <param name="password">Optional. If sudo mechanism is set to SudoMechanism.Password it is required></param> /// <exception cref="ArgumentException">If sudo mechanism password is wanted but no password was provided.</exception> /// <remarks> /// By default the library operates on SudoMechanism.None and therefore expects the current user to be able to /// communicate with the docker daemon. /// </remarks> [Experimental] public static void SetSudo(this SudoMechanism sudo, string password = null) { if (string.IsNullOrWhiteSpace(password) && sudo == SudoMechanism.Password) throw new ArgumentException("When using SudoMechanism.Password a password must be provided!", nameof(password)); _sudoMechanism = sudo; _sudoPassword = password; _binaryResolver = new DockerBinariesResolver(_sudoMechanism, _sudoPassword); } public static string ResolveBinary(this string dockerCommand, bool preferMachine = false, bool forceResolve = false) { if (forceResolve || null == _binaryResolver) _binaryResolver = new DockerBinariesResolver(_sudoMechanism, _sudoPassword); return dockerCommand.ResolveBinary(_binaryResolver, preferMachine); } public static string ResolveBinary(this string dockerCommand, DockerBinariesResolver resolver, bool preferMachine = false) { var binary = resolver.Resolve(dockerCommand, preferMachine); if (FdOs.IsWindows() || binary.Sudo == SudoMechanism.None) return binary.FqPath; string cmd; if (binary.Sudo == SudoMechanism.NoPassword) cmd = $"sudo {binary.FqPath}"; else cmd = $"echo {binary.SudoPassword} | sudo -S {binary.FqPath}"; if (string.IsNullOrEmpty(cmd)) { if (!string.IsNullOrEmpty(dockerCommand) && dockerCommand.ToLower() == "docker-machine") throw new FluentDockerException( $"Could not find {dockerCommand} make sure it is on your path. From 2.2.0 you have to seprately install it via https://github.com/docker/machine/releases"); throw new FluentDockerException($"Could not find {dockerCommand}, make sure it is on your path."); } return cmd; } public static bool IsMachineBinaryPresent() { if (null == _binaryResolver) _binaryResolver = new DockerBinariesResolver(_sudoMechanism, _sudoPassword); return null != _binaryResolver.MainDockerMachine; } public static bool IsComposeBinaryPresent() { if (null == _binaryResolver) _binaryResolver = new DockerBinariesResolver(_sudoMechanism, _sudoPassword); return null != _binaryResolver.MainDockerCompose; } public static IEnumerable<string> GetResolvedBinaries() { if (null == _binaryResolver) _binaryResolver = new DockerBinariesResolver(_sudoMechanism, _sudoPassword); return new List<string> { "docker : " + (_binaryResolver.MainDockerClient.FqPath ?? "not found"), "docker-compose: " + (_binaryResolver.MainDockerCompose.FqPath ?? "not found"), "docker-machine: " + (_binaryResolver.MainDockerMachine.FqPath ?? "not found") }; } /// <summary> /// Checks is the current main environment is toolbox or not. /// </summary> /// <returns>Returns true if toolbox, false otherwise.</returns> public static bool IsToolbox() { return _binaryResolver.MainDockerClient.IsToolbox; } public static bool IsEmulatedNative() { return !FdOs.IsLinux() && !IsToolbox(); } public static bool IsDockerDnsAvailable() { try { Dns.GetHostEntry("host.docker.internal"); return true; } catch (SocketException) { return false; } } public static bool IsNative() { return FdOs.IsLinux(); } public static IPAddress EmulatedNativeAddress(bool useCache = true) { if (useCache && null != _cachedDockerIpAddress) return _cachedDockerIpAddress; var hostEntry = Dns.GetHostEntry("host.docker.internal"); if (hostEntry.AddressList.Length > 0) { // Prefer IPv4 addresses var v4Address = hostEntry.AddressList.LastOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork); _cachedDockerIpAddress = v4Address ?? hostEntry.AddressList.Last(); } return _cachedDockerIpAddress; } internal static string RenderBaseArgs(this DockerUri host, ICertificatePaths certificates = null) { var args = string.Empty; if (null != host && !host.IsStandardDaemon) { args = $" -H {host}"; } if (null == certificates) return args; args += $" --tlsverify --tlscacert={certificates.CaCertificate} --tlscert={certificates.ClientCertificate} --tlskey={certificates.ClientKey}"; return args; } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using NuGet.VisualStudio.Resources; namespace NuGet.VisualStudio { [PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(IVsPackageSourceProvider))] [Export(typeof(IPackageSourceProvider))] public class VsPackageSourceProvider : IVsPackageSourceProvider { private static readonly string NuGetLegacyOfficialFeedName = VsResources.NuGetLegacyOfficialSourceName; private static readonly string NuGetOfficialFeedName = VsResources.NuGetOfficialSourceName; private static readonly PackageSource NuGetDefaultSource = new PackageSource(NuGetConstants.DefaultFeedUrl, NuGetOfficialFeedName); private static readonly PackageSource Windows8Source = new PackageSource( NuGetConstants.VSExpressForWindows8FeedUrl, VsResources.VisualStudioExpressForWindows8SourceName, isEnabled: true, isOfficial: true); private static readonly Dictionary<PackageSource, PackageSource> _feedsToMigrate = new Dictionary<PackageSource, PackageSource> { { new PackageSource(NuGetConstants.V1FeedUrl, NuGetLegacyOfficialFeedName), NuGetDefaultSource }, { new PackageSource(NuGetConstants.V2LegacyFeedUrl, NuGetLegacyOfficialFeedName), NuGetDefaultSource }, { new PackageSource(NuGetConstants.V2LegacyOfficialPackageSourceUrl, NuGetLegacyOfficialFeedName), NuGetDefaultSource }, }; internal const string ActivePackageSourceSectionName = "activePackageSource"; private readonly IPackageSourceProvider _packageSourceProvider; private readonly IVsShellInfo _vsShellInfo; private readonly ISettings _settings; private readonly ISolutionManager _solutionManager; private bool _initialized; private List<PackageSource> _packageSources; private PackageSource _activePackageSource; [ImportingConstructor] public VsPackageSourceProvider( ISettings settings, IVsShellInfo vsShellInfo, ISolutionManager solutionManager) : this(settings, new PackageSourceProvider(settings, new[] { NuGetDefaultSource}, _feedsToMigrate), vsShellInfo, solutionManager) { } internal VsPackageSourceProvider( ISettings settings, IPackageSourceProvider packageSourceProvider, IVsShellInfo vsShellInfo) :this(settings, packageSourceProvider, vsShellInfo, null) { } private VsPackageSourceProvider( ISettings settings, IPackageSourceProvider packageSourceProvider, IVsShellInfo vsShellInfo, ISolutionManager solutionManager) { if (settings == null) { throw new ArgumentNullException("settings"); } if (packageSourceProvider == null) { throw new ArgumentNullException("packageSourceProvider"); } if (vsShellInfo == null) { throw new ArgumentNullException("vsShellInfo"); } _packageSourceProvider = packageSourceProvider; _solutionManager = solutionManager; _settings = settings; _vsShellInfo = vsShellInfo; if (null != _solutionManager) { _solutionManager.SolutionClosed += OnSolutionOpenedOrClosed; _solutionManager.SolutionOpened += OnSolutionOpenedOrClosed; } } private void OnSolutionOpenedOrClosed(object sender, EventArgs e) { _initialized = false; } public PackageSource ActivePackageSource { get { EnsureInitialized(); return _activePackageSource; } set { EnsureInitialized(); if (value != null && !IsAggregateSource(value) && !_packageSources.Contains(value) && !value.Name.Equals(NuGetOfficialFeedName, StringComparison.CurrentCultureIgnoreCase)) { throw new ArgumentException(VsResources.PackageSource_Invalid, "value"); } _activePackageSource = value; PersistActivePackageSource(_settings, _activePackageSource); } } internal static IEnumerable<PackageSource> DefaultSources { get { return new[] { NuGetDefaultSource}; } } internal static Dictionary<PackageSource, PackageSource> FeedsToMigrate { get { return _feedsToMigrate; } } public IEnumerable<PackageSource> LoadPackageSources() { EnsureInitialized(); // assert that we are not returning aggregate source Debug.Assert(_packageSources == null || !_packageSources.Any(IsAggregateSource)); return _packageSources; } public void SavePackageSources(IEnumerable<PackageSource> sources) { if (sources == null) { throw new ArgumentNullException("sources"); } EnsureInitialized(); Debug.Assert(!sources.Any(IsAggregateSource)); ActivePackageSource = null; _packageSources.Clear(); _packageSources.AddRange(sources); PersistPackageSources(_packageSourceProvider, _vsShellInfo, _packageSources); } public void DisablePackageSource(PackageSource source) { // There's no scenario for this method to get called, so do nothing here. Debug.Fail("This method shouldn't get called."); } public bool IsPackageSourceEnabled(PackageSource source) { EnsureInitialized(); var sourceInUse = _packageSources.FirstOrDefault(ps => ps.Equals(source)); return sourceInUse != null && sourceInUse.IsEnabled; } private void EnsureInitialized() { while (!_initialized) { _initialized = true; _packageSources = _packageSourceProvider.LoadPackageSources().ToList(); // When running Visual Studio Express for Windows 8, we insert the curated feed at the top if (_vsShellInfo.IsVisualStudioExpressForWindows8) { bool windows8SourceIsEnabled = _packageSourceProvider.IsPackageSourceEnabled(Windows8Source); // defensive coding: make sure we don't add duplicated win8 source _packageSources.RemoveAll(p => p.Equals(Windows8Source)); // Windows8Source is a static object which is meant for doing comparison only. // To add it to the list of package sources, we make a clone of it first. var windows8SourceClone = Windows8Source.Clone(); windows8SourceClone.IsEnabled = windows8SourceIsEnabled; _packageSources.Insert(0, windows8SourceClone); } InitializeActivePackageSource(); } } private void InitializeActivePackageSource() { _activePackageSource = DeserializeActivePackageSource(_settings, _vsShellInfo); PackageSource migratedActiveSource; bool activeSourceChanged = false; if (_activePackageSource == null) { // If there are no sources, pick the first source that's enabled. activeSourceChanged = true; _activePackageSource = _packageSources.FirstOrDefault(p => p.IsEnabled) ?? AggregatePackageSource.Instance; } else if (_feedsToMigrate.TryGetValue(_activePackageSource, out migratedActiveSource)) { // Check if we need to migrate the active source. activeSourceChanged = true; _activePackageSource = migratedActiveSource; } if (activeSourceChanged) { PersistActivePackageSource(_settings, _activePackageSource); } } private static void PersistActivePackageSource(ISettings settings, PackageSource activePackageSource) { settings.DeleteSection(ActivePackageSourceSectionName); if (activePackageSource != null) { settings.SetValue(ActivePackageSourceSectionName, activePackageSource.Name, activePackageSource.Source); } } private static PackageSource DeserializeActivePackageSource( ISettings settings, IVsShellInfo vsShellInfo) { var settingValues = settings.GetValues(ActivePackageSourceSectionName, isPath: false); PackageSource packageSource = null; if (settingValues != null && settingValues.Any()) { var setting = settingValues.First(); if (IsAggregateSource(setting.Key, setting.Value)) { packageSource = AggregatePackageSource.Instance; } else { packageSource = new PackageSource(setting.Value, setting.Key); } } if (packageSource != null) { // guard against corrupted data if the active package source is not enabled packageSource.IsEnabled = true; } return packageSource; } private static void PersistPackageSources(IPackageSourceProvider packageSourceProvider, IVsShellInfo vsShellInfo, List<PackageSource> packageSources) { bool windows8SourceIsDisabled = false; // When running Visual Studio Express For Windows 8, we will have previously added a curated package source. // But we don't want to persist it, so remove it from the list. if (vsShellInfo.IsVisualStudioExpressForWindows8) { PackageSource windows8SourceInUse = packageSources.Find(p => p.Equals(Windows8Source)); Debug.Assert(windows8SourceInUse != null); if (windows8SourceInUse != null) { packageSources = packageSources.Where(ps => !ps.Equals(Windows8Source)).ToList(); windows8SourceIsDisabled = !windows8SourceInUse.IsEnabled; } } // Starting from version 1.3, we persist the package sources to the nuget.config file instead of VS registry. // assert that we are not saving aggregate source Debug.Assert(!packageSources.Any(p => IsAggregateSource(p.Name, p.Source))); packageSourceProvider.SavePackageSources(packageSources); if (windows8SourceIsDisabled) { packageSourceProvider.DisablePackageSource(Windows8Source); } } private static bool IsAggregateSource(string name, string source) { PackageSource aggregate = AggregatePackageSource.Instance; return aggregate.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase) || aggregate.Source.Equals(source, StringComparison.InvariantCultureIgnoreCase); } private static bool IsAggregateSource(PackageSource packageSource) { return IsAggregateSource(packageSource.Name, packageSource.Source); } } }
using System; using System.Collections; using System.IO; using Raksha.Utilities; using Raksha.Utilities.Collections; namespace Raksha.Asn1 { public abstract class Asn1Sequence : Asn1Object, IEnumerable { private readonly IList seq; /** * return an Asn1Sequence from the given object. * * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ public static Asn1Sequence GetInstance( object obj) { if (obj == null || obj is Asn1Sequence) { return (Asn1Sequence)obj; } else if (obj is byte[]) { try { return Asn1Sequence.GetInstance(Asn1Object.FromByteArray((byte[])obj)); } catch (IOException e) { throw new ArgumentException("Failed to construct sequence from byte[]", e); } } throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); } /** * Return an ASN1 sequence from a tagged object. There is a special * case here, if an object appears to have been explicitly tagged on * reading but we were expecting it to be implicitly tagged in the * normal course of events it indicates that we lost the surrounding * sequence - so we need to add it back (this will happen if the tagged * object is a sequence that contains other sequences). If you are * dealing with implicitly tagged sequences you really <b>should</b> * be using this method. * * @param obj the tagged object. * @param explicitly true if the object is meant to be explicitly tagged, * false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static Asn1Sequence GetInstance( Asn1TaggedObject obj, bool explicitly) { Asn1Object inner = obj.GetObject(); if (explicitly) { if (!obj.IsExplicit()) throw new ArgumentException("object implicit - explicit expected."); return (Asn1Sequence) inner; } // // constructed object which appears to be explicitly tagged // when it should be implicit means we have to add the // surrounding sequence. // if (obj.IsExplicit()) { if (obj is BerTaggedObject) { return new BerSequence(inner); } return new DerSequence(inner); } if (inner is Asn1Sequence) { return (Asn1Sequence) inner; } throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); } protected internal Asn1Sequence( int capacity) { seq = Platform.CreateArrayList(capacity); } public virtual IEnumerator GetEnumerator() { return seq.GetEnumerator(); } [Obsolete("Use GetEnumerator() instead")] public IEnumerator GetObjects() { return GetEnumerator(); } private class Asn1SequenceParserImpl : Asn1SequenceParser { private readonly Asn1Sequence outer; private readonly int max; private int index; public Asn1SequenceParserImpl( Asn1Sequence outer) { this.outer = outer; this.max = outer.Count; } public IAsn1Convertible ReadObject() { if (index == max) return null; Asn1Encodable obj = outer[index++]; if (obj is Asn1Sequence) return ((Asn1Sequence)obj).Parser; if (obj is Asn1Set) return ((Asn1Set)obj).Parser; // NB: Asn1OctetString implements Asn1OctetStringParser directly // if (obj is Asn1OctetString) // return ((Asn1OctetString)obj).Parser; return obj; } public Asn1Object ToAsn1Object() { return outer; } } public virtual Asn1SequenceParser Parser { get { return new Asn1SequenceParserImpl(this); } } /** * return the object at the sequence position indicated by index. * * @param index the sequence number (starting at zero) of the object * @return the object at the sequence position indicated by index. */ public virtual Asn1Encodable this[int index] { get { return (Asn1Encodable) seq[index]; } } [Obsolete("Use 'object[index]' syntax instead")] public Asn1Encodable GetObjectAt( int index) { return this[index]; } [Obsolete("Use 'Count' property instead")] public int Size { get { return Count; } } public virtual int Count { get { return seq.Count; } } protected override int Asn1GetHashCode() { int hc = Count; foreach (object o in this) { hc *= 17; if (o == null) { hc ^= DerNull.Instance.GetHashCode(); } else { hc ^= o.GetHashCode(); } } return hc; } protected override bool Asn1Equals( Asn1Object asn1Object) { Asn1Sequence other = asn1Object as Asn1Sequence; if (other == null) return false; if (Count != other.Count) return false; IEnumerator s1 = GetEnumerator(); IEnumerator s2 = other.GetEnumerator(); while (s1.MoveNext() && s2.MoveNext()) { Asn1Object o1 = GetCurrent(s1).ToAsn1Object(); Asn1Object o2 = GetCurrent(s2).ToAsn1Object(); if (!o1.Equals(o2)) return false; } return true; } private Asn1Encodable GetCurrent(IEnumerator e) { Asn1Encodable encObj = (Asn1Encodable)e.Current; // unfortunately null was allowed as a substitute for DER null if (encObj == null) return DerNull.Instance; return encObj; } protected internal void AddObject( Asn1Encodable obj) { seq.Add(obj); } public override string ToString() { return CollectionUtilities.ToString(seq); } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Resources; namespace FluorineFx { /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> internal class __Res { private static ResourceManager _resMgr; internal const string Amf_Begin = "Amf_Begin"; internal const string Amf_End = "Amf_End"; internal const string Amf_Fatal = "Amf_Fatal"; internal const string Amf_Fatal404 = "Amf_Fatal404"; internal const string Amf_ReadBodyFail = "Amf_ReadBodyFail"; internal const string Amf_SerializationFail = "Amf_SerializationFail"; internal const string Amf_ResponseFail = "Amf_ResponseFail"; internal const string Context_MissingError = "Context_MissingError"; internal const string Context_Initialized = "Context_Initialized"; internal const string Rtmpt_Begin = "Rtmpt_Begin"; internal const string Rtmpt_End = "Rtmpt_End"; internal const string Rtmpt_Fatal = "Rtmpt_Fatal"; internal const string Rtmpt_Fatal404 = "Rtmpt_Fatal404"; internal const string Rtmpt_CommandBadRequest = "Rtmpt_CommandBadRequest"; internal const string Rtmpt_CommandNotSupported = "Rtmpt_CommandNotSupported"; internal const string Rtmpt_CommandOpen = "Rtmpt_CommandOpen"; internal const string Rtmpt_CommandSend = "Rtmpt_CommandSend"; internal const string Rtmpt_CommandIdle = "Rtmpt_CommandIdle"; internal const string Rtmpt_CommandClose = "Rtmpt_CommandClose"; internal const string Rtmpt_ReturningMessages = "Rtmpt_ReturningMessages"; internal const string Rtmpt_NotifyError = "Rtmpt_NotifyError"; internal const string Rtmpt_UnknownClient = "Rtmpt_UnknownClient"; internal const string Swx_Begin = "Swx_Begin"; internal const string Swx_End = "Swx_End"; internal const string Swx_Fatal = "Swx_Fatal"; internal const string Swx_Fatal404 = "Swx_Fatal404"; internal const string Swx_InvalidCrossDomainUrl = "Swx_InvalidCrossDomainUrl"; internal const string Json_Begin = "Json_Begin"; internal const string Json_End = "Json_End"; internal const string Json_Fatal = "Json_Fatal"; internal const string Json_Fatal404 = "Json_Fatal404"; internal const string Rtmp_HSInitBuffering = "Rtmp_HSInitBuffering"; internal const string Rtmp_HSReplyBuffering = "Rtmp_HSReplyBuffering"; internal const string Rtmp_HeaderBuffering = "Rtmp_HeaderBuffering"; internal const string Rtmp_DataBuffering = "Rtmp_DataBuffering"; internal const string Rtmp_ChunkSmall = "Rtmp_ChunkSmall"; internal const string Rtmp_DecodeHeader = "Rtmp_DecodeHeader"; internal const string Rtmp_ServerAddMapping = "Rtmp_ServerAddMapping"; internal const string Rtmp_ServerRemoveMapping = "Rtmp_ServerRemoveMapping"; internal const string Rtmp_SocketListenerAccept = "Rtmp_SocketListenerAccept"; internal const string Rtmp_SocketBeginReceive = "Rtmp_SocketBeginReceive"; internal const string Rtmp_SocketReceiveProcessing = "Rtmp_SocketReceiveProcessing"; internal const string Rtmp_SocketBeginRead = "Rtmp_SocketBeginRead"; internal const string Rtmp_SocketReadProcessing = "Rtmp_SocketReadProcessing"; internal const string Rtmp_SocketBeginSend = "Rtmp_SocketBeginSend"; internal const string Rtmp_SocketSendProcessing = "Rtmp_SocketSendProcessing"; internal const string Rtmp_SocketConnectionReset = "Rtmp_SocketConnectionReset"; internal const string Rtmp_SocketConnectionTimeout = "Rtmp_SocketConnectionTimeout"; internal const string Rtmp_SocketConnectionAborted = "Rtmp_SocketConnectionAborted"; internal const string Rtmp_SocketDisconnectProcessing = "Rtmp_SocketDisconnectProcessing"; internal const string Rtmp_ConnectionClose = "Rtmp_ConnectionClose"; internal const string Rtmp_CouldNotProcessMessage = "Rtmp_CouldNotProcessMessage"; internal const string Rtmp_BeginHandlePacket = "Rtmp_BeginHandlePacket"; internal const string Rtmp_EndHandlePacket = "Rtmp_EndHandlePacket"; internal const string Rtmp_BeginDisconnect = "Rtmp_BeginDisconnect"; internal const string Rtmp_WritePacket = "Rtmp_WritePacket"; internal const string Rtmp_SocketSend = "Rtmp_SocketSend"; internal const string Rtmp_HandlerError = "Rtmp_HandlerError"; internal const string PushNotSupported = "PushNotSupported"; internal const string Arg_Mismatch = "Arg_Mismatch"; internal const string Cache_Hit = "Cache_Hit"; internal const string Cache_HitKey = "Cache_HitKey"; internal const string Compiler_Error = "Compiler_Error"; internal const string ClassDefinition_Loaded = "ClassDefinition_Loaded"; internal const string ClassDefinition_LoadedUntyped = "ClassDefinition_LoadedUntyped"; internal const string Externalizable_CastFail = "Externalizable_CastFail"; internal const string TypeIdentifier_Loaded = "TypeIdentifier_Loaded"; internal const string TypeLoad_ASO = "TypeLoad_ASO"; internal const string TypeMapping_Write = "TypeMapping_Write"; internal const string TypeSerializer_NotFound = "TypeSerializer_NotFound"; internal const string Endpoint_BindFail = "Endpoint_BindFail"; internal const string Endpoint_Bind = "Endpoint_Bind"; internal const string Endpoint_HandleMessage = "Endpoint_HandleMessage"; internal const string Endpoint_Response = "Endpoint_Response"; internal const string Type_InitError = "Type_InitError"; internal const string Type_Mismatch = "Type_Mismatch"; internal const string Type_MismatchMissingSource = "Type_MismatchMissingSource"; internal const string Wsdl_ProxyGen = "Wsdl_ProxyGen"; internal const string Wsdl_ProxyGenFail = "Wsdl_ProxyGenFail"; internal const string Destination_NotFound = "Destination_NotFound"; internal const string Destination_Reinit = "Destination_Reinit"; internal const string MessageBroker_NotAvailable = "MessageBroker_NotAvailable"; internal const string MessageBroker_RegisterError = "MessageBroker_RegisterError"; internal const string MessageBroker_RoutingError = "MessageBroker_RoutingError"; internal const string MessageBroker_RoutingMessage = "MessageBroker_RoutingMessage"; internal const string MessageBroker_Response = "MessageBroker_Response"; internal const string MessageServer_TryingServiceConfig = "MessageServer_TryingServiceConfig"; internal const string MessageServer_LoadingConfigDefault = "MessageServer_LoadingConfigDefault"; internal const string MessageServer_LoadingServiceConfig = "MessageServer_LoadingServiceConfig"; internal const string MessageServer_Start = "MessageServer_Start"; internal const string MessageServer_Started = "MessageServer_Started"; internal const string MessageServer_StartError = "MessageServer_StartError"; internal const string MessageServer_Stop = "MessageServer_Stop"; internal const string MessageServer_AccessFail = "MessageServer_AccessFail"; internal const string MessageServer_Create = "MessageServer_Create"; internal const string MessageServer_MissingAdapter = "MessageServer_MissingAdapter"; internal const string MessageClient_Disconnect = "MessageClient_Disconnect"; internal const string MessageClient_Unsubscribe = "MessageClient_Unsubscribe"; internal const string MessageClient_Timeout = "MessageClient_Timeout"; internal const string MessageDestination_RemoveSubscriber = "MessageDestination_RemoveSubscriber"; internal const string MessageServiceSubscribe = "MessageServiceSubscribe"; internal const string MessageServiceUnsubscribe = "MessageServiceUnsubscribe"; internal const string MessageServiceUnknown = "MessageServiceUnknown"; internal const string MessageServiceRoute = "MessageServiceRoute"; internal const string MessageServicePush = "MessageServicePush"; internal const string MessageServicePushBinary = "MessageServicePushBinary"; internal const string Subtopic_Invalid = "Subtopic_Invalid"; internal const string Selector_InvalidResult = "Selector_InvalidResult"; internal const string Client_Create = "Client_Create"; internal const string Client_Invalidated = "Client_Invalidated"; internal const string Client_Lease = "Client_Lease"; internal const string ClientManager_CacheExpired = "ClientManager_CacheExpired"; internal const string ClientManager_Remove = "ClientManager_Remove"; internal const string Session_Create = "Session_Create"; internal const string Session_Invalidated = "Session_Invalidated"; internal const string Session_Lease = "Session_Lease"; internal const string SessionManager_CacheExpired = "SessionManager_CacheExpired"; internal const string SessionManager_Remove = "SessionManager_Remove"; internal const string SubscriptionManager_CacheExpired = "SubscriptionManager_CacheExpired"; internal const string SubscriptionManager_Remove = "SubscriptionManager_Remove"; internal const string Invalid_Destination = "Invalid_Destination"; internal const string Security_AccessNotAllowed = "Security_AccessNotAllowed"; internal const string Security_LoginMissing = "Security_LoginMissing"; internal const string Security_ConstraintRefNotFound = "Security_ConstraintRefNotFound"; internal const string Security_ConstraintSectionNotFound = "Security_ConstraintSectionNotFound"; internal const string Security_AuthenticationFailed = "Security_AuthenticationFailed"; internal const string SocketServer_Start = "SocketServer_Start"; internal const string SocketServer_Started = "SocketServer_Started"; internal const string SocketServer_Stopping = "SocketServer_Stopping"; internal const string SocketServer_Stopped = "SocketServer_Stopped"; internal const string SocketServer_Failed = "SocketServer_Failed"; internal const string SocketServer_ListenerFail = "SocketServer_ListenerFail"; internal const string SocketServer_SocketOptionFail = "SocketServer_SocketOptionFail"; internal const string RtmpEndpoint_Start = "RtmpEndpoint_Start"; internal const string RtmpEndpoint_Starting = "RtmpEndpoint_Starting"; internal const string RtmpEndpoint_Started = "RtmpEndpoint_Started"; internal const string RtmpEndpoint_Stopping = "RtmpEndpoint_Stopping"; internal const string RtmpEndpoint_Stopped = "RtmpEndpoint_Stopped"; internal const string RtmpEndpoint_Failed = "RtmpEndpoint_Failed"; internal const string RtmpEndpoint_Error = "RtmpEndpoint_Error"; internal const string Scope_Connect = "Scope_Connect"; internal const string Scope_NotFound = "Scope_NotFound"; internal const string Scope_ChildNotFound = "Scope_ChildNotFound"; internal const string Scope_Check = "Scope_Check"; internal const string Scope_CheckHostPath = "Scope_CheckHostPath"; internal const string Scope_CheckWildcardHostPath = "Scope_CheckWildcardHostPath"; internal const string Scope_CheckHostNoPath = "Scope_CheckHostNoPath"; internal const string Scope_CheckDefaultHostPath = "Scope_CheckDefaultHostPath"; internal const string Scope_UnregisterError = "Scope_UnregisterError"; internal const string Scope_DisconnectError = "Scope_DisconnectError"; internal const string SharedObject_Delete = "SharedObject_Delete"; internal const string SharedObject_DeleteError = "SharedObject_DeleteError"; internal const string SharedObject_StoreError = "SharedObject_StoreError"; internal const string SharedObject_Sync = "SharedObject_Sync"; internal const string SharedObject_SyncConnError = "SharedObject_SyncConnError"; internal const string SharedObjectService_CreateStore = "SharedObjectService_CreateStore"; internal const string SharedObjectService_CreateStoreError = "SharedObjectService_CreateStoreError"; internal const string DataDestination_RemoveSubscriber = "DataDestination_RemoveSubscriber"; internal const string DataService_Unknown = "DataService_Unknown"; internal const string Sequence_AddSubscriber = "Sequence_AddSubscriber"; internal const string Sequence_RemoveSubscriber = "Sequence_RemoveSubscriber"; internal const string SequenceManager_CreateSeq = "SequenceManager_CreateSeq"; internal const string SequenceManager_Remove = "SequenceManager_Remove"; internal const string SequenceManager_RemoveStatus = "SequenceManager_RemoveStatus"; internal const string SequenceManager_Unknown = "SequenceManager_Unknown"; internal const string SequenceManager_ReleaseCollection = "SequenceManager_ReleaseCollection"; internal const string SequenceManager_RemoveSubscriber = "SequenceManager_RemoveSubscriber"; internal const string SequenceManager_RemoveEmptySeq = "SequenceManager_RemoveEmptySeq"; internal const string SequenceManager_RemoveSubscriberSeq = "SequenceManager_RemoveSubscriberSeq"; internal const string Service_NotFound = "Service_NotFound"; internal const string Service_Mapping = "Service_Mapping"; internal const string ServiceHandler_InvocationFailed = "ServiceHandler_InvocationFailed"; internal const string Identity_Failed = "Identity_Failed"; internal const string Invoke_Method = "Invoke_Method"; internal const string Channel_NotFound = "Channel_NotFound"; internal const string TypeHelper_Probing = "TypeHelper_Probing"; internal const string TypeHelper_LoadDllFail = "TypeHelper_LoadDllFail"; internal const string TypeHelper_ConversionFail = "TypeHelper_ConversionFail"; internal const string Invocation_NoSuitableMethod = "Invocation_NoSuitableMethod"; internal const string Invocation_Ambiguity = "Invocation_Ambiguity"; internal const string Invocation_ParameterType = "Invocation_ParameterType"; internal const string Invocation_Failed = "Invocation_Failed"; internal const string ServiceInvoker_Resolve = "ServiceInvoker_Resolve"; internal const string ServiceInvoker_ResolveFail = "ServiceInvoker_ResolveFail"; internal const string Reflection_MemberNotFound = "Reflection_MemberNotFound"; internal const string Reflection_PropertyReadOnly = "Reflection_PropertyReadOnly"; internal const string Reflection_PropertySetFail = "Reflection_PropertySetFail"; internal const string Reflection_PropertyIndexFail = "Reflection_PropertyIndexFail"; internal const string Reflection_FieldSetFail = "Reflection_FieldSetFail"; internal const string AppAdapter_AppConnect = "AppAdapter_AppConnect"; internal const string AppAdapter_AppDisconnect = "AppAdapter_AppDisconnect"; internal const string AppAdapter_RoomConnect = "AppAdapter_RoomConnect"; internal const string AppAdapter_RoomDisconnect = "AppAdapter_RoomDisconnect"; internal const string AppAdapter_AppStart = "AppAdapter_AppStart"; internal const string AppAdapter_RoomStart = "AppAdapter_RoomStart"; internal const string AppAdapter_AppStop = "AppAdapter_AppStop"; internal const string AppAdapter_RoomStop = "AppAdapter_RoomStop"; internal const string AppAdapter_AppJoin = "AppAdapter_AppJoin"; internal const string AppAdapter_AppLeave = "AppAdapter_AppLeave"; internal const string AppAdapter_RoomJoin = "AppAdapter_RoomJoin"; internal const string AppAdapter_RoomLeave = "AppAdapter_RoomLeave"; internal const string Compress_Info = "Compress_Info"; internal const string Fluorine_InitModule = "Fluorine_InitModule"; internal const string Fluorine_Start = "Fluorine_Start"; internal const string Fluorine_Version = "Fluorine_Version"; internal const string Fluorine_Fatal = "Fluorine_Fatal"; internal const string ServiceBrowser_Aquire = "ServiceBrowser_Aquire"; internal const string ServiceBrowser_Aquired = "ServiceBrowser_Aquired"; internal const string ServiceBrowser_AquireFail = "ServiceBrowser_AquireFail"; internal const string ServiceAdapter_MissingSettings = "ServiceAdapter_MissingSettings"; internal const string ServiceAdapter_Stop = "ServiceAdapter_Stop"; internal const string ServiceAdapter_ManageFail = "ServiceAdapter_ManageFail"; internal const string Msmq_StartQueue = "Msmq_StartQueue"; internal const string Msmq_InitFormatter = "Msmq_InitFormatter"; internal const string Msmq_Receive = "Msmq_Receive"; internal const string Msmq_Send = "Msmq_Send"; internal const string Msmq_Fail = "Msmq_Fail"; internal const string Msmq_Enable = "Msmq_Enable"; internal const string Msmq_Poison = "Msmq_Poison"; internal const string Silverlight_StartPS = "Silverlight_StartPS"; internal const string Silverlight_PSError = "Silverlight_PSError"; internal const string Optimizer_Fatal = "Optimizer_Fatal"; internal const string Optimizer_Warning = "Optimizer_Warning"; internal const string Optimizer_FileLocation = "Optimizer_FileLocation"; internal const string Error_ContextDump = "Error_ContextDump"; internal static string GetString(string key) { if (_resMgr == null) { _resMgr = new ResourceManager("FluorineFx.Resources.Resource", typeof(__Res).Assembly); } string text = _resMgr.GetString(key); if (text == null) { throw new ApplicationException("Missing resource from FluorineFx library! Key: " + key); } return text; } internal static string GetString(string key, params object[] inserts) { return string.Format(GetString(key), inserts); } } }
#region license /* MediaFoundationLib - Provide access to MediaFoundation interfaces via .NET Copyright (C) 2007 http://mfnet.sourceforge.net This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #endregion using System; using System.Collections; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security; using MediaFoundation.Misc; using MediaFoundation.Transform; using MediaFoundation.ReadWrite; using MediaFoundation.MFPlayer; using MediaFoundation.EVR; namespace MediaFoundation { public static class MFExtern { [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFShutdown(); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFStartup( int Version, MFStartup dwFlags ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSystemTimeSource( out IMFPresentationTimeSource ppSystemTimeSource ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateCollection( out IMFCollection ppIMFCollection ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateStreamDescriptor( int dwStreamIdentifier, int cMediaTypes, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] IMFMediaType[] apMediaTypes, out IMFStreamDescriptor ppDescriptor ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int CreatePropertyStore( out IPropertyStore ppStore ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAttributes( out IMFAttributes ppMFAttributes, int cInitialSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateWaveFormatExFromMFMediaType( IMFMediaType pMFType, [Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(WEMarshaler))] out WaveFormatEx ppWF, out int pcbSize, MFWaveFormatExConvertFlags Flags ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAsyncResult( [MarshalAs(UnmanagedType.IUnknown)] object punkObject, IMFAsyncCallback pCallback, [MarshalAs(UnmanagedType.IUnknown)] object punkState, out IMFAsyncResult ppAsyncResult ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInvokeCallback( IMFAsyncResult pAsyncResult ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreatePresentationDescriptor( int cStreamDescriptors, [In, MarshalAs(UnmanagedType.LPArray)] IMFStreamDescriptor[] apStreamDescriptors, out IMFPresentationDescriptor ppPresentationDescriptor ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitMediaTypeFromWaveFormatEx( IMFMediaType pMFType, [In, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(WEMarshaler))] WaveFormatEx ppWF, int cbBufSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateEventQueue( out IMFMediaEventQueue ppMediaEventQueue ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaType( out IMFMediaType ppMFType ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaEvent( MediaEventType met, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidExtendedType, int hrStatus, [In, MarshalAs(UnmanagedType.LPStruct)] ConstPropVariant pvValue, out IMFMediaEvent ppEvent ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSample( out IMFSample ppIMFSample ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMemoryBuffer( int cbMaxLength, out IMFMediaBuffer ppBuffer ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetService( [In, MarshalAs(UnmanagedType.Interface)] object punkObject, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppvObject ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoRendererActivate( IntPtr hwndVideo, out IMFActivate ppActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTopologyNode( MFTopologyType NodeType, out IMFTopologyNode ppNode ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSourceResolver( out IMFSourceResolver ppISourceResolver ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaSession( IMFAttributes pConfiguration, out IMFMediaSession ppMediaSession ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTopology( out IMFTopology ppTopo ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAudioRendererActivate( out IMFActivate ppActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreatePresentationClock( out IMFPresentationClock ppPresentationClock ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFEnumDeviceSources( IMFAttributes pAttributes, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] out IMFActivate[] pppSourceActivate, out int pcSourceActivate ); [DllImport("mfplat.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTRegister( [In, MarshalAs(UnmanagedType.Struct)] Guid clsidMFT, [In, MarshalAs(UnmanagedType.Struct)] Guid guidCategory, [In, MarshalAs(UnmanagedType.LPWStr)] string pszName, [In] int Flags, // Must be zero [In] int cInputTypes, [In, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(RTAMarshaler))] object pInputTypes, // should be MFTRegisterTypeInfo[], but .Net bug prevents in x64 [In] int cOutputTypes, [In, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(RTAMarshaler))] object pOutputTypes, // should be MFTRegisterTypeInfo[], but .Net bug prevents in x64 [In] IMFAttributes pAttributes ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTUnregister( [In, MarshalAs(UnmanagedType.Struct)] Guid clsidMFT ); [DllImport("mfplat.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTGetInfo( [In, MarshalAs(UnmanagedType.Struct)] Guid clsidMFT, [MarshalAs(UnmanagedType.LPWStr)] out string pszName, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "0", MarshalTypeRef = typeof(RTIMarshaler))] ArrayList ppInputTypes, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "0", MarshalTypeRef = typeof(RTIMarshaler))] MFInt pcInputTypes, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "1", MarshalTypeRef = typeof(RTIMarshaler))] ArrayList ppOutputTypes, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "1", MarshalTypeRef = typeof(RTIMarshaler))] MFInt pcOutputTypes, IntPtr ip // Must be IntPtr.Zero due to MF bug, but should be out IMFAttributes ppAttributes ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int CreateNamedPropertyStore( out INamedPropertyStore ppStore ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFLockPlatform(); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFUnlockPlatform(); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetTimerPeriodicity( out int Periodicity); [DllImport("mfplat.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateFile( MFFileAccessMode AccessMode, MFFileOpenMode OpenMode, MFFileFlags fFlags, [MarshalAs(UnmanagedType.LPWStr)] string pwszFileURL, out IMFByteStream ppIByteStream); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTempFile( MFFileAccessMode AccessMode, MFFileOpenMode OpenMode, MFFileFlags fFlags, out IMFByteStream ppIByteStream); [DllImport("mfplat.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFBeginCreateFile( [In] MFFileAccessMode AccessMode, [In] MFFileOpenMode OpenMode, [In] MFFileFlags fFlags, [In, MarshalAs(UnmanagedType.LPWStr)] string pwszFilePath, [In] IMFAsyncCallback pCallback, [In] [MarshalAs(UnmanagedType.IUnknown)] object pState, [MarshalAs(UnmanagedType.IUnknown)] out object ppCancelCookie); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFEndCreateFile( [In] IMFAsyncResult pResult, out IMFByteStream ppFile); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCancelCreateFile( [In] [MarshalAs(UnmanagedType.IUnknown)] object pCancelCookie); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAlignedMemoryBuffer( [In] int cbMaxLength, [In] int cbAligment, out IMFMediaBuffer ppBuffer); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern long MFGetSystemTime( ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetSupportedSchemes( [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(PVMarshaler))] PropVariant pPropVarSchemeArray ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetSupportedMimeTypes( [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(PVMarshaler))] PropVariant pPropVarSchemeArray ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSimpleTypeHandler( out IMFMediaTypeHandler ppHandler ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSequencerSegmentOffset( int dwId, long hnsOffset, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(PVMarshaler))] PropVariant pvarSegmentOffset ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoRenderer( [MarshalAs(UnmanagedType.LPStruct)] Guid riidRenderer, [MarshalAs(UnmanagedType.IUnknown)] out object ppVideoRenderer ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaBufferWrapper( [In] IMFMediaBuffer pBuffer, [In] int cbOffset, [In] int dwLength, out IMFMediaBuffer ppBuffer); // Technically, the last param should be an IMediaBuffer. However, that interface is // beyond the scope of this library. If you are using DirectShowNet (where this *is* // defined), you can cast from the object to the IMediaBuffer. [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateLegacyMediaBufferOnMFMediaBuffer( [In] IMFSample pSample, [In] IMFMediaBuffer pMFMediaBuffer, [In] int cbOffset, [MarshalAs(UnmanagedType.IUnknown)] out object ppMediaBuffer); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitAttributesFromBlob( [In] IMFAttributes pAttributes, IntPtr pBuf, [In] int cbBufSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetAttributesAsBlobSize( [In] IMFAttributes pAttributes, out int pcbBufSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetAttributesAsBlob( [In] IMFAttributes pAttributes, IntPtr pBuf, [In] int cbBufSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFSerializeAttributesToStream( IMFAttributes pAttr, MFAttributeSerializeOptions dwOptions, IStream pStm); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFDeserializeAttributesFromStream( IMFAttributes pAttr, MFAttributeSerializeOptions dwOptions, IStream pStm); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMFVideoFormatFromMFMediaType( [In] IMFMediaType pMFType, out MFVideoFormat ppMFVF, out int pcbSize ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetUncompressedVideoFormat( [In, MarshalAs(UnmanagedType.LPStruct)] MFVideoFormat pVideoFormat ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitMediaTypeFromMFVideoFormat( [In] IMFMediaType pMFType, MFVideoFormat pMFVF, [In] int cbBufSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitAMMediaTypeFromMFMediaType( [In] IMFMediaType pMFType, [In, MarshalAs(UnmanagedType.Struct)] Guid guidFormatBlockType, [Out] AMMediaType pAMType ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAMMediaTypeFromMFMediaType( [In] IMFMediaType pMFType, [In, MarshalAs(UnmanagedType.Struct)] Guid guidFormatBlockType, out AMMediaType ppAMType // delete with DeleteMediaType ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitMediaTypeFromAMMediaType( [In] IMFMediaType pMFType, [In] AMMediaType pAMType ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitMediaTypeFromVideoInfoHeader( [In] IMFMediaType pMFType, VideoInfoHeader pVIH, [In] int cbBufSize, [In, MarshalAs(UnmanagedType.LPStruct)] Guid pSubtype ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitMediaTypeFromVideoInfoHeader2( [In] IMFMediaType pMFType, VideoInfoHeader2 pVIH2, [In] int cbBufSize, [In, MarshalAs(UnmanagedType.LPStruct)] Guid pSubtype ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMediaType( MFVideoFormat pVideoFormat, out IMFVideoMediaType ppIVideoMediaType ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTEnum( [In, MarshalAs(UnmanagedType.Struct)] Guid guidCategory, [In] int Flags, // Must be zero [In, MarshalAs(UnmanagedType.LPStruct)] MFTRegisterTypeInfo pInputType, [In, MarshalAs(UnmanagedType.LPStruct)] MFTRegisterTypeInfo pOutputType, [In] IMFAttributes pAttributes, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "0", MarshalTypeRef = typeof(GAMarshaler))] ArrayList ppclsidMFT, [In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "0", MarshalTypeRef = typeof(GAMarshaler))] MFInt pcMFTs ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSequencerSource( [MarshalAs(UnmanagedType.IUnknown)] object pReserved, out IMFSequencerSource ppSequencerSource ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFAllocateWorkQueue( out int pdwWorkQueue); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFUnlockWorkQueue( [In] int dwWorkQueue); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFPutWorkItem( int dwQueue, IMFAsyncCallback pCallback, [MarshalAs(UnmanagedType.IUnknown)] object pState); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreatePMPMediaSession( MFPMPSessionCreationFlags dwCreationFlags, IMFAttributes pConfiguration, out IMFMediaSession ppMediaSession, out IMFActivate ppEnablerActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFContentInfo( out IMFASFContentInfo ppIContentInfo); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFSplitter( out IMFASFSplitter ppISplitter); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFProfile( out IMFASFProfile ppIProfile); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAudioRenderer( IMFAttributes pAudioAttributes, out IMFMediaSink ppSink ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFIndexer( out IMFASFIndexer ppIIndexer); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetStrideForBitmapInfoHeader( int format, int dwWidth, out int pStride ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCalculateBitmapImageSize( [In, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(BMMarshaler))] BitmapInfoHeader pBMIH, [In] int cbBufSize, out int pcbImageSize, out bool pbKnown ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoSampleFromSurface( [In, MarshalAs(UnmanagedType.IUnknown)] object pUnkSurface, out IMFSample ppSample ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFFrameRateToAverageTimePerFrame( [In] int unNumerator, [In] int unDenominator, out long punAverageTimePerFrame ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFUnwrapMediaType( [In] IMFMediaType pWrap, out IMFMediaType ppOrig ); #if ALLOW_UNTESTED_INTERFACES #region Tested // While these methods are tested, the interfaces they use are not [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTopoLoader( out IMFTopoLoader ppObj ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateStandardQualityManager( out IMFQualityManager ppQualityManager ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreatePMPServer( MFPMPSessionCreationFlags dwCreationFlags, out IMFPMPServer ppPMPServer ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFMultiplexer( out IMFASFMultiplexer ppIMultiplexer); #endregion #region Work Queue [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFPutWorkItemEx( int dwQueue, IMFAsyncResult pResult); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFScheduleWorkItem( IMFAsyncCallback pCallback, [MarshalAs(UnmanagedType.IUnknown)] object pState, long Timeout, long pKey); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFScheduleWorkItemEx( IMFAsyncResult pResult, long Timeout, long pKey); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCancelWorkItem( long Key); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFAddPeriodicCallback( IntPtr Callback, [MarshalAs(UnmanagedType.IUnknown)] object pContext, out int pdwKey); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFRemovePeriodicCallback( int dwKey); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFLockWorkQueue( [In] int dwWorkQueue); [DllImport("mfplat.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFBeginRegisterWorkQueueWithMMCSS( int dwWorkQueueId, [In, MarshalAs(UnmanagedType.LPWStr)] string wszClass, int dwTaskId, [In] IMFAsyncCallback pDoneCallback, [In] [MarshalAs(UnmanagedType.IUnknown)] object pDoneState); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFEndRegisterWorkQueueWithMMCSS( [In] IMFAsyncResult pResult, out int pdwTaskId); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFBeginUnregisterWorkQueueWithMMCSS( int dwWorkQueueId, [In] IMFAsyncCallback pDoneCallback, [In] [MarshalAs(UnmanagedType.IUnknown)] object pDoneState); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFEndUnregisterWorkQueueWithMMCSS( [In] IMFAsyncResult pResult); [DllImport("mf.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFSetWorkQueueClass( int dwWorkQueueId, [MarshalAs(UnmanagedType.LPWStr)] string szClass); [DllImport("mfplat.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetWorkQueueMMCSSClass( int dwWorkQueueId, [MarshalAs(UnmanagedType.LPWStr)] out string pwszClass, out int pcchClass); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetWorkQueueMMCSSTaskId( int dwWorkQueueId, out int pdwTaskId); #endregion #region Check dllimport [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAC3MediaSink( IMFByteStream pTargetByteStream, IMFMediaType pAudioMediaType, out IMFMediaSink ppMediaSink ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateADTSMediaSink( IMFByteStream pTargetByteStream, IMFMediaType pAudioMediaType, out IMFMediaSink ppMediaSink ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMuxSink( [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidOutputSubType, IMFAttributes pOutputAttributes, IMFByteStream pOutputByteStream, out IMFMediaSink ppMuxSink ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateFMPEG4MediaSink( IMFByteStream pIByteStream, IMFMediaType pVideoMediaType, IMFMediaType pAudioMediaType, out IMFMediaSink ppIMediaSink ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTranscodeTopologyFromByteStream( IMFMediaSource pSrc, IMFByteStream pOutputStream, IMFTranscodeProfile pProfile, out IMFTopology ppTranscodeTopo ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTrackedSample( out IMFTrackedSample ppMFSample ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateStreamOnMFByteStream( IMFByteStream pByteStream, out IStream ppStream ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMFByteStreamOnStreamEx( [MarshalAs(UnmanagedType.IUnknown)] object punkStream, out IMFByteStream ppByteStream ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateStreamOnMFByteStreamEx( IMFByteStream pByteStream, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaTypeFromProperties( [MarshalAs(UnmanagedType.IUnknown)] object punkStream, out IMFMediaType ppMediaType ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreatePropertiesFromMediaType( IMFMediaType pMediaType, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateProtectedEnvironmentAccess( out IMFProtectedEnvironmentAccess ppAccess ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFLoadSignedLibrary( [In, MarshalAs(UnmanagedType.LPWStr)] string pszName, out IMFSignedLibrary ppLib ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetSystemId( out IMFSystemId ppId ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFPutWorkItem2( int dwQueue, int Priority, IMFAsyncCallback pCallback, [In, MarshalAs(UnmanagedType.IUnknown)] object pState ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFPutWorkItemEx2( int dwQueue, int Priority, IMFAsyncResult pResult ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFPutWaitingWorkItem( IntPtr hEvent, int Priority, IMFAsyncResult pResult, out long pKey ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFAllocateSerialWorkQueue( int dwWorkQueue, out int pdwWorkQueue ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFBeginRegisterWorkQueueWithMMCSSEx( int dwWorkQueueId, [In, MarshalAs(UnmanagedType.LPWStr)] string wszClass, int dwTaskId, int lPriority, IMFAsyncCallback pDoneCallback, [In, MarshalAs(UnmanagedType.IUnknown)] object pDoneState ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFRegisterPlatformWithMMCSS( [In, MarshalAs(UnmanagedType.LPWStr)] string wszClass, ref int pdwTaskId, int lPriority ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFUnregisterPlatformFromMMCSS(); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFLockSharedWorkQueue( [In, MarshalAs(UnmanagedType.LPWStr)] string wszClass, int BasePriority, ref int pdwTaskId, out int pID ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetWorkQueueMMCSSPriority( int dwWorkQueueId, out int lPriority ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFMapDX9FormatToDXGIFormat( int dx9 ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFMapDXGIFormatToDX9Format( int dx11 ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFLockDXGIDeviceManager( out int pResetToken, out IMFDXGIDeviceManager ppManager ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFUnlockDXGIDeviceManager(); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateWICBitmapBuffer( [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] object punkSurface, out IMFMediaBuffer ppBuffer ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateDXGISurfaceBuffer( [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] object punkSurface, int uSubresourceIndex, bool fBottomUpWhenLinear, out IMFMediaBuffer ppBuffer ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoSampleAllocatorEx( [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppSampleAllocator ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateDXGIDeviceManager( out int resetToken, out IMFDXGIDeviceManager ppDeviceManager ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFRegisterLocalSchemeHandler( [In, MarshalAs(UnmanagedType.LPWStr)] string szScheme, IMFActivate pActivate ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFRegisterLocalByteStreamHandler( [In, MarshalAs(UnmanagedType.LPWStr)] string szFileExtension, [In, MarshalAs(UnmanagedType.LPWStr)] string szMimeType, IMFActivate pActivate ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMFByteStreamWrapper( IMFByteStream pStream, out IMFByteStream ppStreamWrapper ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaExtensionActivate( [In, MarshalAs(UnmanagedType.LPWStr)] string szActivatableClassId, [MarshalAs(UnmanagedType.Interface)] object pConfiguration, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreate2DMediaBuffer( int dwWidth, int dwHeight, int dwFourCC, bool fBottomUp, out IMFMediaBuffer ppBuffer ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaBufferFromMediaType( IMFMediaType pMediaType, long llDuration, int dwMinLength, int dwMinAlignment, out IMFMediaBuffer ppBuffer ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetContentProtectionSystemCLSID( [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidProtectionSystemID, out Guid pclsid ); #endregion [DllImport("MFCaptureEngine.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateCaptureEngine( out IMFCaptureEngine ppCaptureEngine ); [DllImport("Mfreadwrite.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSinkWriterFromURL( [In, MarshalAs(UnmanagedType.LPWStr)] string pwszOutputURL, IMFByteStream pByteStream, IMFAttributes pAttributes, out IMFSinkWriter ppSinkWriter ); [DllImport("Mfreadwrite.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSinkWriterFromMediaSink( IMFMediaSink pMediaSink, IMFAttributes pAttributes, out IMFSinkWriter ppSinkWriter ); [DllImport("Mfreadwrite.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSourceReaderFromURL( [In, MarshalAs(UnmanagedType.LPWStr)] string pwszURL, IMFAttributes pAttributes, out IMFSourceReader ppSourceReader ); [DllImport("Mfreadwrite.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSourceReaderFromByteStream( IMFByteStream pByteStream, IMFAttributes pAttributes, out IMFSourceReader ppSourceReader ); [DllImport("Mfreadwrite.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSourceReaderFromMediaSource( IMFMediaSource pMediaSource, IMFAttributes pAttributes, out IMFSourceReader ppSourceReader ); [DllImport("mfplay.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFPCreateMediaPlayer( [In, MarshalAs(UnmanagedType.LPWStr)] string pwszURL, [MarshalAs(UnmanagedType.Bool)] bool fStartPlayback, MFP_CREATION_OPTIONS creationOptions, IMFPMediaPlayerCallback pCallback, IntPtr hWnd, out IMFPMediaPlayer ppMediaPlayer); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateRemoteDesktopPlugin( out IMFRemoteDesktopPlugin ppPlugin ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateDXSurfaceBuffer( [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [In] [MarshalAs(UnmanagedType.IUnknown)] object punkSurface, [In] bool fBottomUpWhenLinear, out IMFMediaBuffer ppBuffer); // -------------------------------------------------- [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFValidateMediaTypeSize( [In, MarshalAs(UnmanagedType.Struct)] Guid FormatType, IntPtr pBlock, [In] int cbSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitMediaTypeFromMPEG1VideoInfo( [In] IMFMediaType pMFType, MPEG1VideoInfo pMP1VI, [In] int cbBufSize, [In, MarshalAs(UnmanagedType.LPStruct)] Guid pSubtype ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitMediaTypeFromMPEG2VideoInfo( [In] IMFMediaType pMFType, Mpeg2VideoInfo pMP2VI, [In] int cbBufSize, [In, MarshalAs(UnmanagedType.LPStruct)] Guid pSubtype ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCalculateImageSize( [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidSubtype, [In] int unWidth, [In] int unHeight, out int pcbImageSize ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFAverageTimePerFrameToFrameRate( [In] long unAverageTimePerFrame, out int punNumerator, out int punDenominator ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCompareFullToPartialMediaType( [In] IMFMediaType pMFTypeFull, [In] IMFMediaType pMFTypePartial ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFWrapMediaType( [In] IMFMediaType pOrig, [In, MarshalAs(UnmanagedType.LPStruct)] Guid MajorType, [In, MarshalAs(UnmanagedType.LPStruct)] Guid SubType, out IMFMediaType ppWrap ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMediaTypeFromSubtype( [In, MarshalAs(UnmanagedType.LPStruct)] Guid pAMSubtype, out IMFVideoMediaType ppIVideoMediaType ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern bool MFIsFormatYUV( int Format ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetPlaneSize( int format, int dwWidth, int dwHeight, out int pdwPlaneSize ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitVideoFormat( [In] MFVideoFormat pVideoFormat, [In] MFStandardVideoFormat type ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFInitVideoFormat_RGB( [In] MFVideoFormat pVideoFormat, [In] int dwWidth, [In] int dwHeight, [In] int D3Dfmt ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFConvertColorInfoToDXVA( out int pdwToDXVA, MFVideoFormat pFromFormat ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFConvertColorInfoFromDXVA( MFVideoFormat pToFormat, int dwFromDXVA ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCopyImage( IntPtr pDest, int lDestStride, IntPtr pSrc, int lSrcStride, int dwWidthInBytes, int dwLines ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFConvertFromFP16Array( float[] pDest, short[] pSrc, int dwCount ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFConvertToFP16Array( short[] pDest, float[] pSrc, int dwCount ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMediaTypeFromRepresentation( [MarshalAs(UnmanagedType.Struct)] Guid guidRepresentation, IntPtr pvRepresentation, out IMFMediaType ppIMediaType ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFRequireProtectedEnvironment( IMFPresentationDescriptor pPresentationDescriptor ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFSerializePresentationDescriptor( IMFPresentationDescriptor pPD, out int pcbData, IntPtr ppbData ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFDeserializePresentationDescriptor( int cbData, IntPtr pbData, out IMFPresentationDescriptor ppPD ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFShutdownObject( object pUnk ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSampleGrabberSinkActivate( IMFMediaType pIMFMediaType, IMFSampleGrabberSinkCallback pIMFSampleGrabberSinkCallback, out IMFActivate ppIActivate ); [DllImport("mf.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateProxyLocator( [MarshalAs(UnmanagedType.LPWStr)] string pszProtocol, IPropertyStore pProxyConfig, out IMFNetProxyLocator ppProxyLocator ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateNetSchemePlugin( [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] object ppvHandler ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFProfileFromPresentationDescriptor( [In] IMFPresentationDescriptor pIPD, out IMFASFProfile ppIProfile); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFIndexerByteStream( [In] IMFByteStream pIContentByteStream, [In] long cbIndexStartOffset, out IMFByteStream pIIndexByteStream); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFStreamSelector( [In] IMFASFProfile pIASFProfile, out IMFASFStreamSelector ppSelector); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFMediaSink( IMFByteStream pIByteStream, out IMFMediaSink ppIMediaSink ); [DllImport("mf.dll", CharSet = CharSet.Unicode, ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFMediaSinkActivate( [MarshalAs(UnmanagedType.LPWStr)] string pwszFileName, IMFASFContentInfo pContentInfo, out IMFActivate ppIActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateWMVEncoderActivate( IMFMediaType pMediaType, IPropertyStore pEncodingConfigurationProperties, out IMFActivate ppActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateWMAEncoderActivate( IMFMediaType pMediaType, IPropertyStore pEncodingConfigurationProperties, out IMFActivate ppActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreatePresentationDescriptorFromASFProfile( [In] IMFASFProfile pIProfile, out IMFPresentationDescriptor ppIPD); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoPresenter( [In, MarshalAs(UnmanagedType.IUnknown)] object pOwner, [MarshalAs(UnmanagedType.LPStruct)] Guid riidDevice, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IntPtr ppVideoPresenter ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMixer( [In, MarshalAs(UnmanagedType.IUnknown)] object pOwner, [MarshalAs(UnmanagedType.LPStruct)] Guid riidDevice, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppVideoMixer ); [DllImport("evr.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMixerAndPresenter( [In, MarshalAs(UnmanagedType.IUnknown)] object pMixerOwner, [In, MarshalAs(UnmanagedType.IUnknown)] object pPresenterOwner, [MarshalAs(UnmanagedType.LPStruct)] Guid riidMixer, out IntPtr ppvVideoMixer, [MarshalAs(UnmanagedType.LPStruct)] Guid riidPresenter, out IntPtr ppvVideoPresenter ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFStreamingMediaSink( IMFByteStream pIByteStream, out IMFMediaSink ppIMediaSink ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateASFStreamingMediaSinkActivate( IMFActivate pByteStreamActivate, IMFASFContentInfo pContentInfo, out IMFActivate ppIActivate ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTransformActivate( out IMFActivate ppActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateDeviceSource( IMFAttributes pAttributes, out IMFMediaSource ppSource ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateDeviceSourceActivate( IMFAttributes pAttributes, out IMFActivate ppActivate ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateSampleCopierMFT(out IMFTransform ppCopierMFT); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTranscodeProfile( out IMFTranscodeProfile ppTranscodeProfile ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTranscodeTopology( IMFMediaSource pSrc, [MarshalAs(UnmanagedType.LPWStr)] string pwszOutputFilePath, IMFTranscodeProfile pProfile, out IMFTopology ppTranscodeTopo ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTranscodeGetAudioOutputAvailableTypes( [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidSubType, int dwMFTFlags, IMFAttributes pCodecConfig, out IMFCollection ppAvailableTypes ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateTranscodeSinkActivate( out IMFActivate ppActivate ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMFByteStreamOnStream( IStream pStream, out IMFByteStream ppByteStream ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAggregateSource( IMFCollection pSourceCollection, out IMFMediaSource ppAggSource ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetTopoNodeCurrentType( IMFTopologyNode pNode, int dwStreamIndex, [MarshalAs(UnmanagedType.Bool)] bool fOutput, out IMFMediaType ppType); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMPEG4MediaSink( IMFByteStream pIByteStream, IMFMediaType pVideoMediaType, IMFMediaType pAudioMediaType, out IMFMediaSink ppIMediaSink ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreate3GPMediaSink( IMFByteStream pIByteStream, IMFMediaType pVideoMediaType, IMFMediaType pAudioMediaType, out IMFMediaSink ppIMediaSink ); [DllImport("mf.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateMP3MediaSink( IMFByteStream pTargetByteStream, out IMFMediaSink ppMediaSink ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMediaTypeFromBitMapInfoHeaderEx( BitmapInfoHeader[] pbmihBitMapInfoHeader, int cbBitMapInfoHeader, int dwPixelAspectRatioX, int dwPixelAspectRatioY, MFVideoInterlaceMode InterlaceMode, long VideoFlags, int dwFramesPerSecondNumerator, int dwFramesPerSecondDenominator, int dwMaxBitRate, out IMFVideoMediaType ppIVideoMediaType ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetPluginControl( out IMFPluginControl ppPluginControl ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFGetMFTMerit( [MarshalAs(UnmanagedType.IUnknown)] object pMFT, int cbVerifier, IntPtr verifier, out int merit ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTEnumEx( [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidCategory, int Flags, MFTRegisterTypeInfo pInputType, MFTRegisterTypeInfo pOutputType, out IMFActivate[] pppMFTActivate, out int pnumMFTActivate ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFAllocateWorkQueueEx( MFASYNC_WORKQUEUE_TYPE WorkQueueType, out int pdwWorkQueue ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTRegisterLocal( [MarshalAs(UnmanagedType.IUnknown)] object pClassFactory, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidCategory, [MarshalAs(UnmanagedType.LPWStr)] string pszName, int Flags, int cInputTypes, MFTRegisterTypeInfo[] pInputTypes, int cOutputTypes, MFTRegisterTypeInfo[] pOutputTypes ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTUnregisterLocal( [MarshalAs(UnmanagedType.IUnknown)] object pClassFactory ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTRegisterLocalByCLSID( [In, MarshalAs(UnmanagedType.LPStruct)] Guid clisdMFT, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidCategory, [MarshalAs(UnmanagedType.LPWStr)] string pszName, MFT_EnumFlag Flags, int cInputTypes, MFTRegisterTypeInfo[] pInputTypes, int cOutputTypes, MFTRegisterTypeInfo[] pOutputTypes ); [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFTUnregisterLocalByCLSID( [In, MarshalAs(UnmanagedType.LPStruct)] Guid clsidMFT ); #region Untestable [DllImport("mfplat.dll", ExactSpelling = true), Obsolete("This function is deprecated"), SuppressUnmanagedCodeSecurity] public static extern int MFCreateAudioMediaType( [In] WaveFormatEx pAudioFormat, out IMFAudioMediaType ppIAudioMediaType ); [DllImport("mf.dll", ExactSpelling = true), Obsolete("The returned object doesn't support QI"), SuppressUnmanagedCodeSecurity] public static extern int MFCreateCredentialCache( out IMFNetCredentialCache ppCache ); [DllImport("evr.dll", ExactSpelling = true), Obsolete("Not implemented"), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMediaTypeFromBitMapInfoHeader( [In, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(BMMarshaler))] BitmapInfoHeader pbmihBitMapInfoHeader, int dwPixelAspectRatioX, int dwPixelAspectRatioY, MFVideoInterlaceMode InterlaceMode, long VideoFlags, long qwFramesPerSecondNumerator, long qwFramesPerSecondDenominator, int dwMaxBitRate, out IMFVideoMediaType ppIVideoMediaType ); [DllImport("mf.dll", ExactSpelling = true), Obsolete("Interface doesn't exist"), SuppressUnmanagedCodeSecurity] public static extern int MFCreateQualityManager( out IMFQualityManager ppQualityManager ); [DllImport("evr.dll", ExactSpelling = true), Obsolete("Undoc'ed"), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMediaTypeFromVideoInfoHeader( VideoInfoHeader pVideoInfoHeader, int cbVideoInfoHeader, int dwPixelAspectRatioX, int dwPixelAspectRatioY, MFVideoInterlaceMode InterlaceMode, long VideoFlags, [In, MarshalAs(UnmanagedType.LPStruct)] Guid pSubtype, out IMFVideoMediaType ppIVideoMediaType ); [DllImport("evr.dll", ExactSpelling = true), Obsolete("Undoc'ed"), SuppressUnmanagedCodeSecurity] public static extern int MFCreateVideoMediaTypeFromVideoInfoHeader2( VideoInfoHeader2 pVideoInfoHeader, int cbVideoInfoHeader, long AdditionalVideoFlags, [In, MarshalAs(UnmanagedType.LPStruct)] Guid pSubtype, out IMFVideoMediaType ppIVideoMediaType ); #endregion #endif } }
/* * Created by SharpDevelop. * User: JohnR * Date: 4/08/2007 * Time: 7:09 a.m. * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tests.TestSupport { /// <summary> /// An extended <see cref="MemoryStream">memory stream</see> /// that tracks closing and diposing /// </summary> public class MemoryStreamEx : MemoryStream { public MemoryStreamEx() : base() { } public MemoryStreamEx(byte[] buffer) : base(buffer) { } protected override void Dispose(bool disposing) { isDisposed_=true; base.Dispose(disposing); } public override void Close() { isClosed_=true; base.Close(); } public bool IsClosed { get { return isClosed_; } } public bool IsDisposed { get { return isDisposed_; } set { isDisposed_=value; } } #region Instance Fields bool isDisposed_; bool isClosed_; #endregion } /// <summary> /// A stream that cannot seek. /// </summary> public class MemoryStreamWithoutSeek : MemoryStreamEx { public override bool CanSeek { get { return false; } } } public class NullStream : Stream { public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { throw new Exception("The method or operation is not implemented."); } } public override long Position { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } public override int Read(byte[] buffer, int offset, int count) { throw new Exception("The method or operation is not implemented."); } public override long Seek(long offset, SeekOrigin origin) { throw new Exception("The method or operation is not implemented."); } public override void SetLength(long value) { throw new Exception("The method or operation is not implemented."); } public override void Write(byte[] buffer, int offset, int count) { } } public class WindowedStream : Stream { public WindowedStream(int size) { ringBuffer_ = new ReadWriteRingBuffer(size); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override void Flush() { // Do nothing } public override long Length { // A bit of a HAK as its not true in the stream sense. get { return ringBuffer_.Count; } } public override long Position { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } public override int Read(byte[] buffer, int offset, int count) { int bytesRead = 0; while (count > 0) { int value = ringBuffer_.ReadByte(); if (value >= 0) { buffer[offset] = (byte)(value & 0xff); offset++; bytesRead++; count--; } else { break; } } return bytesRead; } public override long Seek(long offset, SeekOrigin origin) { throw new Exception("The method or operation is not implemented."); } public override void SetLength(long value) { throw new Exception("The method or operation is not implemented."); } public override void Write(byte[] buffer, int offset, int count) { for (int i = 0; i < count; ++i) { ringBuffer_.WriteByte(buffer[offset + i]); } } public bool IsClosed { get { return ringBuffer_.IsClosed; } } public override void Close() { ringBuffer_.Close(); } public long BytesWritten { get { return ringBuffer_.BytesWritten; } } public long BytesRead { get { return ringBuffer_.BytesRead; } } #region Instance Fields ReadWriteRingBuffer ringBuffer_; #endregion } }