context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Epi.Fields; using Epi.Collections; namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs { /// <summary> /// Field definition dialog for codes fields /// </summary> public partial class CodesFieldDefinition : LegalValuesFieldDefinition { #region Public Interface #region Constructors /// <summary> /// Default Constsructor for exclusive use by the designer /// </summary> public CodesFieldDefinition() { InitializeComponent(); } /// <summary> /// Constructor for the class /// </summary> /// <param name="frm">The parent form</param> /// <param name="page">The current page</param> public CodesFieldDefinition(MainForm frm, Page page) : base(frm) { InitializeComponent(); this.mode = FormMode.Create; this.page = page; selectedFields = new NamedObjectCollection<Field>(); } /// <summary> /// Constructor for the class /// </summary> /// <param name="frm">The parent form</param> /// <param name="field">The fied to be edited</param> public CodesFieldDefinition(MainForm frm, DDLFieldOfCodes field) : base(frm) { InitializeComponent(); this.mode = FormMode.Edit; this.field = field; this.page = field.Page; selectedFields = new NamedObjectCollection<Field>(); LoadFormData(); } #endregion Constructors #region Public Enums and Constants #endregion Public Enums and Constants #region Public Properties /// <summary> /// Gets the field defined by this field definition dialog /// </summary> public override RenderableField Field { get { return field; } } #endregion Public Properties #region Public Methods /// <summary> /// Sets enabled property of OK and Save Only /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); } #endregion Public Methods #endregion Public Interface #region Protected Interface #region Protected Properties #endregion Protected Properties #region Protected Methods /// <summary> /// Sets the field's properties based on GUI values /// </summary> protected override void SetFieldProperties() { field.PromptText = txtPrompt.Text; field.Name = txtFieldName.Text; if (promptFont != null) { field.PromptFont = promptFont; } if (controlFont != null) { field.ControlFont = controlFont; } field.IsRequired = chkRequired.Checked; field.IsReadOnly = chkReadOnly.Checked; field.ShouldRepeatLast = chkRepeatLast.Checked; if (!string.IsNullOrEmpty(this.sourceTableName) && !string.IsNullOrEmpty(this.textColumnName)) { field.SourceTableName = this.sourceTableName; field.TextColumnName = this.textColumnName; } if (string.IsNullOrEmpty(field.AssociatedFieldInformation)) { StringBuilder sb = new StringBuilder(); string items = lbxLinkedFields.SelectedItems.ToString(); foreach (Field selectedField in selectedFields) { sb.Append(selectedField.Name.ToString() + ":" + selectedField.Id.ToString() + ","); } if (sb.Length > 0) { sb = sb.Remove(sb.Length - 1, 1); } field.AssociatedFieldInformation = sb.ToString(); if (string.IsNullOrEmpty(field.AssociatedFieldInformation)) { field.AssociatedFieldInformation = field.RelateConditionString; } } } #endregion Protected Methods #region Protected Events /// <summary> /// Handles the click event for the "..." data source button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void btnDataSource_Click(object sender, EventArgs e) { if (ValidateToAddDataSource()) { NamedObjectCollection<Field> columnNamesInLower = new NamedObjectCollection<Field>(); int selectedIndex = 1; DataRowView item; string[] selectedFieldNames = new string[lbxLinkedFields.SelectedItems.Count]; for (int i = 0; i < lbxLinkedFields.Items.Count; i++) { item = (DataRowView)lbxLinkedFields.Items[i]; if (lbxLinkedFields.GetSelected(i)) { selectedFieldNames[selectedIndex - 1] = item[lbxLinkedFields.DisplayMember].ToString(); DataRow selectRow = item.Row; string fieldColumnName = (selectRow[ColumnNames.NAME].ToString()); string fieldStringID = (selectRow[ColumnNames.FIELD_ID].ToString()); if (DoesFieldNameExistInCollection(fieldColumnName, selectedFields) == false) { selectedFields.Add(page.GetView().GetFieldById(int.Parse(fieldStringID))); } selectedIndex++; } } CodesDialog codesDialog = new CodesDialog((TableBasedDropDownField)this.Field, this.MainForm, txtFieldName.Text, this.page, selectedFields); DialogResult result = codesDialog.ShowDialog(); if (result == DialogResult.OK) { if (!((string.IsNullOrEmpty(codesDialog.SourceTableName) && string.IsNullOrEmpty(codesDialog.TextColumnName)))) { txtDataSource.Text = codesDialog.SourceTableName + " :: " + codesDialog.TextColumnName; lbxLinkedFields.Enabled = true; lblSelectFields.Enabled = true; txtFieldName.Enabled = false; string dialogRelateCondition = codesDialog.relateCondition; if (string.IsNullOrEmpty(dialogRelateCondition)) { ((DDLFieldOfCodes)field).AssociatedFieldInformation = ((DDLFieldOfCodes)field).RelateConditionString; } else { ((DDLFieldOfCodes)field).AssociatedFieldInformation = dialogRelateCondition; } ((DDLFieldOfCodes)field).ShouldSort = codesDialog.ShouldSort; } else { txtDataSource.Text = string.Empty; field.SourceTableName = string.Empty; field.TextColumnName = string.Empty; lbxLinkedFields.Enabled = true; lbxLinkedFields.Visible = true; lblSelectFields.Enabled = true; lblSelectFields.Visible = true; ((DDLFieldOfCodes)field).AssociatedFieldInformation = string.Empty; } this.sourceTableName = codesDialog.SourceTableName; this.textColumnName = codesDialog.TextColumnName; btnOk.Enabled = true; } } else { ShowErrorMessages(); } } #endregion Protected Events #endregion Protected Interface #region Private Members #region Private Enums and Constants #endregion Private Enums and Constants #region Private Properties private new DDLFieldOfCodes field; private new string sourceTableName; private new string textColumnName; private NamedObjectCollection<Field> selectedFields; private List<string> selectedIndex; private string fieldName = string.Empty; #endregion Private Properties #region Private Methods /// <summary> /// Load the form with the saved data /// </summary> private new void LoadFormData() { SetFontStyles(field); txtPrompt.Text = field.PromptText; txtFieldName.Text = field.Name; if (!string.IsNullOrEmpty(field.SourceTableName)) { this.sourceTableName = field.SourceTableName; this.textColumnName = field.TextColumnName; txtDataSource.Text = field.SourceTableName + " :: " + field.TextColumnName; } chkReadOnly.Checked = field.IsReadOnly; chkRepeatLast.Checked = field.ShouldRepeatLast; chkRequired.Checked = field.IsRequired; if (!(String.IsNullOrEmpty(txtPrompt.Text))) { btnDataSource.Enabled = true; } else { btnDataSource.Enabled = false; } DataTable fields = page.GetMetadata().GetCodeTargetCandidates(page.Id); string expression = string.Format("FieldTypeId = 1 OR FieldTypeId = 2 OR FieldTypeId = 17 OR FieldTypeId = 18"); lbxLinkedFields.DataSource = fields; lbxLinkedFields.DisplayMember = ColumnNames.NAME; lbxLinkedFields.SelectedItem = null; string fieldName = string.Empty; int fieldId; DataRow[] codeFieldRows = fields.Select(string.Format("{0} = '{1}'", ColumnNames.NAME, field.Name)); if (codeFieldRows != null && codeFieldRows.Length > 0 && codeFieldRows[0] != null) { fields.Rows.Remove(codeFieldRows[0]); fields.AcceptChanges(); } for (int i = 0; i < fields.Rows.Count; i++) { fieldId = (int)fields.Rows[i][ColumnNames.FIELD_ID]; fieldName = (string)fields.Rows[i][ColumnNames.NAME]; bool isSelected = field.PairAssociated.ContainsValue(fieldId); lbxLinkedFields.SetSelected(lbxLinkedFields.FindStringExact(fieldName), isSelected); } if (!(string.IsNullOrEmpty(txtDataSource.Text))) { lbxLinkedFields.Enabled = true; lblSelectFields.Enabled = true; lbxLinkedFields.Visible = true; lblSelectFields.Visible = true; btnOk.Enabled = true; } else { btnOk.Enabled = false; } } private bool DoesFieldNameExistInCollection(string fieldname, NamedObjectCollection<Field> collection) { bool matchFound = false; foreach (string name in collection.Names) { if (fieldname.Equals(name)) { matchFound = true; } } return matchFound; } /// <summary> /// Validates user input /// </summary> /// <returns>true if there is no error; else false</returns> protected override bool ValidateInput() { bool isValid = true; // ValidateToAddDataSource(); return (ErrorMessages.Count == 0); } private bool ValidateToAddDataSource() { if (lbxLinkedFields.Items.Count == 0) { ErrorMessages.Add(SharedStrings.WARNING_MUST_CREATE_TEXT_FIRST); return false; } else if (lbxLinkedFields.SelectedItems.Count == 0 && string.IsNullOrEmpty(txtDataSource.Text)) { ErrorMessages.Add(SharedStrings.NO_LINKED_FIELD_SELECTED); return false; } return true; } /// <summary> /// Click event for OK button /// </summary> /// <param name="sender">sender</param> /// <param name="e">e</param> protected override void btnOk_Click(object sender, System.EventArgs e) { ErrorMessages.Clear(); //if (ValidateInput()) && ValidateToAddDataSource()) if (ValidateDialogInput()) { this.SetFieldProperties(); this.DialogResult = DialogResult.OK; this.Hide(); } else { this.ShowErrorMessages(); } } #endregion Private Methods #endregion Private Members } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DirectoryRoleRequest. /// </summary> public partial class DirectoryRoleRequest : BaseRequest, IDirectoryRoleRequest { /// <summary> /// Constructs a new DirectoryRoleRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DirectoryRoleRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified DirectoryRole using POST. /// </summary> /// <param name="directoryRoleToCreate">The DirectoryRole to create.</param> /// <returns>The created DirectoryRole.</returns> public System.Threading.Tasks.Task<DirectoryRole> CreateAsync(DirectoryRole directoryRoleToCreate) { return this.CreateAsync(directoryRoleToCreate, CancellationToken.None); } /// <summary> /// Creates the specified DirectoryRole using POST. /// </summary> /// <param name="directoryRoleToCreate">The DirectoryRole to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DirectoryRole.</returns> public async System.Threading.Tasks.Task<DirectoryRole> CreateAsync(DirectoryRole directoryRoleToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<DirectoryRole>(directoryRoleToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified DirectoryRole. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified DirectoryRole. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<DirectoryRole>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified DirectoryRole. /// </summary> /// <returns>The DirectoryRole.</returns> public System.Threading.Tasks.Task<DirectoryRole> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified DirectoryRole. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DirectoryRole.</returns> public async System.Threading.Tasks.Task<DirectoryRole> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<DirectoryRole>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified DirectoryRole using PATCH. /// </summary> /// <param name="directoryRoleToUpdate">The DirectoryRole to update.</param> /// <returns>The updated DirectoryRole.</returns> public System.Threading.Tasks.Task<DirectoryRole> UpdateAsync(DirectoryRole directoryRoleToUpdate) { return this.UpdateAsync(directoryRoleToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified DirectoryRole using PATCH. /// </summary> /// <param name="directoryRoleToUpdate">The DirectoryRole to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated DirectoryRole.</returns> public async System.Threading.Tasks.Task<DirectoryRole> UpdateAsync(DirectoryRole directoryRoleToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<DirectoryRole>(directoryRoleToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDirectoryRoleRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDirectoryRoleRequest Expand(Expression<Func<DirectoryRole, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDirectoryRoleRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDirectoryRoleRequest Select(Expression<Func<DirectoryRole, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="directoryRoleToInitialize">The <see cref="DirectoryRole"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(DirectoryRole directoryRoleToInitialize) { if (directoryRoleToInitialize != null && directoryRoleToInitialize.AdditionalData != null) { if (directoryRoleToInitialize.Members != null && directoryRoleToInitialize.Members.CurrentPage != null) { directoryRoleToInitialize.Members.AdditionalData = directoryRoleToInitialize.AdditionalData; object nextPageLink; directoryRoleToInitialize.AdditionalData.TryGetValue("members@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { directoryRoleToInitialize.Members.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
#region Copyright // // Nini Configuration Project. // Copyright (C) 2006 Brent R. Matzelle. All rights reserved. // // This software is published under the terms of the MIT X11 license, a copy of // which has been included with this distribution in the LICENSE.txt file. // #endregion using System; using System.IO; using Nini.Config; using NUnit.Framework; namespace Nini.Test.Config { [TestFixture] public class ConfigBaseTests { [Test] public void GetConfig () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine (" cat = muffy"); writer.WriteLine (" dog = rover"); writer.WriteLine (" bird = tweety"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("Pets", config.Name); Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual (source, config.ConfigSource); } [Test] public void GetString () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" cat = muffy"); writer.WriteLine (" dog = rover"); writer.WriteLine (" bird = tweety"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; Assert.AreEqual ("muffy", config.Get ("cat")); Assert.AreEqual ("rover", config.Get ("dog")); Assert.AreEqual ("muffy", config.GetString ("cat")); Assert.AreEqual ("rover", config.GetString ("dog")); Assert.AreEqual ("my default", config.Get ("Not Here", "my default")); Assert.IsNull (config.Get ("Not Here 2")); } [Test] public void GetInt () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" value 1 = 49588"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; Assert.AreEqual (49588, config.GetInt ("value 1")); Assert.AreEqual (12345, config.GetInt ("Not Here", 12345)); try { config.GetInt ("Not Here Also"); Assert.Fail (); } catch { } } [Test] public void GetLong () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" value 1 = 4000000000"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; Assert.AreEqual (4000000000, config.GetLong ("value 1")); Assert.AreEqual (5000000000, config.GetLong ("Not Here", 5000000000)); try { config.GetLong ("Not Here Also"); Assert.Fail (); } catch { } } [Test] public void GetFloat () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" value 1 = 494.59"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; Assert.AreEqual ((float)494.59, config.GetFloat ("value 1")); Assert.AreEqual ((float)5656.2853, config.GetFloat ("Not Here", (float)5656.2853)); } [Test] public void BooleanAlias () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" bool 1 = TrUe"); writer.WriteLine (" bool 2 = FalSe"); writer.WriteLine (" bool 3 = ON"); writer.WriteLine (" bool 4 = OfF"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; config.Alias.AddAlias ("true", true); config.Alias.AddAlias ("false", false); config.Alias.AddAlias ("on", true); config.Alias.AddAlias ("off", false); Assert.IsTrue (config.GetBoolean ("bool 1")); Assert.IsFalse (config.GetBoolean ("bool 2")); Assert.IsTrue (config.GetBoolean ("bool 3")); Assert.IsFalse (config.GetBoolean ("bool 4")); Assert.IsTrue (config.GetBoolean ("Not Here", true)); } [Test] [ExpectedException (typeof (ArgumentException))] public void BooleanAliasNoDefault () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" bool 1 = TrUe"); writer.WriteLine (" bool 2 = FalSe"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; config.Alias.AddAlias ("true", true); config.Alias.AddAlias ("false", false); Assert.IsTrue (config.GetBoolean ("Not Here", true)); Assert.IsFalse (config.GetBoolean ("Not Here Also")); } [Test] [ExpectedException (typeof (ArgumentException))] public void NonBooleanParameter () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" bool 1 = not boolean"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; config.Alias.AddAlias ("true", true); config.Alias.AddAlias ("false", false); Assert.IsTrue (config.GetBoolean ("bool 1")); } [Test] public void GetIntAlias () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" node type = TEXT"); writer.WriteLine (" error code = WARN"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); const int WARN = 100, ERROR = 200; IConfig config = source.Configs["Test"]; config.Alias.AddAlias ("error code", "waRn", WARN); config.Alias.AddAlias ("error code", "eRRor", ERROR); config.Alias.AddAlias ("node type", new System.Xml.XmlNodeType ()); config.Alias.AddAlias ("default", "age", 31); Assert.AreEqual (WARN, config.GetInt ("error code", true)); Assert.AreEqual ((int)System.Xml.XmlNodeType.Text, config.GetInt ("node type", true)); Assert.AreEqual (31, config.GetInt ("default", 31, true)); } [Test] public void GetKeys () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" bool 1 = TrUe"); writer.WriteLine (" bool 2 = FalSe"); writer.WriteLine (" bool 3 = ON"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("bool 1", config.GetKeys ()[0]); Assert.AreEqual ("bool 2", config.GetKeys ()[1]); Assert.AreEqual ("bool 3", config.GetKeys ()[2]); } [Test] public void GetValues () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" key 1 = value 1"); writer.WriteLine (" key 2 = value 2"); writer.WriteLine (" key 3 = value 3"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Test"]; Assert.AreEqual (3, config.GetValues ().Length); Assert.AreEqual ("value 1", config.GetValues ()[0]); Assert.AreEqual ("value 2", config.GetValues ()[1]); Assert.AreEqual ("value 3", config.GetValues ()[2]); } [Test] public void SetAndRemove () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine (" cat = muffy"); writer.WriteLine (" dog = rover"); writer.WriteLine (" bird = tweety"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("Pets", config.Name); Assert.AreEqual (3, config.GetKeys ().Length); config.Set ("snake", "cobra"); Assert.AreEqual (4, config.GetKeys ().Length); // Test removing Assert.IsNotNull (config.Get ("dog")); config.Remove ("dog"); Assert.AreEqual (3, config.GetKeys ().Length); Assert.IsNull (config.Get ("dog")); Assert.IsNotNull (config.Get ("snake")); } [Test] public void Rename () { IniConfigSource source = new IniConfigSource (); IConfig config = source.AddConfig ("Pets"); config.Set ("cat", "Muffy"); config.Set ("dog", "Rover"); config.Name = "MyPets"; Assert.AreEqual ("MyPets", config.Name); Assert.IsNull (source.Configs["Pets"]); IConfig newConfig = source.Configs["MyPets"]; Assert.AreEqual (config, newConfig); Assert.AreEqual (2, newConfig.GetKeys ().Length); } [Test] public void Contains () { IniConfigSource source = new IniConfigSource (); IConfig config = source.AddConfig ("Pets"); config.Set ("cat", "Muffy"); config.Set ("dog", "Rover"); Assert.IsTrue (config.Contains ("cat")); Assert.IsTrue (config.Contains ("dog")); config.Remove ("cat"); Assert.IsFalse (config.Contains ("cat")); Assert.IsTrue (config.Contains ("dog")); } [Test] public void ExpandString () { StringWriter writer = new StringWriter (); writer.WriteLine ("[web]"); writer.WriteLine (" apache = Apache implements ${protocol}"); writer.WriteLine (" protocol = http"); writer.WriteLine ("[server]"); writer.WriteLine (" domain = ${web|protocol}://nini.sf.net/"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["web"]; Assert.AreEqual ("http", config.Get ("protocol")); Assert.AreEqual ("Apache implements ${protocol}", config.Get ("apache")); Assert.AreEqual ("Apache implements http", config.GetExpanded ("apache")); Assert.AreEqual ("Apache implements ${protocol}", config.Get ("apache")); config = source.Configs["server"]; Assert.AreEqual ("http://nini.sf.net/", config.GetExpanded ("domain")); Assert.AreEqual ("${web|protocol}://nini.sf.net/", config.Get ("domain")); } [Test] public void ExpandWithEndBracket () { StringWriter writer = new StringWriter (); writer.WriteLine ("[web]"); writer.WriteLine (" apache = } Apache implements ${protocol}"); writer.WriteLine (" protocol = http"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["web"]; Assert.AreEqual ("} Apache implements http", config.GetExpanded ("apache")); } [Test] public void ExpandBackToBack () { StringWriter writer = new StringWriter (); writer.WriteLine ("[web]"); writer.WriteLine (" apache = Protocol: ${protocol}${version}"); writer.WriteLine (" protocol = http"); writer.WriteLine (" version = 1.1"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["web"]; Assert.AreEqual ("Protocol: http1.1", config.GetExpanded ("apache")); } } }
using System; using System.IO; using System.Reactive; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using Common.Logging; using NuGet.Lucene.Util; namespace NuGet.Lucene { public class PackageFileSystemWatcher : IDisposable { private FileSystemWatcher fileWatcher; private IDisposable fileObserver; private IDisposable dirObserver; public ILog Log { get; set; } public IFileSystem FileSystem { get; set; } public ILucenePackageRepository PackageRepository { get; set; } public IPackageIndexer Indexer { get; set; } /// <summary> /// Sets the amount of time to wait after receiving a <c cref="FileSystemWatcher.Changed">Changed</c> /// event before attempting to index a package. This timeout is meant to avoid trying to read a package /// while it is still being built or copied into place. /// </summary> public TimeSpan QuietTime { get; set; } public PackageFileSystemWatcher() { Log = LogManager.GetLogger<PackageFileSystemWatcher>(); QuietTime = TimeSpan.FromSeconds(3); } public void Initialize() { fileWatcher = new FileSystemWatcher(FileSystem.Root, "*.nupkg") { NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite, IncludeSubdirectories = true }; var modifiedFilesThrottledByPath = ModifiedFiles .Select(args => args.EventArgs.FullPath) .GroupBy(path => path) .Select(groupByPath => groupByPath.Throttle(QuietTime)) .SelectMany(obs => obs); fileObserver = modifiedFilesThrottledByPath.Subscribe(async path => await OnPackageModified(path)); fileWatcher.Deleted += async (s, e) => await OnPackageDeleted(e.FullPath); fileWatcher.Renamed += async (s, e) => await OnPackageRenamed(e.OldFullPath, e.FullPath); fileWatcher.Error += OnFileWatcherError; fileWatcher.EnableRaisingEvents = true; dirObserver = MovedDirectories.Select(args => args.EventArgs.FullPath).Throttle(QuietTime).Subscribe(OnDirectoryMoved); } public void Dispose() { fileObserver.Dispose(); fileWatcher.Dispose(); dirObserver.Dispose(); } public void OnDirectoryMoved(string fullPath) { try { if (FileSystem.GetFiles(fullPath, "*.nupkg", true).IsEmpty()) return; } catch (IOException ex) { Log.Error(ex); return; } Indexer.SynchronizeIndexWithFileSystemAsync(SynchronizationMode.Incremental, CancellationToken.None); } public async Task OnPackageModified(string fullPath) { Log.Info(m => m("Indexing modified package " + fullPath)); await AddToIndex(fullPath).ContinueWith(LogOnFault); } public async Task OnPackageRenamed(string oldFullPath, string fullPath) { Log.Info(m => m("Package path {0} renamed to {1}.", oldFullPath, fullPath)); var task = RemoveFromIndex(oldFullPath).ContinueWith(LogOnFault); if (fullPath.EndsWith(Constants.PackageExtension)) { var addToIndex = AddToIndex(fullPath).ContinueWith(LogOnFault); await Task.WhenAll(addToIndex, task); return; } await task; } public async Task OnPackageDeleted(string fullPath) { Log.Info(m => m("Package path {0} deleted.", fullPath)); await RemoveFromIndex(fullPath).ContinueWith(LogOnFault); } private async Task AddToIndex(string fullPath) { if (FileSystem.IsTempFile(fullPath)) return; var existingPackage = PackageRepository.LoadFromIndex(fullPath); if (existingPackage != null && !IndexDifferenceCalculator.TimestampsMismatch( existingPackage, FileSystem.GetLastModified(fullPath))) { return; } var package = PackageRepository.LoadFromFileSystem(fullPath); await Indexer.AddPackageAsync(package, CancellationToken.None); } private async Task RemoveFromIndex(string fullPath) { if (FileSystem.IsTempFile(fullPath)) return; var package = PackageRepository.LoadFromIndex(fullPath); if (package != null) { await Indexer.RemovePackageAsync(package, CancellationToken.None); } } private void LogOnFault(Task task) { if (task.IsFaulted && task.Exception != null) { task.Exception.Handle(ex => { Log.Error(ex); return true; }); } } private void OnFileWatcherError(object source, ErrorEventArgs e) { if (e.GetException() is InternalBufferOverflowException) { Log.Warn(m => m("InternalBufferOverflowException in FileSystemWatcher; forcing full synchronization.")); Indexer.SynchronizeIndexWithFileSystemAsync(SynchronizationMode.Incremental, CancellationToken.None); } else { Log.Error(m => m("Unhandled error in FileSystemWatcher"), e.GetException()); } } private IObservable<EventPattern<FileSystemEventArgs>> ModifiedFiles { get { var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( eh => eh.Invoke, eh => fileWatcher.Created += eh, eh => fileWatcher.Created -= eh); var changed = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( eh => eh.Invoke, eh => fileWatcher.Changed += eh, eh => fileWatcher.Changed -= eh); return created.Merge(changed); } } private IObservable<EventPattern<FileSystemEventArgs>> MovedDirectories { get { Func<FileSystemWatcher> createDirWatcher = () => { var dirWatcher = new FileSystemWatcher(FileSystem.Root) { NotifyFilter = NotifyFilters.DirectoryName, IncludeSubdirectories = true, EnableRaisingEvents = true, }; dirWatcher.Error += OnFileWatcherError; return dirWatcher; }; Func<FileSystemWatcher, IObservable<EventPattern<FileSystemEventArgs>>> createObservable = dirWatcher => { var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>( eh => eh.Invoke, eh => dirWatcher.Created += eh, eh => dirWatcher.Created -= eh); var renamed = Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>( eh => eh.Invoke, eh => dirWatcher.Renamed += eh, eh => dirWatcher.Renamed -= eh); return created.Merge(renamed.Select(re => new EventPattern<FileSystemEventArgs>(re.Sender, re.EventArgs))); }; return Observable.Using(createDirWatcher, createObservable); } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// The metrics associated with a virtual block device /// First published in XenServer 4.0. /// </summary> public partial class VBD_metrics : XenObject<VBD_metrics> { public VBD_metrics() { } public VBD_metrics(string uuid, double io_read_kbs, double io_write_kbs, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.io_read_kbs = io_read_kbs; this.io_write_kbs = io_write_kbs; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new VBD_metrics from a Proxy_VBD_metrics. /// </summary> /// <param name="proxy"></param> public VBD_metrics(Proxy_VBD_metrics proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(VBD_metrics update) { uuid = update.uuid; io_read_kbs = update.io_read_kbs; io_write_kbs = update.io_write_kbs; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_VBD_metrics proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; io_read_kbs = Convert.ToDouble(proxy.io_read_kbs); io_write_kbs = Convert.ToDouble(proxy.io_write_kbs); last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_VBD_metrics ToProxy() { Proxy_VBD_metrics result_ = new Proxy_VBD_metrics(); result_.uuid = uuid ?? ""; result_.io_read_kbs = io_read_kbs; result_.io_write_kbs = io_write_kbs; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new VBD_metrics from a Hashtable. /// </summary> /// <param name="table"></param> public VBD_metrics(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); io_read_kbs = Marshalling.ParseDouble(table, "io_read_kbs"); io_write_kbs = Marshalling.ParseDouble(table, "io_write_kbs"); last_updated = Marshalling.ParseDateTime(table, "last_updated"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VBD_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, VBD_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VBD_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static VBD_metrics get_record(Session session, string _vbd_metrics) { return new VBD_metrics((Proxy_VBD_metrics)session.proxy.vbd_metrics_get_record(session.uuid, _vbd_metrics ?? "").parse()); } /// <summary> /// Get a reference to the VBD_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VBD_metrics> get_by_uuid(Session session, string _uuid) { return XenRef<VBD_metrics>.Create(session.proxy.vbd_metrics_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static string get_uuid(Session session, string _vbd_metrics) { return (string)session.proxy.vbd_metrics_get_uuid(session.uuid, _vbd_metrics ?? "").parse(); } /// <summary> /// Get the io/read_kbs field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static double get_io_read_kbs(Session session, string _vbd_metrics) { return Convert.ToDouble(session.proxy.vbd_metrics_get_io_read_kbs(session.uuid, _vbd_metrics ?? "").parse()); } /// <summary> /// Get the io/write_kbs field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static double get_io_write_kbs(Session session, string _vbd_metrics) { return Convert.ToDouble(session.proxy.vbd_metrics_get_io_write_kbs(session.uuid, _vbd_metrics ?? "").parse()); } /// <summary> /// Get the last_updated field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static DateTime get_last_updated(Session session, string _vbd_metrics) { return session.proxy.vbd_metrics_get_last_updated(session.uuid, _vbd_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given VBD_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _vbd_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vbd_metrics_get_other_config(session.uuid, _vbd_metrics ?? "").parse()); } /// <summary> /// Set the other_config field of the given VBD_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vbd_metrics, Dictionary<string, string> _other_config) { session.proxy.vbd_metrics_set_other_config(session.uuid, _vbd_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VBD_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vbd_metrics, string _key, string _value) { session.proxy.vbd_metrics_add_to_other_config(session.uuid, _vbd_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VBD_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vbd_metrics, string _key) { session.proxy.vbd_metrics_remove_from_other_config(session.uuid, _vbd_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the VBD_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VBD_metrics>> get_all(Session session) { return XenRef<VBD_metrics>.Create(session.proxy.vbd_metrics_get_all(session.uuid).parse()); } /// <summary> /// Get all the VBD_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VBD_metrics>, VBD_metrics> get_all_records(Session session) { return XenRef<VBD_metrics>.Create<Proxy_VBD_metrics>(session.proxy.vbd_metrics_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// Read bandwidth (KiB/s) /// </summary> public virtual double io_read_kbs { get { return _io_read_kbs; } set { if (!Helper.AreEqual(value, _io_read_kbs)) { _io_read_kbs = value; Changed = true; NotifyPropertyChanged("io_read_kbs"); } } } private double _io_read_kbs; /// <summary> /// Write bandwidth (KiB/s) /// </summary> public virtual double io_write_kbs { get { return _io_write_kbs; } set { if (!Helper.AreEqual(value, _io_write_kbs)) { _io_write_kbs = value; Changed = true; NotifyPropertyChanged("io_write_kbs"); } } } private double _io_write_kbs; /// <summary> /// Time at which this information was last updated /// </summary> public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
// ReSharper disable All using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.Config.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.Config.Api.Tests { public class CustomFieldTests { public static CustomFieldController Fixture() { CustomFieldController controller = new CustomFieldController(new CustomFieldRepository(), "", new LoginView()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.Config.Entities.CustomField customField = Fixture().Get(0); Assert.NotNull(customField); } [Fact] [Conditional("Debug")] public void First() { Frapid.Config.Entities.CustomField customField = Fixture().GetFirst(); Assert.NotNull(customField); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.Config.Entities.CustomField customField = Fixture().GetPrevious(0); Assert.NotNull(customField); } [Fact] [Conditional("Debug")] public void Next() { Frapid.Config.Entities.CustomField customField = Fixture().GetNext(0); Assert.NotNull(customField); } [Fact] [Conditional("Debug")] public void Last() { Frapid.Config.Entities.CustomField customField = Fixture().GetLast(); Assert.NotNull(customField); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.Config.Entities.CustomField> customFields = Fixture().Get(new long[] { }); Assert.NotNull(customFields); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(0, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(0); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using System; using System.IO; using System.Text; using System.Xml; using System.Diagnostics; using System.Collections; using System.Globalization; using System.Collections.Generic; // OpenIssue : is it better to cache the current namespace decls for each elem // as the current code does, or should it just always walk the namespace stack? namespace System.Xml { internal partial class XmlWellFormedWriter : XmlWriter { public override Task WriteStartDocumentAsync() { return WriteStartDocumentImplAsync(XmlStandalone.Omit); } public override Task WriteStartDocumentAsync(bool standalone) { return WriteStartDocumentImplAsync(standalone ? XmlStandalone.Yes : XmlStandalone.No); } public override async Task WriteEndDocumentAsync() { try { // auto-close all elements while (_elemTop > 0) { await WriteEndElementAsync().ConfigureAwait(false); } State prevState = _currentState; await AdvanceStateAsync(Token.EndDocument).ConfigureAwait(false); if (prevState != State.AfterRootEle) { throw new ArgumentException(SR.Xml_NoRoot); } if (_rawWriter == null) { await _writer.WriteEndDocumentAsync().ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { try { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } XmlConvert.VerifyQName(name, ExceptionType.XmlException); if (_conformanceLevel == ConformanceLevel.Fragment) { throw new InvalidOperationException(SR.Xml_DtdNotAllowedInFragment); } await AdvanceStateAsync(Token.Dtd).ConfigureAwait(false); if (_dtdWritten) { _currentState = State.Error; throw new InvalidOperationException(SR.Xml_DtdAlreadyWritten); } if (_conformanceLevel == ConformanceLevel.Auto) { _conformanceLevel = ConformanceLevel.Document; _stateTable = s_stateTableDocument; } int i; // check characters if (_checkCharacters) { if (pubid != null) { if ((i = _xmlCharType.IsPublicId(pubid)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(pubid, i)), nameof(pubid)); } } if (sysid != null) { if ((i = _xmlCharType.IsOnlyCharData(sysid)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(sysid, i)), nameof(sysid)); } } if (subset != null) { if ((i = _xmlCharType.IsOnlyCharData(subset)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(subset, i)), nameof(subset)); } } } // write doctype await _writer.WriteDocTypeAsync(name, pubid, sysid, subset).ConfigureAwait(false); _dtdWritten = true; } catch { _currentState = State.Error; throw; } } //check if any exception before return the task private Task TryReturnTask(Task task) { if (task.IsSuccess()) { return Task.CompletedTask; } else { return _TryReturnTask(task); } } private async Task _TryReturnTask(Task task) { try { await task.ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } //call nextTaskFun after task finish. Check exception. private Task SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg) { if (task.IsSuccess()) { return TryReturnTask(nextTaskFun(arg)); } else { return _SequenceRun(task, nextTaskFun, arg); } } private async Task _SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg) { try { await task.ConfigureAwait(false); await nextTaskFun(arg).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override Task WriteStartElementAsync(string prefix, string localName, string ns) { try { // check local name if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } CheckNCName(localName); Task task = AdvanceStateAsync(Token.StartElement); if (task.IsSuccess()) { return WriteStartElementAsync_NoAdvanceState(prefix, localName, ns); } else { return WriteStartElementAsync_NoAdvanceState(task, prefix, localName, ns); } } catch { _currentState = State.Error; throw; } } private Task WriteStartElementAsync_NoAdvanceState(string prefix, string localName, string ns) { try { // lookup prefix / namespace if (prefix == null) { if (ns != null) { prefix = LookupPrefix(ns); } if (prefix == null) { prefix = string.Empty; } } else if (prefix.Length > 0) { CheckNCName(prefix); if (ns == null) { ns = LookupNamespace(prefix); } if (ns == null || (ns != null && ns.Length == 0)) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } } if (ns == null) { ns = LookupNamespace(prefix); if (ns == null) { Debug.Assert(prefix.Length == 0); ns = string.Empty; } } if (_elemTop == 0 && _rawWriter != null) { // notify the underlying raw writer about the root level element _rawWriter.OnRootElement(_conformanceLevel); } // write start tag Task task = _writer.WriteStartElementAsync(prefix, localName, ns); if (task.IsSuccess()) { WriteStartElementAsync_FinishWrite(prefix, localName, ns); } else { return WriteStartElementAsync_FinishWrite(task, prefix, localName, ns); } return Task.CompletedTask; } catch { _currentState = State.Error; throw; } } private async Task WriteStartElementAsync_NoAdvanceState(Task task, string prefix, string localName, string ns) { try { await task.ConfigureAwait(false); await WriteStartElementAsync_NoAdvanceState(prefix, localName, ns).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } private void WriteStartElementAsync_FinishWrite(string prefix, string localName, string ns) { try { // push element on stack and add/check namespace int top = ++_elemTop; if (top == _elemScopeStack.Length) { ElementScope[] newStack = new ElementScope[top * 2]; Array.Copy(_elemScopeStack, 0, newStack, 0, top); _elemScopeStack = newStack; } _elemScopeStack[top].Set(prefix, localName, ns, _nsTop); PushNamespaceImplicit(prefix, ns); if (_attrCount >= MaxAttrDuplWalkCount) { _attrHashTable.Clear(); } _attrCount = 0; } catch { _currentState = State.Error; throw; } } private async Task WriteStartElementAsync_FinishWrite(Task t, string prefix, string localName, string ns) { try { await t.ConfigureAwait(false); WriteStartElementAsync_FinishWrite(prefix, localName, ns); } catch { _currentState = State.Error; throw; } } public override Task WriteEndElementAsync() { try { Task task = AdvanceStateAsync(Token.EndElement); return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_NoAdvanceState(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndElementAsync_NoAdvanceState() { try { int top = _elemTop; if (top == 0) { throw new XmlException(SR.Xml_NoStartTag, string.Empty); } Task task; // write end tag if (_rawWriter != null) { task = _elemScopeStack[top].WriteEndElementAsync(_rawWriter); } else { task = _writer.WriteEndElementAsync(); } return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndElementAsync_FinishWrite() { try { int top = _elemTop; // pop namespaces int prevNsTop = _elemScopeStack[top].prevNSTop; if (_useNsHashtable && prevNsTop < _nsTop) { PopNamespaces(prevNsTop + 1, _nsTop); } _nsTop = prevNsTop; _elemTop = --top; // check "one root element" condition for ConformanceLevel.Document if (top == 0) { if (_conformanceLevel == ConformanceLevel.Document) { _currentState = State.AfterRootEle; } else { _currentState = State.TopLevel; } } } catch { _currentState = State.Error; throw; } return Task.CompletedTask; } public override Task WriteFullEndElementAsync() { try { Task task = AdvanceStateAsync(Token.EndElement); return SequenceRun(task, thisRef => thisRef.WriteFullEndElementAsync_NoAdvanceState(), this); } catch { _currentState = State.Error; throw; } } private Task WriteFullEndElementAsync_NoAdvanceState() { try { int top = _elemTop; if (top == 0) { throw new XmlException(SR.Xml_NoStartTag, string.Empty); } Task task; // write end tag if (_rawWriter != null) { task = _elemScopeStack[top].WriteFullEndElementAsync(_rawWriter); } else { task = _writer.WriteFullEndElementAsync(); } return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this); } catch { _currentState = State.Error; throw; } } protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string namespaceName) { try { // check local name if (localName == null || localName.Length == 0) { if (prefix == "xmlns") { localName = "xmlns"; prefix = string.Empty; } else { throw new ArgumentException(SR.Xml_EmptyLocalName); } } CheckNCName(localName); Task task = AdvanceStateAsync(Token.StartAttribute); if (task.IsSuccess()) { return WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName); } else { return WriteStartAttributeAsync_NoAdvanceState(task, prefix, localName, namespaceName); } } catch { _currentState = State.Error; throw; } } private Task WriteStartAttributeAsync_NoAdvanceState(string prefix, string localName, string namespaceName) { try { // lookup prefix / namespace if (prefix == null) { if (namespaceName != null) { // special case prefix=null/localname=xmlns if (!(localName == "xmlns" && namespaceName == XmlReservedNs.NsXmlNs)) prefix = LookupPrefix(namespaceName); } if (prefix == null) { prefix = string.Empty; } } if (namespaceName == null) { if (prefix != null && prefix.Length > 0) { namespaceName = LookupNamespace(prefix); } if (namespaceName == null) { namespaceName = string.Empty; } } if (prefix.Length == 0) { if (localName[0] == 'x' && localName == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(SR.Xml_XmlnsPrefix); } _curDeclPrefix = String.Empty; SetSpecialAttribute(SpecialAttribute.DefaultXmlns); goto SkipPushAndWrite; } else if (namespaceName.Length > 0) { prefix = LookupPrefix(namespaceName); if (prefix == null || prefix.Length == 0) { prefix = GeneratePrefix(); } } } else { if (prefix[0] == 'x') { if (prefix == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(SR.Xml_XmlnsPrefix); } _curDeclPrefix = localName; SetSpecialAttribute(SpecialAttribute.PrefixedXmlns); goto SkipPushAndWrite; } else if (prefix == "xml") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXml) { throw new ArgumentException(SR.Xml_XmlPrefix); } switch (localName) { case "space": SetSpecialAttribute(SpecialAttribute.XmlSpace); goto SkipPushAndWrite; case "lang": SetSpecialAttribute(SpecialAttribute.XmlLang); goto SkipPushAndWrite; } } } CheckNCName(prefix); if (namespaceName.Length == 0) { // attributes cannot have default namespace prefix = string.Empty; } else { string definedNs = LookupLocalNamespace(prefix); if (definedNs != null && definedNs != namespaceName) { prefix = GeneratePrefix(); } } } if (prefix.Length != 0) { PushNamespaceImplicit(prefix, namespaceName); } SkipPushAndWrite: // add attribute to the list and check for duplicates AddAttribute(prefix, localName, namespaceName); if (_specAttr == SpecialAttribute.No) { // write attribute name return TryReturnTask(_writer.WriteStartAttributeAsync(prefix, localName, namespaceName)); } return Task.CompletedTask; } catch { _currentState = State.Error; throw; } } private async Task WriteStartAttributeAsync_NoAdvanceState(Task task, string prefix, string localName, string namespaceName) { try { await task.ConfigureAwait(false); await WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } protected internal override Task WriteEndAttributeAsync() { try { Task task = AdvanceStateAsync(Token.EndAttribute); return SequenceRun(task, thisRef => thisRef.WriteEndAttributeAsync_NoAdvance(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndAttributeAsync_NoAdvance() { try { if (_specAttr != SpecialAttribute.No) { return WriteEndAttributeAsync_SepcialAtt(); } else { return TryReturnTask(_writer.WriteEndAttributeAsync()); } } catch { _currentState = State.Error; throw; } } private async Task WriteEndAttributeAsync_SepcialAtt() { try { string value; switch (_specAttr) { case SpecialAttribute.DefaultXmlns: value = _attrValueCache.StringValue; if (PushNamespaceExplicit(string.Empty, value)) { // returns true if the namespace declaration should be written out if (_rawWriter != null) { if (_rawWriter.SupportsNamespaceDeclarationInChunks) { await _rawWriter.WriteStartNamespaceDeclarationAsync(string.Empty).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false); await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await _rawWriter.WriteNamespaceDeclarationAsync(string.Empty, value).ConfigureAwait(false); } } else { await _writer.WriteStartAttributeAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); } } _curDeclPrefix = null; break; case SpecialAttribute.PrefixedXmlns: value = _attrValueCache.StringValue; if (value.Length == 0) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } if (value == XmlReservedNs.NsXmlNs || (value == XmlReservedNs.NsXml && _curDeclPrefix != "xml")) { throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace); } if (PushNamespaceExplicit(_curDeclPrefix, value)) { // returns true if the namespace declaration should be written out if (_rawWriter != null) { if (_rawWriter.SupportsNamespaceDeclarationInChunks) { await _rawWriter.WriteStartNamespaceDeclarationAsync(_curDeclPrefix).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false); await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await _rawWriter.WriteNamespaceDeclarationAsync(_curDeclPrefix, value).ConfigureAwait(false); } } else { await _writer.WriteStartAttributeAsync("xmlns", _curDeclPrefix, XmlReservedNs.NsXmlNs).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); } } _curDeclPrefix = null; break; case SpecialAttribute.XmlSpace: _attrValueCache.Trim(); value = _attrValueCache.StringValue; if (value == "default") { _elemScopeStack[_elemTop].xmlSpace = XmlSpace.Default; } else if (value == "preserve") { _elemScopeStack[_elemTop].xmlSpace = XmlSpace.Preserve; } else { throw new ArgumentException(SR.Xml_InvalidXmlSpace, value); } await _writer.WriteStartAttributeAsync("xml", "space", XmlReservedNs.NsXml).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); break; case SpecialAttribute.XmlLang: value = _attrValueCache.StringValue; _elemScopeStack[_elemTop].xmlLang = value; await _writer.WriteStartAttributeAsync("xml", "lang", XmlReservedNs.NsXml).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); break; } _specAttr = SpecialAttribute.No; _attrValueCache.Clear(); } catch { _currentState = State.Error; throw; } } public override async Task WriteCDataAsync(string text) { try { if (text == null) { text = string.Empty; } await AdvanceStateAsync(Token.CData).ConfigureAwait(false); await _writer.WriteCDataAsync(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteCommentAsync(string text) { try { if (text == null) { text = string.Empty; } await AdvanceStateAsync(Token.Comment).ConfigureAwait(false); await _writer.WriteCommentAsync(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteProcessingInstructionAsync(string name, string text) { try { // check name if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } CheckNCName(name); // check text if (text == null) { text = string.Empty; } // xml declaration is a special case (not a processing instruction, but we allow WriteProcessingInstruction as a convenience) if (name.Length == 3 && string.Equals(name, "xml", StringComparison.OrdinalIgnoreCase)) { if (_currentState != State.Start) { throw new ArgumentException(_conformanceLevel == ConformanceLevel.Document ? SR.Xml_DupXmlDecl : SR.Xml_CannotWriteXmlDecl); } _xmlDeclFollows = true; await AdvanceStateAsync(Token.PI).ConfigureAwait(false); if (_rawWriter != null) { // Translate PI into an xml declaration await _rawWriter.WriteXmlDeclarationAsync(text).ConfigureAwait(false); } else { await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false); } } else { await AdvanceStateAsync(Token.PI).ConfigureAwait(false); await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteEntityRefAsync(string name) { try { // check name if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } CheckNCName(name); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteEntityRef(name); } else { await _writer.WriteEntityRefAsync(name).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteCharEntityAsync(char ch) { try { if (Char.IsSurrogate(ch)) { throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteCharEntity(ch); } else { await _writer.WriteCharEntityAsync(ch).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { try { if (!Char.IsSurrogatePair(highChar, lowChar)) { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteSurrogateCharEntity(lowChar, highChar); } else { await _writer.WriteSurrogateCharEntityAsync(lowChar, highChar).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteWhitespaceAsync(string ws) { try { if (ws == null) { ws = string.Empty; } if (!XmlCharType.Instance.IsOnlyWhitespace(ws)) { throw new ArgumentException(SR.Xml_NonWhitespace); } await AdvanceStateAsync(Token.Whitespace).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteWhitespace(ws); } else { await _writer.WriteWhitespaceAsync(ws).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override Task WriteStringAsync(string text) { try { if (text == null) { return Task.CompletedTask; } Task task = AdvanceStateAsync(Token.Text); if (task.IsSuccess()) { return WriteStringAsync_NoAdvanceState(text); } else { return WriteStringAsync_NoAdvanceState(task, text); } } catch { _currentState = State.Error; throw; } } private Task WriteStringAsync_NoAdvanceState(string text) { try { if (SaveAttrValue) { _attrValueCache.WriteString(text); return Task.CompletedTask; } else { return TryReturnTask(_writer.WriteStringAsync(text)); } } catch { _currentState = State.Error; throw; } } private async Task WriteStringAsync_NoAdvanceState(Task task, string text) { try { await task.ConfigureAwait(false); await WriteStringAsync_NoAdvanceState(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteCharsAsync(char[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteChars(buffer, index, count); } else { await _writer.WriteCharsAsync(buffer, index, count).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteRawAsync(char[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } await AdvanceStateAsync(Token.RawData).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteRaw(buffer, index, count); } else { await _writer.WriteRawAsync(buffer, index, count).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteRawAsync(string data) { try { if (data == null) { return; } await AdvanceStateAsync(Token.RawData).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteRaw(data); } else { await _writer.WriteRawAsync(data).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override Task WriteBase64Async(byte[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } Task task = AdvanceStateAsync(Token.Base64); if (task.IsSuccess()) { return TryReturnTask(_writer.WriteBase64Async(buffer, index, count)); } else { return WriteBase64Async_NoAdvanceState(task, buffer, index, count); } } catch { _currentState = State.Error; throw; } } private async Task WriteBase64Async_NoAdvanceState(Task task, byte[] buffer, int index, int count) { try { await task.ConfigureAwait(false); await _writer.WriteBase64Async(buffer, index, count).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task FlushAsync() { try { await _writer.FlushAsync().ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteQualifiedNameAsync(string localName, string ns) { try { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } CheckNCName(localName); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); string prefix = String.Empty; if (ns != null && ns.Length != 0) { prefix = LookupPrefix(ns); if (prefix == null) { if (_currentState != State.Attribute) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } prefix = GeneratePrefix(); PushNamespaceImplicit(prefix, ns); } } // if this is a special attribute, then just convert this to text // otherwise delegate to raw-writer if (SaveAttrValue || _rawWriter == null) { if (prefix.Length != 0) { await WriteStringAsync(prefix).ConfigureAwait(false); await WriteStringAsync(":").ConfigureAwait(false); } await WriteStringAsync(localName).ConfigureAwait(false); } else { await _rawWriter.WriteQualifiedNameAsync(prefix, localName, ns).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteBinHexAsync(byte[] buffer, int index, int count) { if (IsClosedOrErrorState) { throw new InvalidOperationException(SR.Xml_ClosedOrError); } try { await AdvanceStateAsync(Token.Text).ConfigureAwait(false); await base.WriteBinHexAsync(buffer, index, count).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } private async Task WriteStartDocumentImplAsync(XmlStandalone standalone) { try { await AdvanceStateAsync(Token.StartDocument).ConfigureAwait(false); if (_conformanceLevel == ConformanceLevel.Auto) { _conformanceLevel = ConformanceLevel.Document; _stateTable = s_stateTableDocument; } else if (_conformanceLevel == ConformanceLevel.Fragment) { throw new InvalidOperationException(SR.Xml_CannotStartDocumentOnFragment); } if (_rawWriter != null) { if (!_xmlDeclFollows) { await _rawWriter.WriteXmlDeclarationAsync(standalone).ConfigureAwait(false); } } else { // We do not pass the standalone value here await _writer.WriteStartDocumentAsync().ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } //call taskFun and change state in sequence private Task AdvanceStateAsync_ReturnWhenFinish(Task task, State newState) { if (task.IsSuccess()) { _currentState = newState; return Task.CompletedTask; } else { return _AdvanceStateAsync_ReturnWhenFinish(task, newState); } } private async Task _AdvanceStateAsync_ReturnWhenFinish(Task task, State newState) { await task.ConfigureAwait(false); _currentState = newState; } private Task AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token) { if (task.IsSuccess()) { _currentState = newState; return AdvanceStateAsync(token); } else { return _AdvanceStateAsync_ContinueWhenFinish(task, newState, token); } } private async Task _AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token) { await task.ConfigureAwait(false); _currentState = newState; await AdvanceStateAsync(token).ConfigureAwait(false); } // Advance the state machine private Task AdvanceStateAsync(Token token) { if ((int)_currentState >= (int)State.Closed) { if (_currentState == State.Closed || _currentState == State.Error) { throw new InvalidOperationException(SR.Xml_ClosedOrError); } else { throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], GetStateName(_currentState))); } } Advance: State newState = _stateTable[((int)token << 4) + (int)_currentState]; // [ (int)token * 16 + (int)currentState ]; Task task; if ((int)newState >= (int)State.Error) { switch (newState) { case State.Error: ThrowInvalidStateTransition(token, _currentState); break; case State.StartContent: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Content); case State.StartContentEle: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Element); case State.StartContentB64: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.B64Content); case State.StartDoc: return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Document); case State.StartDocEle: return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Element); case State.EndAttrSEle: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Element); case State.EndAttrEEle: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Content); case State.EndAttrSCont: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Content); case State.EndAttrSAttr: return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.Attribute); case State.PostB64Cont: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Content, token); } _currentState = State.Content; goto Advance; case State.PostB64Attr: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Attribute, token); } _currentState = State.Attribute; goto Advance; case State.PostB64RootAttr: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.RootLevelAttr, token); } _currentState = State.RootLevelAttr; goto Advance; case State.StartFragEle: StartFragment(); newState = State.Element; break; case State.StartFragCont: StartFragment(); newState = State.Content; break; case State.StartFragB64: StartFragment(); newState = State.B64Content; break; case State.StartRootLevelAttr: return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.RootLevelAttr); default: Debug.Assert(false, "We should not get to this point."); break; } } _currentState = newState; return Task.CompletedTask; } // write namespace declarations private async Task StartElementContentAsync_WithNS() { int start = _elemScopeStack[_elemTop].prevNSTop; for (int i = _nsTop; i > start; i--) { if (_nsStack[i].kind == NamespaceKind.NeedToWrite) { await _nsStack[i].WriteDeclAsync(_writer, _rawWriter).ConfigureAwait(false); } } if (_rawWriter != null) { _rawWriter.StartElementContent(); } } private Task StartElementContentAsync() { if (_nsTop > _elemScopeStack[_elemTop].prevNSTop) { return StartElementContentAsync_WithNS(); } if (_rawWriter != null) { _rawWriter.StartElementContent(); } return Task.CompletedTask; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using Aga.Controls.Tree.NodeControls; using System.Drawing.Imaging; using System.Threading; namespace Aga.Controls.Tree { public partial class TreeViewAdv { #region Keys protected override bool IsInputChar(char charCode) { return true; } protected override bool IsInputKey(Keys keyData) { if (((keyData & Keys.Up) == Keys.Up) || ((keyData & Keys.Down) == Keys.Down) || ((keyData & Keys.Left) == Keys.Left) || ((keyData & Keys.Right) == Keys.Right)) return true; else return base.IsInputKey(keyData); } internal void ChangeInput() { if ((ModifierKeys & Keys.Shift) == Keys.Shift) { if (!(Input is InputWithShift)) Input = new InputWithShift(this); } else if ((ModifierKeys & Keys.Control) == Keys.Control) { if (!(Input is InputWithControl)) Input = new InputWithControl(this); } else { if (!(Input.GetType() == typeof(NormalInputState))) Input = new NormalInputState(this); } } protected override void OnKeyDown(KeyEventArgs e) { this._justGotFocus = false; base.OnKeyDown(e); if (!e.Handled) { if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.ControlKey) ChangeInput(); Input.KeyDown(e); if (!e.Handled) { foreach (NodeControlInfo item in GetNodeControls(CurrentNode)) { item.Control.KeyDown(e); if (e.Handled) break; } } } } protected override void OnKeyUp(KeyEventArgs e) { this._justGotFocus = false; base.OnKeyUp(e); if (!e.Handled) { if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.ControlKey) ChangeInput(); if (!e.Handled) { foreach (NodeControlInfo item in GetNodeControls(CurrentNode)) { item.Control.KeyUp(e); if (e.Handled) return; } } } } protected override void OnKeyPress(KeyPressEventArgs e) { this._justGotFocus = false; base.OnKeyPress(e); if (!e.Handled) _search.Search(e.KeyChar); } #endregion #region Mouse private TreeNodeAdvMouseEventArgs CreateMouseArgs(MouseEventArgs e) { TreeNodeAdvMouseEventArgs args = new TreeNodeAdvMouseEventArgs(e); args.ViewLocation = new Point(e.X + OffsetX, e.Y + _rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); args.ModifierKeys = ModifierKeys; args.Node = GetNodeAt(e.Location); NodeControlInfo info = GetNodeControlInfoAt(args.Node, e.Location); args.ControlBounds = info.Bounds; args.Control = info.Control; args.JustGotFocus = _justGotFocus; return args; } protected override void OnMouseWheel(MouseEventArgs e) { _search.EndSearch(); if (SystemInformation.MouseWheelScrollLines > 0) { int lines = e.Delta / 120 * SystemInformation.MouseWheelScrollLines; int newValue = _vScrollBar.Value - lines; newValue = Math.Min(_vScrollBar.Maximum - _vScrollBar.LargeChange + 1, newValue); newValue = Math.Min(_vScrollBar.Maximum, newValue); _vScrollBar.Value = Math.Max(_vScrollBar.Minimum, newValue); } base.OnMouseWheel(e); } protected override void OnMouseDown(MouseEventArgs e) { if (CurrentEditorOwner != null) { CurrentEditorOwner.EndEdit(true); return; } if (!Focused) Focus(); _search.EndSearch(); if (e.Button == MouseButtons.Left) { TreeColumn c; c = GetColumnDividerAt(e.Location); if (c != null) { Input = new ResizeColumnState(this, c, e.Location); return; } c = GetColumnAt(e.Location); if (c != null) { Input = new ClickColumnState(this, c, e.Location); UpdateView(); return; } } ChangeInput(); TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); if (args.Node != null && args.Control != null) args.Control.MouseDown(args); if (!args.Handled) Input.MouseDown(args); base.OnMouseDown(e); } protected override void OnMouseClick(MouseEventArgs e) { //TODO: Disable when click on plusminus icon TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); if (args.Node != null) OnNodeMouseClick(args); base.OnMouseClick(e); } protected override void OnMouseDoubleClick(MouseEventArgs e) { TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); if (args.Node != null && args.Control != null) args.Control.MouseDoubleClick(args); if (!args.Handled) { if (args.Node != null) OnNodeMouseDoubleClick(args); else Input.MouseDoubleClick(args); if (!args.Handled) { if (args.Node != null && args.Button == MouseButtons.Left) args.Node.IsExpanded = !args.Node.IsExpanded; } } base.OnMouseDoubleClick(e); } protected override void OnMouseUp(MouseEventArgs e) { TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); if (Input is ResizeColumnState) Input.MouseUp(args); else { if (args.Node != null && args.Control != null) args.Control.MouseUp(args); if (!args.Handled) Input.MouseUp(args); base.OnMouseUp(e); } this._justGotFocus = false; } protected override void OnMouseMove(MouseEventArgs e) { if (Input.MouseMove(e)) return; base.OnMouseMove(e); SetCursor(e); UpdateToolTip(e); if (ItemDragMode && Dist(e.Location, ItemDragStart) > ItemDragSensivity && CurrentNode != null && CurrentNode.IsSelected) { ItemDragMode = false; _toolTip.Active = false; OnItemDrag(e.Button, Selection.ToArray()); } } protected override void OnMouseLeave(EventArgs e) { this._justGotFocus = false; _hotColumn = null; UpdateHeaders(); base.OnMouseLeave(e); } private void SetCursor(MouseEventArgs e) { TreeColumn col; col = GetColumnDividerAt(e.Location); if (col == null) _innerCursor = null; else { if (col.Width == 0) _innerCursor = ResourceHelper.DVSplitCursor; else _innerCursor = Cursors.VSplit; } col = GetColumnAt(e.Location); if (col != _hotColumn) { _hotColumn = col; UpdateHeaders(); } } internal TreeColumn GetColumnAt(Point p) { if (p.Y > ColumnHeaderHeight) return null; int x = -OffsetX; foreach (TreeColumn col in Columns) { if (col.IsVisible) { Rectangle rect = new Rectangle(x, 0, col.Width, ColumnHeaderHeight); x += col.Width; if (rect.Contains(p)) return col; } } return null; } internal int GetColumnX(TreeColumn column) { int x = -OffsetX; foreach (TreeColumn col in Columns) { if (col.IsVisible) { if (column == col) return x; else x += col.Width; } } return x; } internal TreeColumn GetColumnDividerAt(Point p) { if (p.Y > ColumnHeaderHeight) return null; int x = -OffsetX; TreeColumn prevCol = null; Rectangle left, right; foreach (TreeColumn col in Columns) { if (col.IsVisible) { if (col.Width > 0) { left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); right = new Rectangle(x + col.Width - (DividerWidth / 2), 0, DividerWidth / 2, ColumnHeaderHeight); if (left.Contains(p) && prevCol != null) return prevCol; else if (right.Contains(p)) return col; } prevCol = col; x += col.Width; } } left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); if (left.Contains(p) && prevCol != null) return prevCol; return null; } TreeColumn _tooltipColumn; private void UpdateToolTip(MouseEventArgs e) { TreeColumn col = GetColumnAt(e.Location); if (col != null) { if (col != _tooltipColumn) SetTooltip(col.TooltipText); } else DisplayNodesTooltip(e); _tooltipColumn = col; } TreeNodeAdv _hotNode; NodeControl _hotControl; private void DisplayNodesTooltip(MouseEventArgs e) { if (ShowNodeToolTips) { TreeNodeAdvMouseEventArgs args = CreateMouseArgs(e); if (args.Node != null && args.Control != null) { if (args.Node != _hotNode || args.Control != _hotControl) SetTooltip(GetNodeToolTip(args)); } else _toolTip.SetToolTip(this, null); _hotControl = args.Control; _hotNode = args.Node; } else _toolTip.SetToolTip(this, null); } private void SetTooltip(string text) { if (!String.IsNullOrEmpty(text)) { _toolTip.Active = false; _toolTip.SetToolTip(this, text); _toolTip.Active = true; } else _toolTip.SetToolTip(this, null); } private string GetNodeToolTip(TreeNodeAdvMouseEventArgs args) { string msg = args.Control.GetToolTip(args.Node); BaseTextControl btc = args.Control as BaseTextControl; if (btc != null && btc.DisplayHiddenContentInToolTip && String.IsNullOrEmpty(msg)) { Size ms = btc.GetActualSize(args.Node, _measureContext); if (ms.Width > args.ControlBounds.Size.Width || ms.Height > args.ControlBounds.Size.Height || args.ControlBounds.Right - OffsetX > DisplayRectangle.Width) msg = btc.GetLabel(args.Node); } if (String.IsNullOrEmpty(msg) && DefaultToolTipProvider != null) msg = DefaultToolTipProvider.GetToolTip(args.Node, args.Control); return msg; } #endregion #region DragDrop private bool _dragAutoScrollFlag = false; private Bitmap _dragBitmap = null; private System.Threading.Timer _dragTimer; private void StartDragTimer() { if (_dragTimer == null) _dragTimer = new System.Threading.Timer(new TimerCallback(DragTimerTick), null, 0, 100); } private void StopDragTimer() { if (_dragTimer != null) { _dragTimer.Dispose(); _dragTimer = null; } } private void SetDropPosition(Point pt) { TreeNodeAdv node = GetNodeAt(pt); OnDropNodeValidating(pt, ref node); _dropPosition.Node = node; if (node != null) { Rectangle first = _rowLayout.GetRowBounds(FirstVisibleRow); Rectangle bounds = _rowLayout.GetRowBounds(node.Row); float pos = (pt.Y + first.Y - ColumnHeaderHeight - bounds.Y) / (float)bounds.Height; if (pos < TopEdgeSensivity) _dropPosition.Position = NodePosition.Before; else if (pos > (1 - BottomEdgeSensivity)) _dropPosition.Position = NodePosition.After; else _dropPosition.Position = NodePosition.Inside; } } private void DragTimerTick(object state) { _dragAutoScrollFlag = true; } private void DragAutoScroll() { _dragAutoScrollFlag = false; if (_vScrollBar.Minimum != _vScrollBar.Maximum) { Point pt = PointToClient(MousePosition); if (pt.Y < 20 && _vScrollBar.Value > 0) _vScrollBar.Value--; else if (pt.Y > Height - 20 && _vScrollBar.Value <= _vScrollBar.Maximum - _vScrollBar.LargeChange) _vScrollBar.Value++; } } public void DoDragDropSelectedNodes(DragDropEffects allowedEffects) { if (SelectedNodes.Count > 0) { TreeNodeAdv[] nodes = new TreeNodeAdv[SelectedNodes.Count]; SelectedNodes.CopyTo(nodes, 0); DoDragDrop(nodes, allowedEffects); } } private void CreateDragBitmap(IDataObject data) { if (UseColumns || !DisplayDraggingNodes) return; TreeNodeAdv[] nodes = data.GetData(typeof(TreeNodeAdv[])) as TreeNodeAdv[]; if (nodes != null && nodes.Length > 0) { Rectangle rect = DisplayRectangle; Bitmap bitmap = new Bitmap(rect.Width, rect.Height); using (Graphics gr = Graphics.FromImage(bitmap)) { gr.Clear(BackColor); DrawContext context = new DrawContext(); context.Graphics = gr; context.Font = Font; context.Enabled = true; int y = 0; int maxWidth = 0; foreach (TreeNodeAdv node in nodes) { if (node.Tree == this) { int x = 0; int height = _rowLayout.GetRowBounds(node.Row).Height; foreach (NodeControl c in NodeControls) { Size s = c.GetActualSize(node, context); if (!s.IsEmpty) { int width = s.Width; rect = new Rectangle(x, y, width, height); x += (width + 1); context.Bounds = rect; c.Draw(node, context); } } y += height; maxWidth = Math.Max(maxWidth, x); } } if (maxWidth > 0 && y > 0) { _dragBitmap = new Bitmap(maxWidth, y, PixelFormat.Format32bppArgb); using (Graphics tgr = Graphics.FromImage(_dragBitmap)) tgr.DrawImage(bitmap, Point.Empty); BitmapHelper.SetAlphaChanelValue(_dragBitmap, 150); } else _dragBitmap = null; } } } protected override void OnDragOver(DragEventArgs drgevent) { ItemDragMode = false; Point pt = PointToClient(new Point(drgevent.X, drgevent.Y)); if (_dragAutoScrollFlag) DragAutoScroll(); SetDropPosition(pt); UpdateView(); base.OnDragOver(drgevent); } protected override void OnDragEnter(DragEventArgs drgevent) { _search.EndSearch(); DragMode = true; CreateDragBitmap(drgevent.Data); base.OnDragEnter(drgevent); } protected override void OnDragLeave(EventArgs e) { DragMode = false; UpdateView(); base.OnDragLeave(e); } protected override void OnDragDrop(DragEventArgs drgevent) { DragMode = false; UpdateView(); base.OnDragDrop(drgevent); } #endregion } }
// <copyright file=BezierPath company=Hydra> // Copyright (c) 2015 All Rights Reserved // </copyright> // <author>Christopher Cameron</author> using System; using Hydra.HydraCommon.Abstract; using Hydra.HydraCommon.API; using Hydra.HydraCommon.Extensions; using Hydra.HydraCommon.PropertyAttributes; using Hydra.HydraCommon.Utils; using UnityEngine; namespace Hydra.HydraCommon.Concrete { /// <summary> /// Bezier path. /// </summary> [Serializable] public class BezierPath : HydraMonoBehaviourChild { // This value determines the accuracy of mapping linear deltas onto // a bezier patch. Higher numbers = greater accuracy. public const int LENGTH_LINE_SEGMENTS = 50; public const float DELTA_LINE_SEGMENTS = 1.0f / LENGTH_LINE_SEGMENTS; // When calculating the normal we cheat and use a slightly incremented delta // to find a new tangent. public const float NORMAL_INTERVAL = 0.001f; public static readonly float s_Root2 = Mathf.Sqrt(2.0f); [SerializeField] private BezierPointAttribute[] m_Points; [SerializeField] private bool m_Closed; // Cache private static float[] s_SegmentPointDeltas; #region Properties /// <summary> /// Gets or sets the points. /// </summary> /// <value>The points.</value> public BezierPointAttribute[] points { get { return m_Points; } set { m_Points = value; } } /// <summary> /// Gets or sets a value indicating whether this BezierPath is closed. /// </summary> /// <value><c>true</c> if closed; otherwise, <c>false</c>.</value> public bool closed { get { return m_Closed; } set { m_Closed = value; } } #endregion #region Messages /// <summary> /// Called when the parent is enabled. /// </summary> protected override void OnEnable(HydraMonoBehaviour parent) { if (m_Points == null) m_Points = new BezierPointAttribute[0]; base.OnEnable(parent); } #endregion #region Methods /// <summary> /// Gets the first point. /// </summary> /// <returns>The first point.</returns> public BezierPointAttribute GetFirstPoint() { return (m_Points.Length == 0) ? null : m_Points[0]; } /// <summary> /// Gets the last point. /// </summary> /// <returns>The last point.</returns> public BezierPointAttribute GetLastPoint() { return (m_Points.Length == 0) ? null : m_Points[m_Points.Length - 1]; } /// <summary> /// Gets the previous point in the path. If this is the first point and /// and the path is closed, this method will return the last point. /// </summary> /// <returns>The previous point.</returns> /// <param name="point">Point.</param> public BezierPointAttribute GetPreviousPoint(BezierPointAttribute point) { int index = m_Points.IndexOf(point); return GetPreviousPoint(index); } /// <summary> /// Gets the previous point in the path. If this is the first point and /// and the path is closed, this method will return the last point. /// </summary> /// <returns>The previous point.</returns> /// <param name="index">Index.</param> public BezierPointAttribute GetPreviousPoint(int index) { if (index == 0) return m_Closed ? GetLastPoint() : null; return m_Points[index - 1]; } /// <summary> /// Gets the next point in the path. If this is the last point and /// and the path is closed, this method will return the first point. /// </summary> /// <returns>The next point.</returns> /// <param name="point">Point.</param> public BezierPointAttribute GetNextPoint(BezierPointAttribute point) { int index = m_Points.IndexOf(point); return GetNextPoint(index); } /// <summary> /// Gets the next point in the path. If this is the last point and /// and the path is closed, this method will return the first point. /// </summary> /// <returns>The next point.</returns> /// <param name="index">Index.</param> public BezierPointAttribute GetNextPoint(int index) { if (index == m_Points.Length - 1) return m_Closed ? GetFirstPoint() : null; return m_Points[index + 1]; } /// <summary> /// Returns the position at the given delta. /// </summary> /// <param name="delta">Delta.</param> public Vector3 Interpolate(float delta) { if (m_Points.Length == 0) throw new Exception("Path has no points."); if (m_Points.Length == 1 && !m_Closed) return m_Points[0].position; BezierPointAttribute pointA; BezierPointAttribute pointB; float patchDelta; PatchForDelta(out pointA, out pointB, out patchDelta, delta); return Interpolate(pointA, pointB, patchDelta); } /// <summary> /// Returns the tangent at the given delta. /// </summary> /// <param name="delta">Delta.</param> public Vector3 Tangent(float delta) { if (m_Points.Length == 0) throw new Exception("Path has no points."); if (m_Points.Length == 1 && !m_Closed) return Vector3.right; BezierPointAttribute pointA; BezierPointAttribute pointB; float patchDelta; PatchForDelta(out pointA, out pointB, out patchDelta, delta); return Tangent(pointA, pointB, patchDelta); } /// <summary> /// Returns the normal at the given delta. /// </summary> /// <param name="delta">Delta.</param> public Vector3 Normal(float delta) { if (m_Points.Length == 0) throw new Exception("Path has no points."); if (m_Points.Length == 1 && !m_Closed) return Vector3.up; BezierPointAttribute pointA; BezierPointAttribute pointB; float patchDelta; PatchForDelta(out pointA, out pointB, out patchDelta, delta); return Normal(pointA, pointB, patchDelta); } /// <summary> /// Interpolate returns an interpolated value on the curve between pointA and pointB. /// Be aware that this value is NOT linear. /// </summary> /// <returns>The interpolated value.</returns> /// <param name="pointA">Point a.</param> /// <param name="pointB">Point b.</param> /// <param name="delta">Delta.</param> public Vector3 Interpolate(BezierPointAttribute pointA, BezierPointAttribute pointB, float delta) { BezierPointAttribute previousPoint = GetPreviousPoint(pointA); BezierPointAttribute nextPoint = GetNextPoint(pointB); Vector3 outTangent = GetOutTangent(previousPoint, pointA, pointB); Vector3 inTangent = GetInTangent(pointA, pointB, nextPoint); float x = ComputeBezier(pointA.position.x, outTangent.x, inTangent.x, pointB.position.x, delta); float y = ComputeBezier(pointA.position.y, outTangent.y, inTangent.y, pointB.position.y, delta); float z = ComputeBezier(pointA.position.z, outTangent.z, inTangent.z, pointB.position.z, delta); return new Vector3(x, y, z); } /// <summary> /// Returns the positions on the curve between the two points at the given deltas. /// /// This method is faster than calling Interpolate multiple times for the same patch. /// </summary> /// <returns>The interpolated positions.</returns> /// <param name="output">Output.</param> /// <param name="pointA">Point a.</param> /// <param name="pointB">Point b.</param> /// <param name="deltas">Deltas.</param> public void Interpolate(ref Vector3[] output, BezierPointAttribute pointA, BezierPointAttribute pointB, float[] deltas) { BezierPointAttribute previousPoint = GetPreviousPoint(pointA); BezierPointAttribute nextPoint = GetNextPoint(pointB); Interpolate(ref output, previousPoint, pointA, pointB, nextPoint, deltas); } /// <summary> /// Returns the tangent at the given non-linear delta. /// </summary> /// <returns>The tangent vector.</returns> /// <param name="pointA">Point a.</param> /// <param name="pointB">Point b.</param> /// <param name="delta">Delta.</param> public Vector3 Tangent(BezierPointAttribute pointA, BezierPointAttribute pointB, float delta) { BezierPointAttribute previousPoint = GetPreviousPoint(pointA); BezierPointAttribute nextPoint = GetNextPoint(pointB); Vector3 outTangent = GetOutTangent(previousPoint, pointA, pointB); Vector3 inTangent = GetInTangent(pointA, pointB, nextPoint); float x = ComputeBezierDerivative(pointA.position.x, outTangent.x, inTangent.x, pointB.position.x, delta); float y = ComputeBezierDerivative(pointA.position.y, outTangent.y, inTangent.y, pointB.position.y, delta); float z = ComputeBezierDerivative(pointA.position.z, outTangent.z, inTangent.z, pointB.position.z, delta); return new Vector3(x, y, z); } /// <summary> /// Returns the normal at the given non-linear delta. /// </summary> /// <returns>The normal vector.</returns> /// <param name="pointA">Point a.</param> /// <param name="pointB">Point b.</param> /// <param name="delta">Delta.</param> public Vector3 Normal(BezierPointAttribute pointA, BezierPointAttribute pointB, float delta) { Vector3 position = Interpolate(pointA, pointB, delta); Vector3 tangent = Tangent(pointA, pointB, delta).normalized; // Cheat to get the next point along the curve float nextDelta = delta + NORMAL_INTERVAL; Vector3 position2 = Interpolate(pointA, pointB, nextDelta); Vector3 tangent2 = Tangent(pointA, pointB, nextDelta); tangent2 -= (position2 - position); tangent2 = tangent2.normalized; Vector3 c = new Vector3(tangent2.y * tangent.z - tangent2.z * tangent.y, tangent2.z * tangent.x - tangent2.x * tangent.z, tangent2.x * tangent.y - tangent2.y * tangent.x).normalized; Matrix4x4 r = Matrix4x4.identity; r.SetRow(0, new Vector4(c.x * c.x, c.x * c.y - c.z, c.x * c.z + c.y)); r.SetRow(1, new Vector4(c.x * c.y + c.z, c.y * c.y, c.y * c.z - c.x)); r.SetRow(2, new Vector4(c.x * c.z - c.y, c.y * c.z + c.x, c.z * c.z)); return r.MultiplyVector(tangent); } #endregion #region Private Methods /// <summary> /// Provides the patch and patch delta for the given path delta. /// </summary> /// <param name="pointA">Point a.</param> /// <param name="pointB">Point b.</param> /// <param name="patchDelta">Patch delta.</param> /// <param name="delta">Delta.</param> private void PatchForDelta(out BezierPointAttribute pointA, out BezierPointAttribute pointB, out float patchDelta, float delta) { int patches = m_Points.Length - 1; if (m_Closed) patches++; if (patches < 1) throw new Exception("No patches in the path!"); delta = Mathf.Repeat(delta, 1.0f); int patchIndex = HydraMathUtils.FloorToInt(delta * patches); pointA = m_Points[patchIndex]; pointB = GetNextPoint(patchIndex); float singlePatchDelta = 1.0f / patches; patchDelta = delta - (patchIndex * singlePatchDelta); patchDelta *= patches; } #endregion #region Static Methods /// <summary> /// Returns an interpolated value between two points on a single axis. This is NOT linear. /// </summary> /// <returns>The interpolated value.</returns> /// <param name="pointA">Point a.</param> /// <param name="outNormal">Out normal.</param> /// <param name="inNormal">In normal.</param> /// <param name="pointB">Point b.</param> /// <param name="delta">Delta.</param> public static float ComputeBezier(float pointA, float outNormal, float inNormal, float pointB, float delta) { float outNormalPosition = pointA + outNormal; float inNormalPosition = pointB + inNormal; float inverseDelta = 1.0f - delta; float firstTerm = (inverseDelta * inverseDelta * inverseDelta) * pointA; float secondTerm = 3.0f * (inverseDelta * inverseDelta) * delta * outNormalPosition; float thirdTerm = 3.0f * inverseDelta * (delta * delta) * inNormalPosition; float fourthTerm = (delta * delta * delta) * pointB; return firstTerm + secondTerm + thirdTerm + fourthTerm; } /// <summary> /// Returns the tangent at a given delta between two points on a single axis. The delta is NOT linear. /// </summary> /// <returns>The tangent.</returns> /// <param name="pointA">Point a.</param> /// <param name="outNormal">Out normal.</param> /// <param name="inNormal">In normal.</param> /// <param name="pointB">Point b.</param> /// <param name="delta">Delta.</param> public static float ComputeBezierDerivative(float pointA, float outNormal, float inNormal, float pointB, float delta) { float outNormalPosition = pointA + outNormal; float inNormalPosition = pointB + inNormal; float deltaSquare = delta * delta; float inverseDelta = 1.0f - delta; float inverseDeltaSquare = inverseDelta * inverseDelta; float firstTerm = -3.0f * pointA * inverseDeltaSquare; float secondTerm = outNormalPosition * (3.0f * inverseDeltaSquare - 6.0f * (1.0f - delta) * delta); float thirdTerm = inNormalPosition * (6.0f * (1.0f - delta) * delta - 3.0f * deltaSquare); float fourthTerm = 3.0f * pointB * deltaSquare; return firstTerm + secondTerm + thirdTerm + fourthTerm; } /// <summary> /// Creates a bezier circle path. /// </summary> /// <param name="radius">Radius.</param> public static BezierPath Circle(float radius) { BezierPath path = CreateInstance<BezierPath>(null); path.closed = true; float controlDistance = radius * 4.0f * (s_Root2 - 1.0f) / 3.0f; Quaternion offset = Quaternion.identity; Quaternion increment = Quaternion.Euler(0.0f, 0.0f, 90.0f); BezierPointAttribute[] points = new BezierPointAttribute[4]; for (int index = 0; index < 4; index++) { Vector3 position = Vector3.up * radius; Vector3 inTangent = Vector3.right * controlDistance; Vector3 outTangent = Vector3.left * controlDistance; BezierPointAttribute point = BezierPointAttribute.CreateInstance<BezierPointAttribute>(); point.tangentMode = TangentMode.Smooth; point.position = offset * position; point.inTangent = offset * inTangent; point.outTangent = offset * outTangent; points[index] = point; offset *= increment; } path.points = points; return path; } /// <summary> /// Gets the in tangent. /// </summary> /// <returns>The in tangent.</returns> /// <param name="previousPoint">Previous point.</param> /// <param name="point">Point.</param> /// <param name="nextPoint">Next point.</param> public static Vector3 GetInTangent(IBezierPoint previousPoint, IBezierPoint point, IBezierPoint nextPoint) { Vector3 inTangent; Vector3 outTangent; GetTangents(out inTangent, out outTangent, previousPoint, point, nextPoint); return inTangent; } /// <summary> /// Gets the out tangent. /// </summary> /// <returns>The out tangent.</returns> /// <param name="previousPoint">Previous point.</param> /// <param name="point">Point.</param> /// <param name="nextPoint">Next point.</param> public static Vector3 GetOutTangent(IBezierPoint previousPoint, IBezierPoint point, IBezierPoint nextPoint) { Vector3 inTangent; Vector3 outTangent; GetTangents(out inTangent, out outTangent, previousPoint, point, nextPoint); return outTangent; } /// <summary> /// Gets the tangents. /// </summary> /// <param name="inTangent">In tangent.</param> /// <param name="outTangent">Out tangent.</param> /// <param name="previousPoint">Previous point.</param> /// <param name="point">Point.</param> /// <param name="nextPoint">Next point.</param> public static void GetTangents(out Vector3 inTangent, out Vector3 outTangent, IBezierPoint previousPoint, IBezierPoint point, IBezierPoint nextPoint) { switch (point.tangentMode) { case TangentMode.Smooth: inTangent = point.inTangent; outTangent = point.inTangent * -1.0f; break; case TangentMode.Corner: inTangent = point.inTangent; outTangent = point.outTangent; break; case TangentMode.Symmetric: GetSymmetricTangents(out inTangent, out outTangent, previousPoint, point, nextPoint); break; case TangentMode.Auto: GetAutoTangents(out inTangent, out outTangent, previousPoint, point, nextPoint); break; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Gets the symmetric tangents. /// </summary> /// <param name="inTangent">In tangent.</param> /// <param name="outTangent">Out tangent.</param> /// <param name="previousPoint">Previous point.</param> /// <param name="point">Point.</param> /// <param name="nextPoint">Next point.</param> private static void GetSymmetricTangents(out Vector3 inTangent, out Vector3 outTangent, IBezierPoint previousPoint, IBezierPoint point, IBezierPoint nextPoint) { Vector3 previousToNext; Vector3 thisToPrevious = Vector3.zero; Vector3 thisToNext = Vector3.zero; if (previousPoint != null) thisToPrevious = previousPoint.position - point.position; if (nextPoint != null) thisToNext = nextPoint.position - point.position; if (previousPoint == null) previousToNext = thisToNext; else if (nextPoint == null) previousToNext = thisToPrevious; else previousToNext = nextPoint.position - previousPoint.position; float inTangentMagnitude = thisToPrevious.magnitude / 3.0f; float outTangentMagnitude = thisToNext.magnitude / 3.0f; float averageMagnitude = (inTangentMagnitude + outTangentMagnitude) / 2.0f; inTangent = -1.0f * averageMagnitude * previousToNext.normalized; outTangent = averageMagnitude * previousToNext.normalized; } /// <summary> /// Gets the auto tangents. /// </summary> /// <param name="inTangent">In tangent.</param> /// <param name="outTangent">Out tangent.</param> /// <param name="previousPoint">Previous point.</param> /// <param name="point">Point.</param> /// <param name="nextPoint">Next point.</param> private static void GetAutoTangents(out Vector3 inTangent, out Vector3 outTangent, IBezierPoint previousPoint, IBezierPoint point, IBezierPoint nextPoint) { Vector3 previousToNext; Vector3 thisToPrevious = Vector3.zero; Vector3 thisToNext = Vector3.zero; if (previousPoint != null) thisToPrevious = previousPoint.position - point.position; if (nextPoint != null) thisToNext = nextPoint.position - point.position; if (previousPoint == null) previousToNext = thisToNext; else if (nextPoint == null) previousToNext = thisToPrevious; else previousToNext = nextPoint.position - previousPoint.position; float inTangentMagnitude = thisToPrevious.magnitude / 3.0f; float outTangentMagnitude = thisToNext.magnitude / 3.0f; inTangent = -1.0f * inTangentMagnitude * previousToNext.normalized; outTangent = outTangentMagnitude * previousToNext.normalized; } /// <summary> /// Using the curve between pointA and pointB we take a discrete number of line segments /// and return all of the points that make those lines. /// </summary> /// <returns>The segment points.</returns> /// <param name="output">Output.</param> /// <param name="pointA">Point a.</param> /// <param name="pointB">Point b.</param> /// <param name="pointC">Point c.</param> /// <param name="pointD">Point d.</param> public static void GetSegmentPoints(ref Vector3[] output, IBezierPoint pointA, IBezierPoint pointB, IBezierPoint pointC, IBezierPoint pointD) { Array.Resize(ref s_SegmentPointDeltas, LENGTH_LINE_SEGMENTS + 1); for (int index = 0; index < LENGTH_LINE_SEGMENTS + 1; index++) s_SegmentPointDeltas[index] = DELTA_LINE_SEGMENTS * index; Interpolate(ref output, pointA, pointB, pointC, pointD, s_SegmentPointDeltas); } /// <summary> /// Returns the positions on the curve between the two points at the given deltas. /// /// This method is faster than calling Interpolate multiple times for the same patch. /// </summary> /// <returns>The interpolated positions.</returns> /// <param name="output">Output.</param> /// <param name="pointA">Point a.</param> /// <param name="pointB">Point b.</param> /// <param name="pointC">Point c.</param> /// <param name="pointD">Point d.</param> /// <param name="deltas">Deltas.</param> public static void Interpolate(ref Vector3[] output, IBezierPoint pointA, IBezierPoint pointB, IBezierPoint pointC, IBezierPoint pointD, float[] deltas) { Array.Resize(ref output, deltas.Length); Vector3 outTangent = GetOutTangent(pointA, pointB, pointC); Vector3 inTangent = GetInTangent(pointB, pointC, pointD); for (int index = 0; index < deltas.Length; index++) { float delta = deltas[index]; float x = ComputeBezier(pointB.position.x, outTangent.x, inTangent.x, pointC.position.x, delta); float y = ComputeBezier(pointB.position.y, outTangent.y, inTangent.y, pointC.position.y, delta); float z = ComputeBezier(pointB.position.z, outTangent.z, inTangent.z, pointC.position.z, delta); output[index] = new Vector3(x, y, z); } } #endregion } }
// // AddinRegistry.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Xml; using System.Collections; using System.Collections.Specialized; using Mono.Addins.Database; using Mono.Addins.Description; using System.Collections.Generic; using System.Linq; namespace Mono.Addins { /// <summary> /// An add-in registry. /// </summary> /// <remarks> /// An add-in registry is a data structure used by the add-in engine to locate add-ins to load. /// /// A registry can be configured to look for add-ins in several directories. However, add-ins /// copied to those directories won't be detected until an explicit add-in scan is requested. /// The registry can be updated by an application by calling Registry.Update(), or by a user by /// running the 'mautil' add-in setup tool. /// /// The registry has information about the location of every add-in and a timestamp of the last /// check, so the Update method will only scan new or modified add-ins. An application can /// add a call to Registry.Update() in the Main method to detect all new add-ins every time the /// app is started. /// /// Every add-in added to the registry is parsed and validated, and if there is any error it /// will be rejected. The registry is also in charge of scanning the add-in assemblies and look /// for extensions and other information declared using custom attributes. That information is /// merged with the manifest information (if there is one) to create a complete add-in /// description ready to be used at run-time. /// /// Mono.Addins allows sharing an add-in registry among several applications. In this context, /// all applications sharing the registry share the same extension point model, and it is /// possible to implement add-ins which extend several hosts. /// </remarks> public class AddinRegistry: IDisposable { AddinDatabase database; StringCollection addinDirs; string basePath; string currentDomain; string startupDirectory; string addinsDir; string databaseDir; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="registryPath"> /// Location of the add-in registry. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// The add-in registry will look for add-ins in an 'addins' /// subdirectory of the provided registryPath. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath): this (null, registryPath, null, null, null) { } /// <summary> /// Initializes a new instance. /// </summary> /// <param name="registryPath"> /// Location of the add-in registry. /// </param> /// <param name="startupDirectory"> /// Location of the application. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// The add-in registry will look for add-ins in an 'addins' /// subdirectory of the provided registryPath. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath, string startupDirectory): this (null, registryPath, startupDirectory, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.AddinRegistry"/> class. /// </summary> /// <param name='registryPath'> /// Location of the add-in registry. /// </param> /// <param name='startupDirectory'> /// Location of the application. /// </param> /// <param name='addinsDir'> /// Add-ins directory. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// Configuration information about the add-in registry will be stored in /// 'registryPath'. The add-in registry will look for add-ins in the provided /// 'addinsDir' directory. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath, string startupDirectory, string addinsDir): this (null, registryPath, startupDirectory, addinsDir, null) { } /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.AddinRegistry"/> class. /// </summary> /// <param name='registryPath'> /// Location of the add-in registry. /// </param> /// <param name='startupDirectory'> /// Location of the application. /// </param> /// <param name='addinsDir'> /// Add-ins directory. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <param name='databaseDir'> /// Location of the add-in database. If the path is relative, it is considered to be relative /// to the configDir directory. /// </param> /// <remarks> /// Creates a new add-in registry located in the provided path. /// Configuration information about the add-in registry will be stored in /// 'registryPath'. The add-in registry will look for add-ins in the provided /// 'addinsDir' directory. Cached information about add-ins will be stored in /// the 'databaseDir' directory. /// /// When specifying a path, it is possible to use a special folder name as root. /// For example: [Personal]/.config/MyApp. In this case, [Personal] will be replaced /// by the location of the Environment.SpecialFolder.Personal folder. Any value /// of the Environment.SpecialFolder enumeration can be used (always between square /// brackets) /// </remarks> public AddinRegistry (string registryPath, string startupDirectory, string addinsDir, string databaseDir): this (null, registryPath, startupDirectory, addinsDir, databaseDir) { } internal AddinRegistry (AddinEngine engine, string registryPath, string startupDirectory, string addinsDir, string databaseDir) { basePath = Path.GetFullPath (Util.NormalizePath (registryPath)); if (addinsDir != null) { addinsDir = Util.NormalizePath (addinsDir); if (Path.IsPathRooted (addinsDir)) this.addinsDir = Path.GetFullPath (addinsDir); else this.addinsDir = Path.GetFullPath (Path.Combine (basePath, addinsDir)); } else this.addinsDir = Path.Combine (basePath, "addins"); if (databaseDir != null) { databaseDir = Util.NormalizePath (databaseDir); if (Path.IsPathRooted (databaseDir)) this.databaseDir = Path.GetFullPath (databaseDir); else this.databaseDir = Path.GetFullPath (Path.Combine (basePath, databaseDir)); } else this.databaseDir = Path.GetFullPath (basePath); // Look for add-ins in the hosts directory and in the default // addins directory addinDirs = new StringCollection (); addinDirs.Add (DefaultAddinsFolder); // Initialize the database after all paths have been set database = new AddinDatabase (engine, this); // Get the domain corresponding to the startup folder if (startupDirectory != null && startupDirectory.Length > 0) { this.startupDirectory = Util.NormalizePath (startupDirectory); currentDomain = database.GetFolderDomain (null, this.startupDirectory); } else currentDomain = AddinDatabase.GlobalDomain; } /// <summary> /// Gets the global registry. /// </summary> /// <returns> /// The global registry /// </returns> /// <remarks> /// The global add-in registry is created in "~/.config/mono.addins", /// and it is the default registry used when none is specified. /// </remarks> public static AddinRegistry GetGlobalRegistry () { return GetGlobalRegistry (null, null); } internal static AddinRegistry GetGlobalRegistry (AddinEngine engine, string startupDirectory) { AddinRegistry reg = new AddinRegistry (engine, GlobalRegistryPath, startupDirectory, null, null); string baseDir; if (Util.IsWindows) baseDir = Environment.GetFolderPath (Environment.SpecialFolder.CommonProgramFiles); else baseDir = "/etc"; reg.GlobalAddinDirectories.Add (Path.Combine (baseDir, "mono.addins")); return reg; } internal bool UnknownDomain { get { return currentDomain == AddinDatabase.UnknownDomain; } } internal static string GlobalRegistryPath { get { string customDir = Environment.GetEnvironmentVariable ("MONO_ADDINS_GLOBAL_REGISTRY"); if (customDir != null && customDir.Length > 0) return Path.GetFullPath (Util.NormalizePath (customDir)); string path = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); path = Path.Combine (path, "mono.addins"); return Path.GetFullPath (path); } } internal string CurrentDomain { get { return currentDomain; } } /// <summary> /// Location of the add-in registry. /// </summary> public string RegistryPath { get { return basePath; } } /// <summary> /// Disposes the add-in engine. /// </summary> public void Dispose () { database.Shutdown (); } /// <summary> /// Returns an add-in from the registry. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <returns> /// The add-in, or 'null' if not found. /// </returns> /// <remarks> /// The add-in identifier may optionally include a version number, for example: "TextEditor.Xml,1.2" /// </remarks> public Addin GetAddin (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return null; Addin ad = database.GetInstalledAddin (currentDomain, id); if (ad != null && IsRegisteredForUninstall (ad.Id)) return null; return ad; } /// <summary> /// Returns an add-in from the registry. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <param name="exactVersionMatch"> /// 'true' if the exact add-in version must be found. /// </param> /// <returns> /// The add-in, or 'null' if not found. /// </returns> /// <remarks> /// The add-in identifier may optionally include a version number, for example: "TextEditor.Xml,1.2". /// In this case, if the exact version is not found and exactVersionMatch is 'false', it will /// return one than is compatible with the required version. /// </remarks> public Addin GetAddin (string id, bool exactVersionMatch) { if (currentDomain == AddinDatabase.UnknownDomain) return null; Addin ad = database.GetInstalledAddin (currentDomain, id, exactVersionMatch); if (ad != null && IsRegisteredForUninstall (ad.Id)) return null; return ad; } /// <summary> /// Gets all add-ins or add-in roots registered in the registry. /// </summary> /// <returns> /// The addins. /// </returns> /// <param name='flags'> /// Flags. /// </param> public Addin[] GetModules (AddinSearchFlags flags) { if (currentDomain == AddinDatabase.UnknownDomain) return new Addin [0]; AddinSearchFlagsInternal f = (AddinSearchFlagsInternal)(int)flags; return database.GetInstalledAddins (currentDomain, f | AddinSearchFlagsInternal.ExcludePendingUninstall).ToArray (); } /// <summary> /// Gets all add-ins registered in the registry. /// </summary> /// <returns> /// Add-ins registered in the registry. /// </returns> public Addin[] GetAddins () { return GetModules (AddinSearchFlags.IncludeAddins); } /// <summary> /// Gets all add-in roots registered in the registry. /// </summary> /// <returns> /// Descriptions of all add-in roots. /// </returns> public Addin[] GetAddinRoots () { return GetModules (AddinSearchFlags.IncludeRoots); } /// <summary> /// Loads an add-in description /// </summary> /// <param name="progressStatus"> /// Progress tracker. /// </param> /// <param name="file"> /// Name of the file to load /// </param> /// <returns> /// An add-in description /// </returns> /// <remarks> /// This method loads an add-in description from a file. The file can be an XML manifest or an /// assembly that implements an add-in. /// </remarks> public AddinDescription GetAddinDescription (IProgressStatus progressStatus, string file) { if (currentDomain == AddinDatabase.UnknownDomain) return null; string outFile = Path.GetTempFileName (); try { database.ParseAddin (progressStatus, currentDomain, file, outFile, false); } catch { File.Delete (outFile); throw; } try { AddinDescription desc = AddinDescription.Read (outFile); if (desc != null) { desc.AddinFile = file; desc.OwnerDatabase = database; } return desc; } catch { // Errors are already reported using the progress status object return null; } finally { File.Delete (outFile); } } /// <summary> /// Reads an XML add-in manifest /// </summary> /// <param name="file"> /// Path to the XML file /// </param> /// <returns> /// An add-in description /// </returns> public AddinDescription ReadAddinManifestFile (string file) { AddinDescription desc = AddinDescription.Read (file); if (currentDomain != AddinDatabase.UnknownDomain) { desc.OwnerDatabase = database; desc.Domain = currentDomain; } return desc; } /// <summary> /// Reads an XML add-in manifest /// </summary> /// <param name="reader"> /// Reader that contains the XML /// </param> /// <param name="baseFile"> /// Base path to use to discover add-in files /// </param> /// <returns> /// An add-in description /// </returns> public AddinDescription ReadAddinManifestFile (TextReader reader, string baseFile) { if (currentDomain == AddinDatabase.UnknownDomain) return null; AddinDescription desc = AddinDescription.Read (reader, baseFile); desc.OwnerDatabase = database; desc.Domain = currentDomain; return desc; } /// <summary> /// Checks whether an add-in is enabled. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <returns> /// 'true' if the add-in is enabled. /// </returns> public bool IsAddinEnabled (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return false; return database.IsAddinEnabled (currentDomain, id); } /// <summary> /// Enables an add-in. /// </summary> /// <param name="id"> /// Identifier of the add-in /// </param> /// <remarks> /// If the enabled add-in depends on other add-ins which are disabled, /// those will automatically be enabled too. /// </remarks> public void EnableAddin (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return; database.EnableAddin (currentDomain, id, true); } /// <summary> /// Disables an add-in. /// </summary> /// <param name="id"> /// Identifier of the add-in. /// </param> /// <remarks> /// When an add-in is disabled, all extension points it defines will be ignored /// by the add-in engine. Other add-ins which depend on the disabled add-in will /// also automatically be disabled. /// </remarks> public void DisableAddin (string id) { if (currentDomain == AddinDatabase.UnknownDomain) return; database.DisableAddin (currentDomain, id); } /// <summary> /// Registers a set of add-ins for uninstallation. /// </summary> /// <param name='id'> /// Identifier of the add-in /// </param> /// <param name='files'> /// Files to be uninstalled /// </param> /// <remarks> /// This method can be used to instruct the add-in manager to uninstall /// an add-in the next time the registry is updated. This is useful /// when an add-in manager can't delete an add-in because if it is /// loaded. /// </remarks> public void RegisterForUninstall (string id, IEnumerable<string> files) { database.RegisterForUninstall (currentDomain, id, files); } /// <summary> /// Determines whether an add-in is registered for uninstallation /// </summary> /// <returns> /// <c>true</c> if the add-in is registered for uninstallation /// </returns> /// <param name='addinId'> /// Identifier of the add-in /// </param> public bool IsRegisteredForUninstall (string addinId) { return database.IsRegisteredForUninstall (currentDomain, addinId); } /// <summary> /// Gets a value indicating whether there are pending add-ins to be uninstalled installed /// </summary> public bool HasPendingUninstalls { get { return database.HasPendingUninstalls (currentDomain); } } /// <summary> /// Internal use only /// </summary> public void DumpFile (string file) { Mono.Addins.Serialization.BinaryXmlReader.DumpFile (file); } /// <summary> /// Resets the configuration files of the registry /// </summary> public void ResetConfiguration () { database.ResetConfiguration (); } internal void NotifyDatabaseUpdated () { if (startupDirectory != null) currentDomain = database.GetFolderDomain (null, startupDirectory); } /// <summary> /// Updates the add-in registry. /// </summary> /// <remarks> /// This method must be called after modifying, installing or uninstalling add-ins. /// /// When calling Update, every add-in added to the registry is parsed and validated, /// and if there is any error it will be rejected. It will also cache add-in information /// needed at run-time. /// /// If during the update operation the registry finds new add-ins or detects that some /// add-ins have been deleted, the loaded extension points will be updated to include /// or exclude extension nodes from those add-ins. /// </remarks> public void Update () { Update (new ConsoleProgressStatus (false)); } /// <summary> /// Updates the add-in registry. /// </summary> /// <param name="monitor"> /// Progress monitor to keep track of the update operation. /// </param> /// <remarks> /// This method must be called after modifying, installing or uninstalling add-ins. /// /// When calling Update, every add-in added to the registry is parsed and validated, /// and if there is any error it will be rejected. It will also cache add-in information /// needed at run-time. /// /// If during the update operation the registry finds new add-ins or detects that some /// add-ins have been deleted, the loaded extension points will be updated to include /// or exclude extension nodes from those add-ins. /// </remarks> public void Update (IProgressStatus monitor) { database.Update (monitor, currentDomain); } /// <summary> /// Regenerates the cached data of the add-in registry. /// </summary> /// <param name="monitor"> /// Progress monitor to keep track of the rebuild operation. /// </param> public void Rebuild (IProgressStatus monitor) { database.Repair (monitor, currentDomain); // A full rebuild may cause the domain to change if (!string.IsNullOrEmpty (startupDirectory)) currentDomain = database.GetFolderDomain (null, startupDirectory); } /// <summary> /// Registers an extension. Only AddinFileSystemExtension extensions are supported right now. /// </summary> /// <param name='extension'> /// The extension to register /// </param> public void RegisterExtension (object extension) { database.RegisterExtension (extension); } /// <summary> /// Unregisters an extension. /// </summary> /// <param name='extension'> /// The extension to unregister /// </param> public void UnregisterExtension (object extension) { database.UnregisterExtension (extension); } internal void CopyExtensionsFrom (AddinRegistry other) { database.CopyExtensions (other.database); } internal Addin GetAddinForHostAssembly (string filePath) { if (currentDomain == AddinDatabase.UnknownDomain) return null; return database.GetAddinForHostAssembly (currentDomain, filePath); } internal bool AddinDependsOn (string id1, string id2) { return database.AddinDependsOn (currentDomain, id1, id2); } internal void ScanFolders (IProgressStatus monitor, string folderToScan, StringCollection filesToIgnore) { database.ScanFolders (monitor, currentDomain, folderToScan, filesToIgnore); } internal void ParseAddin (IProgressStatus progressStatus, string file, string outFile) { database.ParseAddin (progressStatus, currentDomain, file, outFile, true); } /// <summary> /// Gets the default add-ins folder of the registry. /// </summary> /// <remarks> /// For every add-in registry there is an add-in folder where the registry will look for add-ins by default. /// This folder is an "addins" subdirectory of the directory where the repository is located. In most cases, /// this folder will only contain .addins files referencing other more convenient locations for add-ins. /// </remarks> public string DefaultAddinsFolder { get { return addinsDir; } } internal string AddinCachePath { get { return databaseDir; } } internal StringCollection GlobalAddinDirectories { get { return addinDirs; } } internal string StartupDirectory { get { return startupDirectory; } } internal bool CreateHostAddinsFile (string hostFile) { hostFile = Path.GetFullPath (hostFile); string baseName = Path.GetFileNameWithoutExtension (hostFile); if (!Directory.Exists (database.HostsPath)) Directory.CreateDirectory (database.HostsPath); foreach (string s in Directory.GetFiles (database.HostsPath, baseName + "*.addins")) { try { using (StreamReader sr = new StreamReader (s)) { XmlTextReader tr = new XmlTextReader (sr); tr.MoveToContent (); string host = tr.GetAttribute ("host-reference"); if (host == hostFile) return false; } } catch { // Ignore this file } } string file = Path.Combine (database.HostsPath, baseName) + ".addins"; int n=1; while (File.Exists (file)) { file = Path.Combine (database.HostsPath, baseName) + "_" + n + ".addins"; n++; } using (StreamWriter sw = new StreamWriter (file)) { XmlTextWriter tw = new XmlTextWriter (sw); tw.Formatting = Formatting.Indented; tw.WriteStartElement ("Addins"); tw.WriteAttributeString ("host-reference", hostFile); tw.WriteStartElement ("Directory"); tw.WriteAttributeString ("shared", "false"); tw.WriteString (Path.GetDirectoryName (hostFile)); tw.WriteEndElement (); tw.Close (); } return true; } #pragma warning disable 1591 [Obsolete] public static string[] GetRegisteredStartupFolders (string registryPath) { string dbDir = Path.Combine (registryPath, "addin-db-" + AddinDatabase.VersionTag); dbDir = Path.Combine (dbDir, "hosts"); if (!Directory.Exists (dbDir)) return new string [0]; ArrayList dirs = new ArrayList (); foreach (string s in Directory.GetFiles (dbDir, "*.addins")) { try { using (StreamReader sr = new StreamReader (s)) { XmlTextReader tr = new XmlTextReader (sr); tr.MoveToContent (); string host = tr.GetAttribute ("host-reference"); host = Path.GetDirectoryName (host); if (!dirs.Contains (host)) dirs.Add (host); } } catch { // Ignore this file } } return (string[]) dirs.ToArray (typeof(string)); } #pragma warning restore 1591 } /// <summary> /// Addin search flags. /// </summary> [Flags] public enum AddinSearchFlags { /// <summary> /// Add-ins are included in the search /// </summary> IncludeAddins = 1, /// <summary> /// Add-in roots are included in the search /// </summary> IncludeRoots = 1 << 1, /// <summary> /// Both add-in and add-in roots are included in the search /// </summary> IncludeAll = IncludeAddins | IncludeRoots, /// <summary> /// Only the latest version of every add-in or add-in root is included in the search /// </summary> LatestVersionsOnly = 1 << 3 } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Text; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using Amazon.Runtime; using Amazon.Runtime.Internal.Util; using AWSSDK_DotNet.IntegrationTests.Utils; using System.Diagnostics; using Amazon.Util; namespace AWSSDK_DotNet.IntegrationTests.Tests.S3 { /// <summary> /// Summary description for PutObjectTest /// </summary> [TestClass] public class PutObjectTest : TestBase<AmazonS3Client> { public static readonly long MEG_SIZE = (int)Math.Pow(2, 20); private Random random = new Random(); private static string bucketName; private const string testContent = "This is the content body!"; [ClassInitialize()] public static void Initialize(TestContext a) { StreamWriter writer = File.CreateText("PutObjectFile.txt"); writer.Write("This is some sample text.!!"); writer.Close(); bucketName = S3TestUtils.CreateBucket(Client); } [ClassCleanup] public static void ClassCleanup() { AmazonS3Util.DeleteS3BucketWithObjects(Client, bucketName); BaseClean(); } [TestMethod] [TestCategory("S3")] public void TestStorageClass() { var key = "contentBodyPut" + random.Next(); var storageClass = S3StorageClass.ReducedRedundancy; PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = key, ContentBody = testContent, CannedACL = S3CannedACL.AuthenticatedRead, StorageClass = storageClass }; request.Metadata.Add("Subject", "Content-As-Object"); PutObjectResponse response = Client.PutObject(request); Console.WriteLine("S3 generated ETag: {0}", response.ETag); Assert.IsTrue(response.ETag.Length > 0); var metadata = Client.GetObjectMetadata(bucketName, key); Assert.IsNotNull(metadata); Assert.IsNotNull(metadata.StorageClass); Assert.AreEqual(metadata.StorageClass, storageClass); VerifyPut(testContent, request); } [TestMethod] [TestCategory("S3")] public void TestHttpErrorResponseUnmarshalling() { try { Client.PutObject(new PutObjectRequest { BucketName = UtilityMethods.GenerateName("NonExistentBucket"), Key = "1", ContentBody = "TestContent" }); } catch (AmazonS3Exception exception) { Console.WriteLine(exception.Message); Console.WriteLine(exception.ErrorCode); Console.WriteLine(exception.StatusCode); Assert.IsTrue(exception.Message.Contains("The specified bucket does not exist")); Assert.AreEqual("NoSuchBucket", exception.ErrorCode); Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode); } } #if ASYNC_AWAIT [TestMethod] [TestCategory("S3")] public async System.Threading.Tasks.Task PutObjectAsync() { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "contentBodyPut" + random.Next(), ContentBody = testContent, CannedACL = S3CannedACL.AuthenticatedRead }; PutObjectResponse response = await Client.PutObjectAsync(request); Console.WriteLine("S3 generated ETag: {0}", response.ETag); Assert.IsTrue(response.ETag.Length > 0); } [TestMethod] [TestCategory("S3")] public async System.Threading.Tasks.Task PutObjectCancellationTest() { var fileName = UtilityMethods.GenerateName(@"CancellationTest\LargeFile"); string basePath = @"c:\temp\test\"; var path = Path.Combine(basePath, fileName); UtilityMethods.GenerateFile(path, 50 * MEG_SIZE); var putObjectRequest = new PutObjectRequest { BucketName = bucketName, Key = "CancellationTest" + random.Next(), CannedACL = S3CannedACL.AuthenticatedRead, FilePath = path }; var cts = new CancellationTokenSource(); cts.CancelAfter(1000); var token = cts.Token; try { await Client.PutObjectAsync(putObjectRequest, token); } catch(OperationCanceledException exception) { Assert.AreEqual(token, exception.CancellationToken); Assert.AreEqual(true, exception.CancellationToken.IsCancellationRequested); return; } finally { Directory.Delete(basePath, true); } Assert.Fail("An OperationCanceledException was not thrown"); } #endif [TestMethod] [TestCategory("S3")] public void PutObjectWithExternalEndpoint() { var s3Client = new AmazonS3Client(new AmazonS3Config { ServiceURL = "https://s3-external-1.amazonaws.com", SignatureVersion = "4" }); var testBucketName = "testBucket" + random.Next(); var key = "testKey"; try { s3Client.PutBucket(testBucketName); s3Client.PutObject(new PutObjectRequest { BucketName = testBucketName, Key = key, ContentBody = "testValue" }); s3Client.GetObject(testBucketName, key); } finally { AmazonS3Util.DeleteS3BucketWithObjects(s3Client, testBucketName); s3Client.Dispose(); } } [TestMethod] [TestCategory("S3")] public void PutObjectWithLeadingSlash() { foreach(var useV4 in new bool[] { false, true }) { AWSConfigsS3.UseSignatureVersion4 = useV4; using(var client = new AmazonS3Client()) { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "/contentBodyPut" + random.Next(), ContentBody = "This is the content body!", CannedACL = S3CannedACL.AuthenticatedRead }; request.Metadata.Add("Subject", "Content-As-Object"); PutObjectResponse response = client.PutObject(request); Console.WriteLine("S3 generated ETag: {0}", response.ETag); Assert.IsTrue(response.ETag.Length > 0); } } } [TestMethod] [TestCategory("S3")] public void PutObject() { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "contentBodyPut" + random.Next(), ContentBody = testContent, CannedACL = S3CannedACL.AuthenticatedRead }; request.Metadata.Add("Subject", "Content-As-Object"); PutObjectResponse response = Client.PutObject(request); Console.WriteLine("S3 generated ETag: {0}", response.ETag); Assert.IsTrue(response.ETag.Length > 0); VerifyPut(testContent, request); } [TestMethod] [TestCategory("S3")] public void PutObject_SigV4() { var oldS3SigV4 = AWSConfigsS3.UseSignatureVersion4; AWSConfigsS3.UseSignatureVersion4 = true; try { using (var client = new AmazonS3Client()) { RetryUtilities.ConfigureClient(client); PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "contentBodyPut" + random.Next(), ContentBody = "This is the content body!", CannedACL = S3CannedACL.AuthenticatedRead }; request.Metadata.Add("Subject", "Content-As-Object"); PutObjectResponse response = client.PutObject(request); Console.WriteLine("S3 generated ETag: {0}", response.ETag); Assert.IsTrue(response.ETag.Length > 0); } } finally { AWSConfigsS3.UseSignatureVersion4 = oldS3SigV4; } } [TestMethod] [TestCategory("S3")] public void PutObject_WithExpires() { var key = "contentBodyPut" + random.Next(); var expires = DateTime.Now.AddYears(5); PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", CannedACL = S3CannedACL.AuthenticatedRead, }; request.Metadata.Add("Subject", "Content-As-Object"); request.Headers.Expires = expires; PutObjectResponse response = Client.PutObject(request); Console.WriteLine("S3 generated ETag: {0}", response.ETag); Assert.IsTrue(response.ETag.Length > 0); using (var getResponse = Client.GetObject(new GetObjectRequest { BucketName = bucketName, Key = key })) { Assert.IsTrue(expires.ApproximatelyEqual(getResponse.Expires)); } } [TestCategory("S3")] [TestMethod] public void PutObjectWeirdKeys() { var keys = new List<string> { "b204a53f-781a-4cdd-a29c-3626818eb199:115740.pdf", "46dbc16e-5f55-4bda-b275-75e2a8ab243c:115740.pdf" }; string filePath = "SomeFile.txt"; string contents = "Sample content"; File.WriteAllText(filePath, contents); foreach (var key in keys) { var request = new PutObjectRequest { BucketName = bucketName, Key = key, FilePath = filePath, }; Client.PutObject(request); using (var response = Client.GetObject(new GetObjectRequest { BucketName = bucketName, Key = key })) using (var reader = new StreamReader(response.ResponseStream)) { var rtContents = reader.ReadToEnd(); Assert.IsNotNull(rtContents); Assert.AreEqual(contents, rtContents); } } } [TestMethod] [TestCategory("S3")] public void PutObjectWithBacklashInKey() { const string writtenContent = @"an object with a \ in the key"; const string key = @"My\Key"; var request = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = writtenContent, }; Client.PutObject(request); using (var response = Client.GetObject(new GetObjectRequest { BucketName = bucketName, Key = key })) using (var reader = new StreamReader(response.ResponseStream)) { var readContent = reader.ReadToEnd(); Assert.AreEqual(readContent, writtenContent); } } [TestMethod] [TestCategory("S3")] public void PutObjectWrongRegion() { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "contentBodyPut" + random.Next(), ContentBody = "This is the content body!", CannedACL = S3CannedACL.AuthenticatedRead }; using (var client = new AmazonS3Client(RegionEndpoint.USWest2)) { // Returns an exception with HTTP 301 MovedPermanently var exception = AssertExtensions.ExpectException<AmazonS3Exception>(() => client.PutObject(request)); Assert.AreEqual("PermanentRedirect", exception.ErrorCode); Assert.AreEqual(HttpStatusCode.MovedPermanently, exception.StatusCode); Assert.IsFalse(string.IsNullOrEmpty(exception.Message)); Assert.IsFalse(string.IsNullOrEmpty(exception.RequestId)); Assert.IsFalse(string.IsNullOrEmpty(exception.AmazonId2)); } } [TestMethod] [TestCategory("S3")] public void GetObjectWithNonMatchingEtag() { var key = "TestMatchingEtag" + random.Next(); var request = new PutObjectRequest() { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", CannedACL = S3CannedACL.AuthenticatedRead }; Client.PutObject(request); var etag = Client.GetObject(new GetObjectRequest { BucketName = bucketName, Key = key }).ETag; // Returns an exception with HTTP 304 NotModified var exception = AssertExtensions.ExpectException<AmazonS3Exception>(() => Client.GetObject(new GetObjectRequest { BucketName = bucketName, Key = key, EtagToNotMatch = etag }) ); Assert.AreEqual("NotModified", exception.ErrorCode); Assert.AreEqual(HttpStatusCode.NotModified, exception.StatusCode); Assert.IsFalse(string.IsNullOrEmpty(exception.Message)); Assert.IsFalse(string.IsNullOrEmpty(exception.RequestId)); Assert.IsFalse(string.IsNullOrEmpty(exception.AmazonId2)); } [TestMethod] [TestCategory("S3")] public void TemporaryRedirectForS3OperationsWithSigV4() { AWSConfigsS3.UseSignatureVersion4 = true; TemporaryRedirectForS3Operations(); AWSConfigsS3.UseSignatureVersion4 = false; } [TestMethod] [TestCategory("S3")] public void TemporaryRedirectForS3Operations() { var testBucketName = UtilityMethods.GenerateName(UtilityMethods.SDK_TEST_PREFIX); using (var client = new AmazonS3Client()) { var bucket = client.PutBucket(new PutBucketRequest { BucketName = testBucketName, BucketRegion = S3Region.USW2 }); try { client.PutObject(new PutObjectRequest { BucketName = testBucketName, Key = "TestKey1", ContentBody = "sample text" }); client.PutObject(new PutObjectRequest { BucketName = testBucketName, Key = "TestKey2", InputStream = UtilityMethods.CreateStreamFromString("sample text") }); // Returns an exception with HTTP 307 TemporaryRedirect var exception = AssertExtensions.ExpectException<AmazonS3Exception>(() => client.PutObject(new PutObjectRequest { BucketName = testBucketName, Key = "TestKey3", InputStream = UtilityMethods.CreateStreamFromString("sample text", new NonRewindableStream()) }) ); Assert.AreEqual("TemporaryRedirect", exception.ErrorCode); Assert.AreEqual(HttpStatusCode.TemporaryRedirect, exception.StatusCode); Assert.IsFalse(string.IsNullOrEmpty(exception.Message)); Assert.IsFalse(string.IsNullOrEmpty(exception.RequestId)); Assert.IsFalse(string.IsNullOrEmpty(exception.AmazonId2)); var objects = client.ListObjects(new ListObjectsRequest { BucketName = testBucketName }).S3Objects; Assert.AreEqual(2, objects.Count); } finally { AmazonS3Util.DeleteS3BucketWithObjects(client, testBucketName); } } } [TestMethod] [TestCategory("S3")] public void DeleteNonExistentBucket() { // Returns an exception with HTTP 404 NotFound var exception = AssertExtensions.ExpectException<AmazonS3Exception>(() => Client.DeleteBucket(new DeleteBucketRequest { BucketName = "nonexistentbucket1234567890" }) ); Assert.AreEqual("NoSuchBucket", exception.ErrorCode); Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode); Assert.IsFalse(string.IsNullOrEmpty(exception.Message)); Assert.IsFalse(string.IsNullOrEmpty(exception.RequestId)); Assert.IsFalse(string.IsNullOrEmpty(exception.AmazonId2)); } [TestMethod] [TestCategory("S3")] public void PutObjectWithContentEncoding() { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "contentBodyPutWithEncoding" + random.Next(), ContentBody = "This is the content body!", CannedACL = S3CannedACL.AuthenticatedRead }; request.Headers.ContentEncoding = "gzip"; request.Headers.ContentDisposition = "disposition"; PutObjectResponse response = Client.PutObject(request); var getRequest = new GetObjectRequest() { BucketName = request.BucketName, Key = request.Key }; using (var getResponse = Client.GetObject(getRequest)) { Assert.AreEqual("disposition", getResponse.Headers.ContentDisposition); Assert.AreEqual("gzip", getResponse.Headers.ContentEncoding); } } [TestMethod] [TestCategory("S3")] public void PutEmptyFile() { string key = "contentBodyPut" + random.Next(); PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.Key = key; request.ContentBody = string.Empty; PutObjectResponse response = Client.PutObject(request); using (GetObjectResponse getResponse = Client.GetObject(new GetObjectRequest() { BucketName = bucketName, Key = key })) { Assert.AreEqual(0, getResponse.ContentLength); } } [TestMethod] [TestCategory("S3")] public void PutObjectLeaveStreamOpen() { string filepath = @"c:\temp\PutObjectLeaveStreamOpen.txt"; string key = "PutObjectLeaveStreamOpen" + random.Next(); writeContent(@"c:\temp", "PutObjectLeaveStreamOpen.txt", "abcdefghighfsldfsdfn"); try { Stream stream = File.OpenRead(filepath); PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.Key = key; request.InputStream = stream; Client.PutObject(request); Assert.IsFalse(stream.CanSeek, "Stream should be closed and seek should not be allowed"); stream = File.OpenRead(filepath); request = new PutObjectRequest(); request.BucketName = bucketName; request.Key = key; request.AutoCloseStream = false; request.InputStream = stream; Client.PutObject(request); Assert.IsTrue(stream.CanSeek, "Stream should still be open and seek should be allowed"); stream.Close(); } finally { File.Delete(filepath); try { Client.DeleteObject(new DeleteObjectRequest() { BucketName = bucketName, Key = key }); } catch { } } } private void writeContent(string directory, string fileName, string content) { if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); StreamWriter writer = new StreamWriter(directory + "/" + fileName); writer.Write(content); writer.Close(); } [TestMethod] [TestCategory("S3")] [ExpectedException(typeof(ArgumentException))] public void PutObject_ContentAndFile() { PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.Key = "PutObjectTest"; request.ContentBody = "CAT"; request.FilePath = "PutObjectFile.txt"; try { Client.PutObject(request); } catch (ArgumentException ex) { Assert.AreEqual<string>("Please specify one of either a FilePath or the ContentBody to be PUT as an S3 object.", ex.Message); Console.WriteLine(ex.ToString()); throw ex; } } [TestMethod] [TestCategory("S3")] [ExpectedException(typeof(ArgumentException), "Please specify one of either an InputStream or the ContentBody to be PUT as an S3 object.")] public void PutObject_ContentAndStream() { PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.Key = "PutObjectTest"; request.ContentBody = "CAT"; using (FileStream fStream = new FileStream("PutObjectFile.txt", FileMode.Open)) { request.InputStream = fStream; try { Client.PutObject(request); } catch (ArgumentException ex) { Assert.AreEqual<string>("Please specify one of either an InputStream or the ContentBody to be PUT as an S3 object.", ex.Message); Console.WriteLine(ex.ToString()); throw ex; } } } [TestMethod] [TestCategory("S3")] [ExpectedException(typeof(ArgumentException), "Please specify one of either an Input FileStream or a Filename to be PUT as an S3 object.")] public void PutObject_StreamAndFile() { PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.Key = "PutObjectTest"; using (FileStream fStream = new FileStream("PutObjectFile.txt", FileMode.Open)) { request.InputStream = fStream; request.FilePath = "PutObjectFile.txt"; try { Client.PutObject(request); } catch (ArgumentException ex) { Assert.AreEqual<string>("Please specify one of either an InputStream or a FilePath to be PUT as an S3 object.", ex.Message); Console.WriteLine(ex.ToString()); throw ex; } } } [TestMethod] [TestCategory("S3")] public void PutObject_KeyFromPath() { string path = "PutObjectFile.txt"; TestKeyFromPath(path); string fullPath = Path.GetFullPath(path); TestKeyFromPath(fullPath); string fullPathUnix = fullPath.Replace('\\', '/'); TestKeyFromPath(fullPathUnix); } private void TestKeyFromPath(string path) { PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.FilePath = path; Client.PutObject(request); string key = Path.GetFileName(path); var metadataRequest = new GetObjectMetadataRequest { BucketName = bucketName, Key = key }; var metadata = Client.GetObjectMetadata(metadataRequest); Assert.IsNotNull(metadata); Assert.IsTrue(metadata.ContentLength > 0); Client.DeleteObject(new DeleteObjectRequest { BucketName = bucketName, Key = key }); AssertExtensions.ExpectException(() => Client.GetObjectMetadata(metadataRequest)); } [TestMethod] [TestCategory("S3")] public void PutObject_FileNameOnly() { PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.FilePath = "PutObjectFile.txt"; Client.PutObject(request); } [TestMethod] [TestCategory("S3")] [ExpectedException(typeof(FileNotFoundException))] public void PutObject_FileNameNotExist() { PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.FilePath = "FileThatDoesntExist"; try { Client.PutObject(request); } catch (FileNotFoundException ex) { Console.WriteLine(ex.ToString()); throw ex; } } [TestMethod] [TestCategory("S3")] public void PutObject_StreamChecksumEnabled() { PutObjectRequest request = new PutObjectRequest(); request.BucketName = bucketName; request.Key = "PutObjectStreamChecksum" + random.Next(); using (FileStream fStream = new FileStream("PutObjectFile.txt", FileMode.Open)) { request.InputStream = fStream; Client.PutObject(request); } } [TestMethod] [TestCategory("S3")] public void PutObjectWithACL() { PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "putobjectwithacl", ContentBody = "Some Random Nonsense", Grants = new List<S3Grant>() { //new S3Grant(){Grantee = new S3Grantee(){EmailAddress = "pavel@amazon.com"}, Permission = S3Permission.FULL_CONTROL}, //new S3Grant(){Grantee = new S3Grantee(){EmailAddress = "aws-dr-tools-test@amazon.com"}, Permission = S3Permission.FULL_CONTROL}, new S3Grant(){Grantee = new S3Grantee(){URI = "http://acs.amazonaws.com/groups/global/AllUsers"}, Permission = S3Permission.READ}, new S3Grant(){Grantee = new S3Grantee { URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"}, Permission = S3Permission.READ} } }; Client.PutObject(request); var acl = Client.GetACL(new GetACLRequest() { BucketName = bucketName, Key = "putobjectwithacl" }).AccessControlList; Assert.AreEqual(2, acl.Grants.Count); foreach (var grant in acl.Grants) { var grantee = grant.Grantee; Console.WriteLine("Grantee:"); if (!string.IsNullOrEmpty(grantee.URI)) Console.WriteLine("Uri: {0}", grantee.URI); if (!string.IsNullOrEmpty(grantee.EmailAddress)) Console.WriteLine("Email: {0}", grantee.EmailAddress); if (grantee.CanonicalUser != null && !string.IsNullOrEmpty(grantee.CanonicalUser)) Console.WriteLine("Canonical user: {0}", grantee.CanonicalUser); Console.WriteLine("Permissions: {0}", grant.Permission.ToString()); } Client.PutACL(new PutACLRequest { BucketName = bucketName, Key = "putobjectwithacl", AccessControlList = new S3AccessControlList { Grants = new List<S3Grant> { new S3Grant { Grantee = new S3Grantee { URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" }, Permission = S3Permission.READ } }, Owner = acl.Owner }, }); Thread.Sleep(1000); acl = Client.GetACL(new GetACLRequest() { BucketName = bucketName, Key = "putobjectwithacl" }).AccessControlList; Assert.AreEqual(1, acl.Grants.Count); } [TestMethod] [TestCategory("S3")] public void PutBucketWithCannedACL() { string aclBucketName = "dotnet-integtests-cannedacl" + DateTime.Now.Ticks; PutBucketRequest request = new PutBucketRequest() { BucketName = aclBucketName, CannedACL = S3CannedACL.LogDeliveryWrite }; Client.PutBucket(request); var acl = Client.GetACL(new GetACLRequest() { BucketName = aclBucketName }).AccessControlList; Client.DeleteBucket(new DeleteBucketRequest() { BucketName = aclBucketName }); // should only have seen grants for full_control to test owner, LogDelivery read_acp and LogDelivery write Assert.AreEqual(3, acl.Grants.Count); foreach (var grant in acl.Grants) { if (!string.IsNullOrEmpty(grant.Grantee.DisplayName)) { Assert.IsNotNull(grant.Grantee.DisplayName); Assert.AreEqual<S3Permission>(S3Permission.FULL_CONTROL, grant.Permission); } else if (!string.IsNullOrEmpty(grant.Grantee.CanonicalUser)) { Assert.IsNotNull(grant.Grantee.CanonicalUser); Assert.AreEqual<S3Permission>(S3Permission.FULL_CONTROL, grant.Permission); } else { Assert.AreEqual<string>("http://acs.amazonaws.com/groups/s3/LogDelivery", grant.Grantee.URI); Assert.IsTrue(grant.Permission == S3Permission.READ_ACP || grant.Permission == S3Permission.WRITE); } } } [TestMethod] [TestCategory("S3")] public void PutObjectWithContentLength() { string sourceKey = "source"; string destKey = "dest"; string contents = "Sample contents"; int length = contents.Length; Client.PutObject(new PutObjectRequest { BucketName = bucketName, Key = sourceKey, ContentBody = contents }); // Disable clock skew testing when generating a presigned url using (RetryUtilities.DisableClockSkewCorrection()) { string url = Client.GetPreSignedURL(new GetPreSignedUrlRequest { BucketName = bucketName, Key = sourceKey, Expires = DateTime.Now + TimeSpan.FromHours(2) }); HttpWebRequest httpRequest = HttpWebRequest.Create(url) as HttpWebRequest; using (HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse) using (Stream stream = httpResponse.GetResponseStream()) { PutStream(destKey, length, stream); } string finalContents = GetContents(destKey); Assert.AreEqual(contents, finalContents); length -= 2; httpRequest = HttpWebRequest.Create(url) as HttpWebRequest; using (HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse) using (Stream stream = httpResponse.GetResponseStream()) { PutStream(destKey, length, stream); } finalContents = GetContents(destKey); Assert.AreEqual(contents.Substring(0, length), finalContents); } } private void PutStream(string destKey, int length, Stream stream) { PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = destKey, InputStream = stream, }; request.Headers.ContentLength = length; using (RetryUtilities.DisableClockSkewCorrection()) { Client.PutObject(request); } } private string GetContents(string key) { Stream stream = Client.GetObject(new GetObjectRequest { BucketName = bucketName, Key = key }).ResponseStream; using (stream) { using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } [TestMethod] [TestCategory("S3")] public void TestStreamRetry() { var s3ClientBufferSize = new AmazonS3Config().BufferSize; var chunkedWrapperBufferSize = ChunkedUploadWrapperStream.DefaultChunkSize; var sizeForFailWithoutWriting = 0; var sizeForFailWithSomeWriting = chunkedWrapperBufferSize * 2; var arbitrarySizeForSuccess = s3ClientBufferSize * 2; var runs = 3; var exceptions = new List<Exception>(); for (int i = 0; i < runs; i++) { exceptions.Add(TryTest(sizeForFailWithoutWriting, failRequest: true)); exceptions.Add(TryTest(sizeForFailWithSomeWriting, failRequest: true)); exceptions.Add(TryTest(arbitrarySizeForSuccess, failRequest: false)); } exceptions = exceptions.Where(e => e != null).ToList(); if (exceptions.Count > 0) #if ASYNC_AWAIT throw new AggregateException(exceptions); #else throw exceptions.First(); #endif } private static Exception TryTest(int errorSize, bool failRequest) { try { Test(errorSize, failRequest); return null; } catch(Exception e) { return e; } } private static void Test(int errorSize, bool failRequest) { var actualSize = errorSize + 128; //var data = new string('@', actualSize + bufferSize); //byte[] bytes = Encoding.UTF8.GetBytes(data); var bytes = CreateData(actualSize); // must precompute this and set in headers to avoid hash computation on ErrorStream // affecting the test var payloadhash = UtilityMethods.ToHex(UtilityMethods.ComputeSHA256(bytes), true); ErrorStream es = ErrorStream.Create(bytes); if (failRequest) es.MaxReadBytes = errorSize; // 1 rewind for S3 pre-marshallers which reset position to 0 // 1 rewind for exception at error size es.MinRewinds = 2; var putRequest = new PutObjectRequest { BucketName = bucketName, Key = "foo1", AutoCloseStream = false }; putRequest.Headers["x-amz-content-sha256"] = payloadhash; putRequest.InputStream = es; CallWithTimeout(() => Client.PutObject(putRequest), TimeSpan.FromSeconds(10)); } static void CallWithTimeout(Action action, TimeSpan timeout) { if (System.Diagnostics.Debugger.IsAttached) { action(); return; } Thread threadToKill = null; Action wrappedAction = () => { threadToKill = Thread.CurrentThread; action(); }; IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeout)) { wrappedAction.EndInvoke(result); } else { threadToKill.Abort(); throw new TimeoutException(); } } private static byte[] CreateData(int size) { var data = new byte[size]; for(int i=0;i<size;i++) { var c = (i % 26) + 'a'; data[i] = (byte)c; } return data; } private static void VerifyPut(string data, PutObjectRequest putRequest) { var getRequest = new GetObjectRequest { BucketName = bucketName, Key = putRequest.Key }; string responseData; using (var response = Client.GetObject(getRequest)) using (var responseStream = response.ResponseStream) using (StreamReader reader = new StreamReader(responseStream)) { responseData = reader.ReadToEnd(); Assert.AreEqual(data, responseData); if (putRequest.StorageClass != null && putRequest.StorageClass != S3StorageClass.Standard) { Assert.IsNotNull(response.StorageClass); Assert.AreEqual(response.StorageClass, putRequest.StorageClass); } } } [TestMethod] [TestCategory("S3")] public void TestResetStreamPosition() { MemoryStream stream = new MemoryStream(); for (int i = 0; i < 10; i++) { stream.WriteByte((byte)i); } Assert.AreEqual(stream.Position, stream.Length); PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "thestream", InputStream = stream, AutoCloseStream = false }; Client.PutObject(request); var getObjectRequest = new GetObjectRequest { BucketName = bucketName, Key = "thestream" }; for (int retries = 0; retries < 5; retries++) { Thread.Sleep(1000 * retries); try { using (var getObjectResponse = Client.GetObject(getObjectRequest)) { Assert.AreEqual(stream.Length, getObjectResponse.ContentLength); } break; } catch (AmazonServiceException e) { if (e.StatusCode != HttpStatusCode.NotFound || retries == 5) throw; } } stream.Seek(5, SeekOrigin.Begin); request.InputStream = stream; request.AutoResetStreamPosition = false; Client.PutObject(request); using (var getObjectResponse = Client.GetObject(getObjectRequest)) { Assert.AreEqual(stream.Length - 5, getObjectResponse.ContentLength); } } private class ErrorStream : WrapperStream { private ErrorStream(Stream stream) : base(stream) { MaxReadBytes = -1; MinRewinds = -1; } public static ErrorStream Create(byte[] bytes, bool readOnly = false) { long length = -1; Stream stream; if (readOnly) { var compressedStream = new MemoryStream(Compress(bytes)); stream = new GZipStream(compressedStream, CompressionMode.Decompress); length = compressedStream.Length; } else { stream = new MemoryStream(bytes); } return new ErrorStream(stream); } private static byte[] Compress(byte[] bytes) { MemoryStream dataStream; using (dataStream = new MemoryStream()) using (GZipStream compress = new GZipStream(dataStream, CompressionMode.Compress)) { compress.Write(bytes, 0, bytes.Length); } var compressedData = dataStream.ToArray(); return compressedData; } public int MaxReadBytes { get; set; } public int MinRewinds { get; set; } public event EventHandler OnRead; public int TotalReadBytes { get; private set; } public int Rewinds { get; private set; } public override int Read(byte[] buffer, int offset, int count) { if (OnRead != null) OnRead(this, null); var readCount = base.Read(buffer, offset, count); TotalReadBytes += readCount; bool throwBasedOnReadBytes = MaxReadBytes >= 0 && TotalReadBytes >= MaxReadBytes; bool suppressThrowBasedOnRewinds = MinRewinds >= 0 && Rewinds >= MinRewinds; if (throwBasedOnReadBytes && !suppressThrowBasedOnRewinds) throw new IOException("Fake Exception"); return readCount; } public override long Seek(long offset, SeekOrigin origin) { var value = base.Seek(offset, origin); TotalReadBytes = 0; Rewinds++; return value; } public override long Position { get { return base.Position; } set { this.Seek(value, SeekOrigin.Begin); } } } } public class NonRewindableStream : MemoryStream { public override bool CanSeek { get { return false; } } } }
using System.Collections.Generic; using GitTools.Testing; using GitVersion.Core.Tests.Helpers; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using LibGit2Sharp; using NUnit.Framework; namespace GitVersion.Core.Tests.IntegrationTests { [TestFixture] public class DevelopScenarios : TestBase { [Test] public void WhenDevelopHasMultipleCommitsSpecifyExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); var thirdCommit = fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.3", commitId: thirdCommit.Sha); } [Test] public void WhenDevelopHasMultipleCommitsSpecifyNonExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.5", commitId: "nonexistingcommitid"); } [Test] public void WhenDevelopBranchedFromTaggedCommitOnMainVersionDoesNotChange() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.AssertFullSemver("1.0.0"); } [Test] public void CanChangeDevelopTagViaConfig() { var config = new Config { Branches = { { "develop", new BranchConfig { Tag = "alpha", SourceBranches = new HashSet<string>() } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1", config); } [Test] public void WhenDeveloperBranchExistsDontTreatAsDevelop() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("developer")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.0.1-developer.1+1"); // this tag should be the branch name by default, not unstable } [Test] public void WhenDevelopBranchedFromMainMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); } [Test] public void MergingReleaseBranchBackIntoDevelopWithMergingToMainDoesBumpDevelopVersion() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("release-2.0.0")); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, MainBranch); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.1.0-alpha.2"); } [Test] public void CanHandleContinuousDelivery() { var config = new Config { Branches = { { "develop", new BranchConfig { VersioningMode = VersioningMode.ContinuousDelivery } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeATaggedCommit("1.1.0-alpha7"); fixture.AssertFullSemver("1.1.0-alpha.7", config); } [Test] public void WhenDevelopBranchedFromMainDetachedHeadMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); var commit = fixture.Repository.Head.Tip; fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, commit); fixture.AssertFullSemver("1.1.0-alpha.1", onlyTrackedBranches: false); } [Test] public void InheritVersionFromReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.MakeATaggedCommit("1.0.0"); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/2.0.0"); fixture.MakeACommit(); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.AssertFullSemver("1.1.0-alpha.1"); fixture.MakeACommit(); fixture.AssertFullSemver("2.1.0-alpha.1"); fixture.MergeNoFF("release/2.0.0"); fixture.AssertFullSemver("2.1.0-alpha.4"); fixture.BranchTo("feature/MyFeature"); fixture.MakeACommit(); fixture.AssertFullSemver("2.1.0-MyFeature.1+5"); } [Test] public void WhenMultipleDevelopBranchesExistAndCurrentBranchHasIncrementInheritPolicyAndCurrentCommitIsAMerge() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("bob_develop"); fixture.Repository.CreateBranch("develop"); fixture.Repository.CreateBranch("feature/x"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "feature/x"); fixture.Repository.MakeACommit(); fixture.Repository.MergeNoFF("develop"); fixture.AssertFullSemver("1.1.0-x.1+3"); } [Test] public void TagOnHotfixShouldNotAffectDevelop() { using var fixture = new BaseGitFlowRepositoryFixture("1.2.0"); Commands.Checkout(fixture.Repository, MainBranch); var hotfix = fixture.Repository.CreateBranch("hotfix-1.2.1"); Commands.Checkout(fixture.Repository, hotfix); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.2.1-beta.1+1"); fixture.Repository.ApplyTag("1.2.1-beta.1"); fixture.AssertFullSemver("1.2.1-beta.1"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.3.0-alpha.2"); } [Test] public void CommitsSinceVersionSourceShouldNotGoDownUponGitFlowReleaseFinish() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.ApplyTag("1.1.0"); fixture.BranchTo("develop"); fixture.MakeACommit("commit in develop - 1"); fixture.AssertFullSemver("1.2.0-alpha.1"); fixture.BranchTo("release/1.2.0"); fixture.AssertFullSemver("1.2.0-beta.1+0"); fixture.Checkout("develop"); fixture.MakeACommit("commit in develop - 2"); fixture.MakeACommit("commit in develop - 3"); fixture.MakeACommit("commit in develop - 4"); fixture.MakeACommit("commit in develop - 5"); fixture.AssertFullSemver("1.3.0-alpha.4"); fixture.Checkout("release/1.2.0"); fixture.MakeACommit("commit in release/1.2.0 - 1"); fixture.MakeACommit("commit in release/1.2.0 - 2"); fixture.MakeACommit("commit in release/1.2.0 - 3"); fixture.AssertFullSemver("1.2.0-beta.1+3"); fixture.Checkout(MainBranch); fixture.MergeNoFF("release/1.2.0"); fixture.ApplyTag("1.2.0"); fixture.Checkout("develop"); fixture.MergeNoFF("release/1.2.0"); fixture.MakeACommit("commit in develop - 6"); fixture.AssertFullSemver("1.3.0-alpha.9"); fixture.SequenceDiagram.Destroy("release/1.2.0"); fixture.Repository.Branches.Remove("release/1.2.0"); var expectedFullSemVer = "1.3.0-alpha.9"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void CommitsSinceVersionSourceShouldNotGoDownUponMergingFeatureOnlyToDevelop() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit($"commit in {MainBranch} - 1"); fixture.ApplyTag("1.1.0"); fixture.BranchTo("develop"); fixture.MakeACommit("commit in develop - 1"); fixture.AssertFullSemver("1.2.0-alpha.1"); fixture.BranchTo("release/1.2.0"); fixture.MakeACommit("commit in release - 1"); fixture.MakeACommit("commit in release - 2"); fixture.MakeACommit("commit in release - 3"); fixture.AssertFullSemver("1.2.0-beta.1+3"); fixture.ApplyTag("1.2.0"); fixture.Checkout("develop"); fixture.MakeACommit("commit in develop - 2"); fixture.AssertFullSemver("1.3.0-alpha.1"); fixture.MergeNoFF("release/1.2.0"); fixture.AssertFullSemver("1.3.0-alpha.5"); fixture.SequenceDiagram.Destroy("release/1.2.0"); fixture.Repository.Branches.Remove("release/1.2.0"); var expectedFullSemVer = "1.3.0-alpha.5"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void PreviousPreReleaseTagShouldBeRespectedWhenCountingCommits() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeATaggedCommit("1.0.0-alpha.3"); // manual bump version fixture.MakeACommit(); fixture.MakeACommit(); fixture.AssertFullSemver("1.0.0-alpha.5"); } [Test] public void WhenPreventIncrementOfMergedBranchVersionIsSetToFalseForDevelopCommitsSinceVersionSourceShouldNotGoDownWhenMergingReleaseToDevelop() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment, Branches = new Dictionary<string, BranchConfig> { { "develop", new BranchConfig { PreventIncrementOfMergedBranchVersion = false } }, } }; using var fixture = new EmptyRepositoryFixture(); const string ReleaseBranch = "release/1.1.0"; fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeATaggedCommit("1.0.0"); fixture.Repository.MakeCommits(1); // Create a release branch and make some commits fixture.BranchTo(ReleaseBranch); fixture.Repository.MakeCommits(3); // Simulate a GitFlow release finish. fixture.Checkout(MainBranch); fixture.MergeNoFF(ReleaseBranch); fixture.ApplyTag("v1.1.0"); fixture.Checkout("develop"); // Simulate some work done on develop while the release branch was open. fixture.Repository.MakeCommits(2); fixture.MergeNoFF(ReleaseBranch); // Version numbers will still be correct when the release branch is around. fixture.AssertFullSemver("1.2.0-alpha.6"); fixture.AssertFullSemver("1.2.0-alpha.6", config); var versionSourceBeforeReleaseBranchIsRemoved = fixture.GetVersion(config).Sha; fixture.Repository.Branches.Remove(ReleaseBranch); var versionSourceAfterReleaseBranchIsRemoved = fixture.GetVersion(config).Sha; Assert.AreEqual(versionSourceBeforeReleaseBranchIsRemoved, versionSourceAfterReleaseBranchIsRemoved); fixture.AssertFullSemver("1.2.0-alpha.6"); fixture.AssertFullSemver("1.2.0-alpha.6", config); config.Branches = new Dictionary<string, BranchConfig> { { "develop", new BranchConfig { PreventIncrementOfMergedBranchVersion = true } }, }; fixture.AssertFullSemver("1.2.0-alpha.3", config); } [Test] public void WhenPreventIncrementOfMergedBranchVersionIsSetToFalseForDevelopCommitsSinceVersionSourceShouldNotGoDownWhenMergingHotfixToDevelop() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment, Branches = new Dictionary<string, BranchConfig> { { "develop", new BranchConfig { PreventIncrementOfMergedBranchVersion = false } }, { "hotfix", new BranchConfig { PreventIncrementOfMergedBranchVersion = true, Regex = "^(origin/)?hotfix[/-]" } }, } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeATaggedCommit("1.0.0"); fixture.Repository.MakeCommits(1); fixture.Checkout("develop"); fixture.Repository.MakeCommits(3); fixture.AssertFullSemver("1.1.0-alpha.4", config); const string ReleaseBranch = "release/1.1.0"; Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch(ReleaseBranch)); fixture.Repository.MakeCommits(3); fixture.AssertFullSemver("1.1.0-beta.3", config); // Simulate a GitFlow release finish. fixture.Checkout(MainBranch); fixture.MergeNoFF(ReleaseBranch); fixture.ApplyTag("v1.1.0"); fixture.Checkout("develop"); // Simulate some work done on develop while the release branch was open. fixture.Repository.MakeCommits(2); fixture.MergeNoFF(ReleaseBranch); fixture.Repository.Branches.Remove(ReleaseBranch); fixture.AssertFullSemver("1.2.0-alpha.6", config); // Create hotfix for defects found in release/1.1.0 const string HotfixBranch = "hotfix/1.1.1"; fixture.Checkout(MainBranch); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch(HotfixBranch)); fixture.Repository.MakeCommits(3); // Hotfix finish fixture.Checkout(MainBranch); fixture.Repository.MergeNoFF(HotfixBranch); fixture.Repository.ApplyTag("v1.1.1"); // Verify develop version fixture.Checkout("develop"); // Simulate some work done on develop while the hotfix branch was open. fixture.Repository.MakeCommits(3); fixture.AssertFullSemver("1.2.0-alpha.9", config); fixture.Repository.MergeNoFF(HotfixBranch); fixture.AssertFullSemver("1.2.0-alpha.19", config); fixture.Repository.Branches.Remove(HotfixBranch); fixture.AssertFullSemver("1.2.0-alpha.19", config); } } }
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; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmMainHOParam { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmMainHOParam() : base() { FormClosed += frmMainHOParam_FormClosed; KeyPress += frmMainHOParam_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.CheckBox _chkBit_6; public System.Windows.Forms.CheckBox _chkBit_5; public System.Windows.Forms.CheckBox _chkBit_1; public System.Windows.Forms.CheckBox _chkBit_2; public System.Windows.Forms.CheckBox _chkBit_3; public System.Windows.Forms.CheckBox _chkBit_4; private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } public System.Windows.Forms.Button cmdClearLock; private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _lbl_2; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_3; //Public WithEvents chkBit As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMainHOParam)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this._chkBit_6 = new System.Windows.Forms.CheckBox(); this._chkBit_5 = new System.Windows.Forms.CheckBox(); this._chkBit_1 = new System.Windows.Forms.CheckBox(); this._chkBit_2 = new System.Windows.Forms.CheckBox(); this._chkBit_3 = new System.Windows.Forms.CheckBox(); this._chkBit_4 = new System.Windows.Forms.CheckBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClearLock = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this._lbl_2 = new System.Windows.Forms.Label(); this._Shape1_3 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); //Me.chkBit = New Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.Shape1 = new RectangleShapeArray(components); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.chkBit, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "4POS HeadOffice Sync - Parameters"; this.ClientSize = new System.Drawing.Size(271, 189); this.Location = new System.Drawing.Point(3, 29); this.ControlBox = false; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.KeyPreview = false; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmMainHOParam"; this._chkBit_6.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkBit_6.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkBit_6.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkBit_6.Text = "Ignore Bill of Material / Recipe"; this._chkBit_6.ForeColor = System.Drawing.SystemColors.WindowText; this._chkBit_6.Size = new System.Drawing.Size(242, 15); this._chkBit_6.Location = new System.Drawing.Point(16, 160); this._chkBit_6.TabIndex = 10; this._chkBit_6.CausesValidation = true; this._chkBit_6.Enabled = true; this._chkBit_6.Cursor = System.Windows.Forms.Cursors.Default; this._chkBit_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkBit_6.Appearance = System.Windows.Forms.Appearance.Normal; this._chkBit_6.TabStop = true; this._chkBit_6.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkBit_6.Visible = true; this._chkBit_6.Name = "_chkBit_6"; this._chkBit_5.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkBit_5.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkBit_5.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkBit_5.Text = "Overwrite Promotion"; this._chkBit_5.ForeColor = System.Drawing.SystemColors.WindowText; this._chkBit_5.Size = new System.Drawing.Size(242, 15); this._chkBit_5.Location = new System.Drawing.Point(16, 142); this._chkBit_5.TabIndex = 9; this._chkBit_5.CausesValidation = true; this._chkBit_5.Enabled = true; this._chkBit_5.Cursor = System.Windows.Forms.Cursors.Default; this._chkBit_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkBit_5.Appearance = System.Windows.Forms.Appearance.Normal; this._chkBit_5.TabStop = true; this._chkBit_5.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkBit_5.Visible = true; this._chkBit_5.Name = "_chkBit_5"; this._chkBit_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkBit_1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkBit_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkBit_1.Text = "Update Re-order level"; this._chkBit_1.ForeColor = System.Drawing.SystemColors.WindowText; this._chkBit_1.Size = new System.Drawing.Size(242, 15); this._chkBit_1.Location = new System.Drawing.Point(16, 59); this._chkBit_1.TabIndex = 6; this._chkBit_1.CausesValidation = true; this._chkBit_1.Enabled = true; this._chkBit_1.Cursor = System.Windows.Forms.Cursors.Default; this._chkBit_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkBit_1.Appearance = System.Windows.Forms.Appearance.Normal; this._chkBit_1.TabStop = true; this._chkBit_1.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkBit_1.Visible = true; this._chkBit_1.Name = "_chkBit_1"; this._chkBit_2.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkBit_2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkBit_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkBit_2.Text = "Overwrite Employee information"; this._chkBit_2.ForeColor = System.Drawing.SystemColors.WindowText; this._chkBit_2.Size = new System.Drawing.Size(242, 15); this._chkBit_2.Location = new System.Drawing.Point(16, 79); this._chkBit_2.TabIndex = 5; this._chkBit_2.CausesValidation = true; this._chkBit_2.Enabled = true; this._chkBit_2.Cursor = System.Windows.Forms.Cursors.Default; this._chkBit_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkBit_2.Appearance = System.Windows.Forms.Appearance.Normal; this._chkBit_2.TabStop = true; this._chkBit_2.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkBit_2.Visible = true; this._chkBit_2.Name = "_chkBit_2"; this._chkBit_3.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkBit_3.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkBit_3.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkBit_3.Text = "Update Item Counter for Waitron"; this._chkBit_3.ForeColor = System.Drawing.SystemColors.WindowText; this._chkBit_3.Size = new System.Drawing.Size(242, 15); this._chkBit_3.Location = new System.Drawing.Point(16, 99); this._chkBit_3.TabIndex = 4; this._chkBit_3.CausesValidation = true; this._chkBit_3.Enabled = true; this._chkBit_3.Cursor = System.Windows.Forms.Cursors.Default; this._chkBit_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkBit_3.Appearance = System.Windows.Forms.Appearance.Normal; this._chkBit_3.TabStop = true; this._chkBit_3.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkBit_3.Visible = true; this._chkBit_3.Name = "_chkBit_3"; this._chkBit_4.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkBit_4.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkBit_4.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkBit_4.Text = "Update Actual Cost"; this._chkBit_4.ForeColor = System.Drawing.SystemColors.WindowText; this._chkBit_4.Size = new System.Drawing.Size(242, 15); this._chkBit_4.Location = new System.Drawing.Point(16, 120); this._chkBit_4.TabIndex = 3; this._chkBit_4.CausesValidation = true; this._chkBit_4.Enabled = true; this._chkBit_4.Cursor = System.Windows.Forms.Cursors.Default; this._chkBit_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkBit_4.Appearance = System.Windows.Forms.Appearance.Normal; this._chkBit_4.TabStop = true; this._chkBit_4.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkBit_4.Visible = true; this._chkBit_4.Name = "_chkBit_4"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(271, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 0; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(8, 4); this.cmdCancel.TabIndex = 8; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; this.cmdClearLock.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClearLock.Text = "Clear Log"; this.cmdClearLock.Size = new System.Drawing.Size(73, 29); this.cmdClearLock.Location = new System.Drawing.Point(552, 4); this.cmdClearLock.TabIndex = 2; this.cmdClearLock.TabStop = false; this.cmdClearLock.BackColor = System.Drawing.SystemColors.Control; this.cmdClearLock.CausesValidation = true; this.cmdClearLock.Enabled = true; this.cmdClearLock.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClearLock.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClearLock.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClearLock.Name = "cmdClearLock"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(184, 4); this.cmdClose.TabIndex = 1; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Text = "1. 4POS HeadOffice Sync - Parameters"; this._lbl_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_2.Size = new System.Drawing.Size(206, 14); this._lbl_2.Location = new System.Drawing.Point(8, 40); this._lbl_2.TabIndex = 7; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = true; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this._Shape1_3.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_3.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_3.Size = new System.Drawing.Size(254, 125); this._Shape1_3.Location = new System.Drawing.Point(8, 55); this._Shape1_3.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_3.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_3.BorderWidth = 1; this._Shape1_3.FillColor = System.Drawing.Color.Black; this._Shape1_3.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_3.Visible = true; this._Shape1_3.Name = "_Shape1_3"; this.Controls.Add(_chkBit_6); this.Controls.Add(_chkBit_5); this.Controls.Add(_chkBit_1); this.Controls.Add(_chkBit_2); this.Controls.Add(_chkBit_3); this.Controls.Add(_chkBit_4); this.Controls.Add(picButtons); this.Controls.Add(_lbl_2); this.ShapeContainer1.Shapes.Add(_Shape1_3); this.Controls.Add(ShapeContainer1); this.picButtons.Controls.Add(cmdCancel); this.picButtons.Controls.Add(cmdClearLock); this.picButtons.Controls.Add(cmdClose); //Me.chkBit.SetIndex(_chkBit_6, CType(6, Short)) //Me.chkBit.SetIndex(_chkBit_5, CType(5, Short)) //Me.chkBit.SetIndex(_chkBit_1, CType(1, Short)) //Me.chkBit.SetIndex(_chkBit_2, CType(2, Short)) //Me.chkBit.SetIndex(_chkBit_3, CType(3, Short)) //Me.chkBit.SetIndex(_chkBit_4, CType(4, Short)) //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) this.Shape1.SetIndex(_Shape1_3, Convert.ToInt16(3)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.chkBit, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; //using System.Data; using System.Diagnostics; using SwinGameSDK; /// <summary> /// The menu controller handles the drawing and user interactions /// from the menus in the game. These include the main menu, game /// menu and the settings m,enu. /// </summary> static class MenuController { /// <summary> /// The menu structure for the game. /// </summary> /// <remarks> /// These are the text captions for the menu items. /// </remarks> private static readonly string[][] _menuStructure = { new string[] { "PLAY", "SETUP", "SCORES", "QUIT" }, new string[] { "RETURN", "SURRENDER", "QUIT" }, new string[] { "EASY", "MEDIUM", "HARD" } }; private const int MENU_TOP = 575; private const int MENU_LEFT = 30; private const int MENU_GAP = 0; private const int BUTTON_WIDTH = 75; private const int BUTTON_HEIGHT = 15; private const int BUTTON_SEP = BUTTON_WIDTH + MENU_GAP; private const int TEXT_OFFSET = 0; private const int MAIN_MENU = 0; private const int GAME_MENU = 1; private const int SETUP_MENU = 2; private const int MAIN_MENU_PLAY_BUTTON = 0; private const int MAIN_MENU_SETUP_BUTTON = 1; private const int MAIN_MENU_TOP_SCORES_BUTTON = 2; private const int MAIN_MENU_QUIT_BUTTON = 3; private const int SETUP_MENU_EASY_BUTTON = 0; private const int SETUP_MENU_MEDIUM_BUTTON = 1; private const int SETUP_MENU_HARD_BUTTON = 2; private const int SETUP_MENU_EXIT_BUTTON = 3; private const int GAME_MENU_RETURN_BUTTON = 0; private const int GAME_MENU_SURRENDER_BUTTON = 1; private const int GAME_MENU_QUIT_BUTTON = 2; private static readonly Color MENU_COLOR = SwinGame.RGBAColor(2, 167, 252, 255); private static readonly Color HIGHLIGHT_COLOR = SwinGame.RGBAColor(1, 57, 86, 255); /// <summary> /// Handles the processing of user input when the main menu is showing /// </summary> public static void HandleMainMenuInput() { HandleMenuInput(MAIN_MENU, 0, 0); } /// <summary> /// Handles the processing of user input when the main menu is showing /// </summary> public static void HandleSetupMenuInput() { bool handled = false; handled = HandleMenuInput(SETUP_MENU, 1, 1); if (!handled) { HandleMenuInput(MAIN_MENU, 0, 0); } } /// <summary> /// Handle input in the game menu. /// </summary> /// <remarks> /// Player can return to the game, surrender, or quit entirely /// </remarks> public static void HandleGameMenuInput() { HandleMenuInput(GAME_MENU, 0, 0); } /// <summary> /// Handles input for the specified menu. /// </summary> /// <param name="menu">the identifier of the menu being processed</param> /// <param name="level">the vertical level of the menu</param> /// <param name="xOffset">the xoffset of the menu</param> /// <returns>false if a clicked missed the buttons. This can be used to check prior menus.</returns> private static bool HandleMenuInput(int menu, int level, int xOffset) { if (SwinGame.KeyTyped(KeyCode.vk_ESCAPE)) { GameController.EndCurrentState(); return true; } if (SwinGame.MouseClicked(MouseButton.LeftButton)) { int i = 0; for (i = 0; i <= _menuStructure[menu].Length - 1; i++) { //IsMouseOver the i'th button of the menu if (IsMouseOverMenu(i, level, xOffset)) { PerformMenuAction(menu, i); return true; } } if (level > 0) { //none clicked - so end this sub menu GameController.EndCurrentState(); } } return false; } /// <summary> /// Draws the main menu to the screen. /// </summary> public static void DrawMainMenu() { //Clears the Screen to Black //SwinGame.DrawText("Main Menu", Color.White, GameFont("ArialLarge"), 50, 50) DrawButtons(MAIN_MENU); } /// <summary> /// Draws the Game menu to the screen /// </summary> public static void DrawGameMenu() { //Clears the Screen to Black //SwinGame.DrawText("Paused", Color.White, GameFont("ArialLarge"), 50, 50) DrawButtons(GAME_MENU); } /// <summary> /// Draws the settings menu to the screen. /// </summary> /// <remarks> /// Also shows the main menu /// </remarks> public static void DrawSettings() { //Clears the Screen to Black //SwinGame.DrawText("Settings", Color.White, GameFont("ArialLarge"), 50, 50) DrawButtons(MAIN_MENU); DrawButtons(SETUP_MENU, 1, 1); } /// <summary> /// Draw the buttons associated with a top level menu. /// </summary> /// <param name="menu">the index of the menu to draw</param> private static void DrawButtons(int menu) { DrawButtons(menu, 0, 0); } /// <summary> /// Draws the menu at the indicated level. /// </summary> /// <param name="menu">the menu to draw</param> /// <param name="level">the level (height) of the menu</param> /// <param name="xOffset">the offset of the menu</param> /// <remarks> /// The menu text comes from the _menuStructure field. The level indicates the height /// of the menu, to enable sub menus. The xOffset repositions the menu horizontally /// to allow the submenus to be positioned correctly. /// </remarks> private static void DrawButtons(int menu, int level, int xOffset) { int btnTop = 0; btnTop = MENU_TOP - (MENU_GAP + BUTTON_HEIGHT) * level; int i = 0; for (i = 0; i <= _menuStructure[menu].Length - 1; i++) { int btnLeft = 0; btnLeft = MENU_LEFT + BUTTON_SEP * (i + xOffset); SwinGame.DrawTextLines(_menuStructure[menu][i], MENU_COLOR, Color.Black, GameResources.GameFont("Menu"), FontAlignment.AlignCenter, btnLeft + TEXT_OFFSET, btnTop + TEXT_OFFSET, BUTTON_WIDTH, BUTTON_HEIGHT); if (SwinGame.MouseDown(MouseButton.LeftButton) & IsMouseOverMenu(i, level, xOffset)) { SwinGame.DrawRectangle(HIGHLIGHT_COLOR, btnLeft, btnTop, BUTTON_WIDTH, BUTTON_HEIGHT); } } } /// <summary> /// Determined if the mouse is over one of the button in the main menu. /// </summary> /// <param name="button">the index of the button to check</param> /// <returns>true if the mouse is over that button</returns> private static bool IsMouseOverButton(int button) { return IsMouseOverMenu(button, 0, 0); } /// <summary> /// Checks if the mouse is over one of the buttons in a menu. /// </summary> /// <param name="button">the index of the button to check</param> /// <param name="level">the level of the menu</param> /// <param name="xOffset">the xOffset of the menu</param> /// <returns>true if the mouse is over the button</returns> private static bool IsMouseOverMenu(int button, int level, int xOffset) { int btnTop = MENU_TOP - (MENU_GAP + BUTTON_HEIGHT) * level; int btnLeft = MENU_LEFT + BUTTON_SEP * (button + xOffset); return UtilityFunctions.IsMouseInRectangle(btnLeft, btnTop, BUTTON_WIDTH, BUTTON_HEIGHT); } /// <summary> /// A button has been clicked, perform the associated action. /// </summary> /// <param name="menu">the menu that has been clicked</param> /// <param name="button">the index of the button that was clicked</param> private static void PerformMenuAction(int menu, int button) { switch (menu) { case MAIN_MENU: PerformMainMenuAction(button); break; case SETUP_MENU: PerformSetupMenuAction(button); break; case GAME_MENU: PerformGameMenuAction(button); break; } } /// <summary> /// The main menu was clicked, perform the button's action. /// </summary> /// <param name="button">the button pressed</param> private static void PerformMainMenuAction(int button) { switch (button) { case MAIN_MENU_PLAY_BUTTON: GameController.StartGame(); break; case MAIN_MENU_SETUP_BUTTON: GameController.AddNewState(GameState.AlteringSettings); break; case MAIN_MENU_TOP_SCORES_BUTTON: GameController.AddNewState(GameState.ViewingHighScores); break; case MAIN_MENU_QUIT_BUTTON: GameController.EndCurrentState(); break; } } /// <summary> /// The setup menu was clicked, perform the button's action. /// </summary> /// <param name="button">the button pressed</param> private static void PerformSetupMenuAction(int button) { switch (button) { case SETUP_MENU_EASY_BUTTON: GameController.SetDifficulty(AIOption.Easy); break; case SETUP_MENU_MEDIUM_BUTTON: GameController.SetDifficulty(AIOption.Medium); break; case SETUP_MENU_HARD_BUTTON: GameController.SetDifficulty(AIOption.Hard); break; } //Always end state - handles exit button as well GameController.EndCurrentState(); } /// <summary> /// The game menu was clicked, perform the button's action. /// </summary> /// <param name="button">the button pressed</param> private static void PerformGameMenuAction(int button) { switch (button) { case GAME_MENU_RETURN_BUTTON: GameController.EndCurrentState(); break; case GAME_MENU_SURRENDER_BUTTON: GameController.EndCurrentState(); //end game menu GameController.EndCurrentState(); //end game SwinGame.StopMusic(); SwinGame.PlayMusic(GameResources.GameMusic("Background")); break; case GAME_MENU_QUIT_BUTTON: GameController.AddNewState(GameState.Quitting); break; } } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
// 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.Net.Security; using System.Security.Cryptography.X509Certificates; using Xunit; namespace System.Net.Tests { public class ServicePointManagerTest : RemoteExecutorTestBase { [Fact] public static void RequireEncryption_ExpectedDefault() { RemoteInvoke(() => Assert.Equal(EncryptionPolicy.RequireEncryption, ServicePointManager.EncryptionPolicy)).Dispose(); } [Fact] public static void CheckCertificateRevocationList_Roundtrips() { RemoteInvoke(() => { Assert.False(ServicePointManager.CheckCertificateRevocationList); ServicePointManager.CheckCertificateRevocationList = true; Assert.True(ServicePointManager.CheckCertificateRevocationList); ServicePointManager.CheckCertificateRevocationList = false; Assert.False(ServicePointManager.CheckCertificateRevocationList); }).Dispose(); } [Fact] public static void DefaultConnectionLimit_Roundtrips() { RemoteInvoke(() => { Assert.Equal(2, ServicePointManager.DefaultConnectionLimit); ServicePointManager.DefaultConnectionLimit = 20; Assert.Equal(20, ServicePointManager.DefaultConnectionLimit); ServicePointManager.DefaultConnectionLimit = 2; Assert.Equal(2, ServicePointManager.DefaultConnectionLimit); }).Dispose(); } [Fact] public static void DnsRefreshTimeout_Roundtrips() { RemoteInvoke(() => { Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout); ServicePointManager.DnsRefreshTimeout = 42; Assert.Equal(42, ServicePointManager.DnsRefreshTimeout); ServicePointManager.DnsRefreshTimeout = 120000; Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout); }).Dispose(); } [Fact] public static void EnableDnsRoundRobin_Roundtrips() { RemoteInvoke(() => { Assert.False(ServicePointManager.EnableDnsRoundRobin); ServicePointManager.EnableDnsRoundRobin = true; Assert.True(ServicePointManager.EnableDnsRoundRobin); ServicePointManager.EnableDnsRoundRobin = false; Assert.False(ServicePointManager.EnableDnsRoundRobin); }).Dispose(); } [Fact] public static void Expect100Continue_Roundtrips() { RemoteInvoke(() => { Assert.True(ServicePointManager.Expect100Continue); ServicePointManager.Expect100Continue = false; Assert.False(ServicePointManager.Expect100Continue); ServicePointManager.Expect100Continue = true; Assert.True(ServicePointManager.Expect100Continue); }).Dispose(); } [Fact] public static void MaxServicePointIdleTime_Roundtrips() { RemoteInvoke(() => { Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime); ServicePointManager.MaxServicePointIdleTime = 42; Assert.Equal(42, ServicePointManager.MaxServicePointIdleTime); ServicePointManager.MaxServicePointIdleTime = 100000; Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime); }).Dispose(); } [Fact] public static void MaxServicePoints_Roundtrips() { RemoteInvoke(() => { Assert.Equal(0, ServicePointManager.MaxServicePoints); ServicePointManager.MaxServicePoints = 42; Assert.Equal(42, ServicePointManager.MaxServicePoints); ServicePointManager.MaxServicePoints = 0; Assert.Equal(0, ServicePointManager.MaxServicePoints); }).Dispose(); } [Fact] public static void ReusePort_Roundtrips() { RemoteInvoke(() => { Assert.False(ServicePointManager.ReusePort); ServicePointManager.ReusePort = true; Assert.True(ServicePointManager.ReusePort); ServicePointManager.ReusePort = false; Assert.False(ServicePointManager.ReusePort); }).Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop default SecurityProtocol to Ssl3; explicitly changed to SystemDefault for core.")] public static void SecurityProtocol_Roundtrips() { RemoteInvoke(() => { var orig = (SecurityProtocolType)0; // SystemDefault. Assert.Equal(orig, ServicePointManager.SecurityProtocol); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; Assert.Equal(SecurityProtocolType.Tls11, ServicePointManager.SecurityProtocol); ServicePointManager.SecurityProtocol = orig; Assert.Equal(orig, ServicePointManager.SecurityProtocol); }).Dispose(); } [Fact] public static void ServerCertificateValidationCallback_Roundtrips() { RemoteInvoke(() => { Assert.Null(ServicePointManager.ServerCertificateValidationCallback); RemoteCertificateValidationCallback callback = delegate { return true; }; ServicePointManager.ServerCertificateValidationCallback = callback; Assert.Same(callback, ServicePointManager.ServerCertificateValidationCallback); ServicePointManager.ServerCertificateValidationCallback = null; Assert.Null(ServicePointManager.ServerCertificateValidationCallback); }).Dispose(); } [Fact] public static void UseNagleAlgorithm_Roundtrips() { RemoteInvoke(() => { Assert.True(ServicePointManager.UseNagleAlgorithm); ServicePointManager.UseNagleAlgorithm = false; Assert.False(ServicePointManager.UseNagleAlgorithm); ServicePointManager.UseNagleAlgorithm = true; Assert.True(ServicePointManager.UseNagleAlgorithm); }).Dispose(); } [Fact] public static void InvalidArguments_Throw() { RemoteInvoke(() => { const int ssl2Client = 0x00000008; const int ssl2Server = 0x00000004; const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server); Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = ssl2); AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null)); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePoints = -1); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.DefaultConnectionLimit = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => ServicePointManager.MaxServicePointIdleTime = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => ServicePointManager.SetTcpKeepAlive(true, -1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => ServicePointManager.SetTcpKeepAlive(true, 1, -1)); AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint(null)); AssertExtensions.Throws<ArgumentNullException>("uriString", () => ServicePointManager.FindServicePoint((string)null, null)); AssertExtensions.Throws<ArgumentNullException>("address", () => ServicePointManager.FindServicePoint((Uri)null, null)); Assert.Throws<NotSupportedException>(() => ServicePointManager.FindServicePoint("http://anything", new FixedWebProxy("https://anything"))); ServicePoint sp = ServicePointManager.FindServicePoint("http://" + Guid.NewGuid().ToString("N"), null); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLeaseTimeout = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ConnectionLimit = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.MaxIdleTime = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sp.ReceiveBufferSize = -2); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveTime", () => sp.SetTcpKeepAlive(true, -1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("keepAliveInterval", () => sp.SetTcpKeepAlive(true, 1, -1)); }).Dispose(); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Ssl3 is supported by desktop but explicitly not by core")] [Fact] public static void SecurityProtocol_Ssl3_NotSupported() { RemoteInvoke(() => { const int ssl2Client = 0x00000008; const int ssl2Server = 0x00000004; const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server); #pragma warning disable 0618 // Ssl2, Ssl3 are deprecated. Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3); Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | ssl2); #pragma warning restore }).Dispose(); } [Fact] public static void FindServicePoint_ReturnsCachedServicePoint() { RemoteInvoke(() => { const string Localhost = "http://localhost"; string address1 = "http://" + Guid.NewGuid().ToString("N"); string address2 = "http://" + Guid.NewGuid().ToString("N"); Assert.NotNull(ServicePointManager.FindServicePoint(new Uri(address1))); Assert.Same( ServicePointManager.FindServicePoint(address1, null), ServicePointManager.FindServicePoint(address1, null)); Assert.Same( ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1))); Assert.Same( ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(address2, new FixedWebProxy(address1))); Assert.Same( ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(Localhost, new FixedWebProxy(address2))); Assert.NotSame( ServicePointManager.FindServicePoint(address1, null), ServicePointManager.FindServicePoint(address2, null)); Assert.NotSame( ServicePointManager.FindServicePoint(address1, null), ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1))); Assert.NotSame( ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address1)), ServicePointManager.FindServicePoint(address1, new FixedWebProxy(address2))); }).Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop ServicePoint lifetime is slightly longer due to implementation details of real implementation")] public static void FindServicePoint_Collectible() { RemoteInvoke(() => { string address = "http://" + Guid.NewGuid().ToString("N"); bool initial = GetExpect100Continue(address); SetExpect100Continue(address, !initial); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.Equal(initial, GetExpect100Continue(address)); }).Dispose(); } [Fact] public static void FindServicePoint_ReturnedServicePointMatchesExpectedValues() { RemoteInvoke(() => { string address = "http://" + Guid.NewGuid().ToString("N"); DateTime start = DateTime.Now; ServicePoint sp = ServicePointManager.FindServicePoint(address, null); Assert.InRange(sp.IdleSince, start, DateTime.MaxValue); Assert.Equal(new Uri(address), sp.Address); Assert.Null(sp.BindIPEndPointDelegate); Assert.Null(sp.Certificate); Assert.Null(sp.ClientCertificate); Assert.Equal(-1, sp.ConnectionLeaseTimeout); Assert.Equal("http", sp.ConnectionName); Assert.Equal(0, sp.CurrentConnections); Assert.Equal(true, sp.Expect100Continue); Assert.Equal(100000, sp.MaxIdleTime); Assert.Equal(new Version(1, 1), sp.ProtocolVersion); Assert.Equal(-1, sp.ReceiveBufferSize); Assert.True(sp.SupportsPipelining, "SupportsPipelining"); Assert.True(sp.UseNagleAlgorithm, "UseNagleAlgorithm"); }).Dispose(); } [Fact] public static void FindServicePoint_PropertiesRoundtrip() { RemoteInvoke(() => { string address = "http://" + Guid.NewGuid().ToString("N"); BindIPEndPoint expectedBindIPEndPointDelegate = delegate { return null; }; int expectedConnectionLeaseTimeout = 42; int expectedConnectionLimit = 84; bool expected100Continue = false; int expectedMaxIdleTime = 200000; int expectedReceiveBufferSize = 123; bool expectedUseNagleAlgorithm = false; ServicePoint sp1 = ServicePointManager.FindServicePoint(address, null); sp1.BindIPEndPointDelegate = expectedBindIPEndPointDelegate; sp1.ConnectionLeaseTimeout = expectedConnectionLeaseTimeout; sp1.ConnectionLimit = expectedConnectionLimit; sp1.Expect100Continue = expected100Continue; sp1.MaxIdleTime = expectedMaxIdleTime; sp1.ReceiveBufferSize = expectedReceiveBufferSize; sp1.UseNagleAlgorithm = expectedUseNagleAlgorithm; ServicePoint sp2 = ServicePointManager.FindServicePoint(address, null); Assert.Same(expectedBindIPEndPointDelegate, sp2.BindIPEndPointDelegate); Assert.Equal(expectedConnectionLeaseTimeout, sp2.ConnectionLeaseTimeout); Assert.Equal(expectedConnectionLimit, sp2.ConnectionLimit); Assert.Equal(expected100Continue, sp2.Expect100Continue); Assert.Equal(expectedMaxIdleTime, sp2.MaxIdleTime); Assert.Equal(expectedReceiveBufferSize, sp2.ReceiveBufferSize); Assert.Equal(expectedUseNagleAlgorithm, sp2.UseNagleAlgorithm); }).Dispose(); } [Fact] public static void FindServicePoint_NewServicePointsInheritCurrentValues() { RemoteInvoke(() => { string address1 = "http://" + Guid.NewGuid().ToString("N"); string address2 = "http://" + Guid.NewGuid().ToString("N"); bool orig100Continue = ServicePointManager.Expect100Continue; bool origNagle = ServicePointManager.UseNagleAlgorithm; ServicePointManager.Expect100Continue = false; ServicePointManager.UseNagleAlgorithm = false; ServicePoint sp1 = ServicePointManager.FindServicePoint(address1, null); Assert.False(sp1.Expect100Continue); Assert.False(sp1.UseNagleAlgorithm); ServicePointManager.Expect100Continue = true; ServicePointManager.UseNagleAlgorithm = true; ServicePoint sp2 = ServicePointManager.FindServicePoint(address2, null); Assert.True(sp2.Expect100Continue); Assert.True(sp2.UseNagleAlgorithm); Assert.False(sp1.Expect100Continue); Assert.False(sp1.UseNagleAlgorithm); ServicePointManager.Expect100Continue = orig100Continue; ServicePointManager.UseNagleAlgorithm = origNagle; }).Dispose(); } // Separated out to avoid the JIT in debug builds interfering with object lifetimes private static bool GetExpect100Continue(string address) => ServicePointManager.FindServicePoint(address, null).Expect100Continue; private static void SetExpect100Continue(string address, bool value) => ServicePointManager.FindServicePoint(address, null).Expect100Continue = value; private sealed class FixedWebProxy : IWebProxy { private readonly Uri _proxyAddress; public FixedWebProxy(string proxyAddress) { _proxyAddress = new Uri(proxyAddress); } public Uri GetProxy(Uri destination) => _proxyAddress; public bool IsBypassed(Uri host) => false; public ICredentials Credentials { get; set; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using LibGit2Sharp.Core; using Xunit; namespace LibGit2Sharp.Tests.TestHelpers { public class BaseFixture : IPostTestDirectoryRemover, IDisposable { private readonly List<string> directories = new List<string>(); #if LEAKS_IDENTIFYING public BaseFixture() { LeaksContainer.Clear(); } #endif static BaseFixture() { // Do the set up in the static ctor so it only happens once SetUpTestEnvironment(); } public static string BareTestRepoPath { get; private set; } public static string StandardTestRepoWorkingDirPath { get; private set; } public static string StandardTestRepoPath { get; private set; } public static string ShallowTestRepoPath { get; private set; } public static string MergedTestRepoWorkingDirPath { get; private set; } public static string MergeTestRepoWorkingDirPath { get; private set; } public static string MergeRenamesTestRepoWorkingDirPath { get; private set; } public static string RevertTestRepoWorkingDirPath { get; private set; } public static string SubmoduleTestRepoWorkingDirPath { get; private set; } private static string SubmoduleTargetTestRepoWorkingDirPath { get; set; } private static string AssumeUnchangedRepoWorkingDirPath { get; set; } private static string SubmoduleSmallTestRepoWorkingDirPath { get; set; } public static DirectoryInfo ResourcesDirectory { get; private set; } public static bool IsFileSystemCaseSensitive { get; private set; } protected static DateTimeOffset TruncateSubSeconds(DateTimeOffset dto) { int seconds = dto.ToSecondsSinceEpoch(); return Epoch.ToDateTimeOffset(seconds, (int) dto.Offset.TotalMinutes); } private static void SetUpTestEnvironment() { IsFileSystemCaseSensitive = IsFileSystemCaseSensitiveInternal(); const string sourceRelativePath = @"../../Resources"; ResourcesDirectory = new DirectoryInfo(sourceRelativePath); // Setup standard paths to our test repositories BareTestRepoPath = Path.Combine(sourceRelativePath, "testrepo.git"); StandardTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "testrepo_wd"); StandardTestRepoPath = Path.Combine(StandardTestRepoWorkingDirPath, "dot_git"); ShallowTestRepoPath = Path.Combine(sourceRelativePath, "shallow.git"); MergedTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergedrepo_wd"); MergeRenamesTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "mergerenames_wd"); MergeTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "merge_testrepo_wd"); RevertTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "revert_testrepo_wd"); SubmoduleTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_wd"); SubmoduleTargetTestRepoWorkingDirPath = Path.Combine(sourceRelativePath, "submodule_target_wd"); AssumeUnchangedRepoWorkingDirPath = Path.Combine(sourceRelativePath, "assume_unchanged_wd"); SubmoduleSmallTestRepoWorkingDirPath = Path.Combine(ResourcesDirectory.FullName, "submodule_small_wd"); } private static bool IsFileSystemCaseSensitiveInternal() { var mixedPath = Path.Combine(Constants.TemporaryReposPath, "mIxEdCase-" + Path.GetRandomFileName()); if (Directory.Exists(mixedPath)) { Directory.Delete(mixedPath); } Directory.CreateDirectory(mixedPath); bool isInsensitive = Directory.Exists(mixedPath.ToLowerInvariant()); Directory.Delete(mixedPath); return !isInsensitive; } // Should match LibGit2Sharp.Core.NativeMethods.IsRunningOnUnix() protected static bool IsRunningOnUnix() { // see http://mono-project.com/FAQ%3a_Technical#Mono_Platforms var p = (int)Environment.OSVersion.Platform; return (p == 4) || (p == 6) || (p == 128); } protected void CreateCorruptedDeadBeefHead(string repoPath) { const string deadbeef = "deadbeef"; string headPath = string.Format("refs/heads/{0}", deadbeef); Touch(repoPath, headPath, string.Format("{0}{0}{0}{0}{0}\n", deadbeef)); } protected SelfCleaningDirectory BuildSelfCleaningDirectory() { return new SelfCleaningDirectory(this); } protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path) { return new SelfCleaningDirectory(this, path); } protected string SandboxBareTestRepo() { return Sandbox(BareTestRepoPath); } protected string SandboxStandardTestRepo() { return Sandbox(StandardTestRepoWorkingDirPath); } protected string SandboxMergedTestRepo() { return Sandbox(MergedTestRepoWorkingDirPath); } protected string SandboxStandardTestRepoGitDir() { return Sandbox(Path.Combine(StandardTestRepoWorkingDirPath)); } protected string SandboxMergeTestRepo() { return Sandbox(MergeTestRepoWorkingDirPath); } protected string SandboxRevertTestRepo() { return Sandbox(RevertTestRepoWorkingDirPath); } public string SandboxSubmoduleTestRepo() { return Sandbox(SubmoduleTestRepoWorkingDirPath, SubmoduleTargetTestRepoWorkingDirPath); } public string SandboxAssumeUnchangedTestRepo() { return Sandbox(AssumeUnchangedRepoWorkingDirPath); } public string SandboxSubmoduleSmallTestRepo() { var submoduleTarget = Path.Combine(ResourcesDirectory.FullName, "submodule_target_wd"); var path = Sandbox(SubmoduleSmallTestRepoWorkingDirPath, submoduleTarget); Directory.CreateDirectory(Path.Combine(path, "submodule_target_wd")); return path; } protected string Sandbox(string sourceDirectoryPath, params string[] additionalSourcePaths) { var scd = BuildSelfCleaningDirectory(); var source = new DirectoryInfo(sourceDirectoryPath); var clonePath = Path.Combine(scd.DirectoryPath, source.Name); DirectoryHelper.CopyFilesRecursively(source, new DirectoryInfo(clonePath)); foreach (var additionalPath in additionalSourcePaths) { var additional = new DirectoryInfo(additionalPath); var targetForAdditional = Path.Combine(scd.DirectoryPath, additional.Name); DirectoryHelper.CopyFilesRecursively(additional, new DirectoryInfo(targetForAdditional)); } return clonePath; } protected string InitNewRepository(bool isBare = false) { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); return Repository.Init(scd.DirectoryPath, isBare); } protected Repository InitIsolatedRepository(string path = null, bool isBare = false, RepositoryOptions options = null) { path = path ?? InitNewRepository(isBare); options = BuildFakeConfigs(BuildSelfCleaningDirectory(), options); return new Repository(path, options); } public void Register(string directoryPath) { directories.Add(directoryPath); } public virtual void Dispose() { foreach (string directory in directories) { DirectoryHelper.DeleteDirectory(directory); } #if LEAKS_IDENTIFYING GC.Collect(); GC.WaitForPendingFinalizers(); if (LeaksContainer.TypeNames.Any()) { Assert.False(true, string.Format("Some handles of the following types haven't been properly released: {0}.{1}" + "In order to get some help fixing those leaks, uncomment the define LEAKS_TRACKING in SafeHandleBase.cs{1}" + "and run the tests locally.", string.Join(", ", LeaksContainer.TypeNames), Environment.NewLine)); } #endif } protected static void InconclusiveIf(Func<bool> predicate, string message) { if (!predicate()) { return; } throw new SkipException(message); } protected void RequiresDotNetOrMonoGreaterThanOrEqualTo(System.Version minimumVersion) { Type type = Type.GetType("Mono.Runtime"); if (type == null) { // We're running on top of .Net return; } MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName == null) { throw new InvalidOperationException("Cannot access Mono.RunTime.GetDisplayName() method."); } var version = (string) displayName.Invoke(null, null); System.Version current; try { current = new System.Version(version.Split(' ')[0]); } catch (Exception e) { throw new Exception(string.Format("Cannot parse Mono version '{0}'.", version), e); } InconclusiveIf(() => current < minimumVersion, string.Format( "Current Mono version is {0}. Minimum required version to run this test is {1}.", current, minimumVersion)); } protected static void AssertValueInConfigFile(string configFilePath, string regex) { var text = File.ReadAllText(configFilePath); var r = new Regex(regex, RegexOptions.Multiline).Match(text); Assert.True(r.Success, text); } public RepositoryOptions BuildFakeConfigs(SelfCleaningDirectory scd, RepositoryOptions options = null) { options = BuildFakeRepositoryOptions(scd, options); StringBuilder sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = global{0}", Environment.NewLine) .AppendFormat("[Wow]{0}", Environment.NewLine) .AppendFormat("Man-I-am-totally-global = 42{0}", Environment.NewLine); File.WriteAllText(options.GlobalConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = system{0}", Environment.NewLine); File.WriteAllText(options.SystemConfigurationLocation, sb.ToString()); sb = new StringBuilder() .AppendFormat("[Woot]{0}", Environment.NewLine) .AppendFormat("this-rocks = xdg{0}", Environment.NewLine); File.WriteAllText(options.XdgConfigurationLocation, sb.ToString()); return options; } private static RepositoryOptions BuildFakeRepositoryOptions(SelfCleaningDirectory scd, RepositoryOptions options = null) { options = options ?? new RepositoryOptions(); string confs = Path.Combine(scd.DirectoryPath, "confs"); Directory.CreateDirectory(confs); options.GlobalConfigurationLocation = Path.Combine(confs, "my-global-config"); options.XdgConfigurationLocation = Path.Combine(confs, "my-xdg-config"); options.SystemConfigurationLocation = Path.Combine(confs, "my-system-config"); return options; } /// <summary> /// Creates a configuration file with user.name and user.email set to signature /// </summary> /// <remarks>The configuration file will be removed automatically when the tests are finished</remarks> /// <param name="signature">The signature to use for user.name and user.email</param> /// <returns>The path to the configuration file</returns> protected string CreateConfigurationWithDummyUser(Signature signature) { return CreateConfigurationWithDummyUser(signature.Name, signature.Email); } protected string CreateConfigurationWithDummyUser(string name, string email) { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); Directory.CreateDirectory(scd.DirectoryPath); string configFilePath = Path.Combine(scd.DirectoryPath, "global-config"); using (Configuration config = new Configuration(configFilePath)) { if (name != null) { config.Set("user.name", name, ConfigurationLevel.Global); } if (email != null) { config.Set("user.email", email, ConfigurationLevel.Global); } } return configFilePath; } /// <summary> /// Asserts that the commit has been authored and committed by the specified signature /// </summary> /// <param name="commit">The commit</param> /// <param name="signature">The signature to compare author and commiter to</param> protected void AssertCommitSignaturesAre(Commit commit, Signature signature) { Assert.Equal(signature.Name, commit.Author.Name); Assert.Equal(signature.Email, commit.Author.Email); Assert.Equal(signature.Name, commit.Committer.Name); Assert.Equal(signature.Email, commit.Committer.Email); } protected static string Touch(string parent, string file, string content = null, Encoding encoding = null) { string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); Directory.CreateDirectory(dir); File.WriteAllText(filePath, content ?? string.Empty, encoding ?? Encoding.ASCII); return filePath; } protected static string Touch(string parent, string file, Stream stream) { Debug.Assert(stream != null); string filePath = Path.Combine(parent, file); string dir = Path.GetDirectoryName(filePath); Debug.Assert(dir != null); Directory.CreateDirectory(dir); using (var fs = File.Open(filePath, FileMode.Create)) { CopyStream(stream, fs); fs.Flush(); } return filePath; } protected string Expected(string filename) { return File.ReadAllText(Path.Combine(ResourcesDirectory.FullName, "expected/" + filename)); } protected string Expected(string filenameFormat, params object[] args) { return Expected(string.Format(CultureInfo.InvariantCulture, filenameFormat, args)); } protected static void AssertRefLogEntry(IRepository repo, string canonicalName, string message, ObjectId @from, ObjectId to, Identity committer, DateTimeOffset when) { var reflogEntry = repo.Refs.Log(canonicalName).First(); Assert.Equal(to, reflogEntry.To); Assert.Equal(message, reflogEntry.Message); Assert.Equal(@from ?? ObjectId.Zero, reflogEntry.From); Assert.Equal(committer.Email, reflogEntry.Committer.Email); Assert.InRange(reflogEntry.Committer.When, when - TimeSpan.FromSeconds(5), when); } protected static void EnableRefLog(IRepository repository, bool enable = true) { repository.Config.Set("core.logAllRefUpdates", enable); } public static void CopyStream(Stream input, Stream output) { // Reused from the following Stack Overflow post with permission // of Jon Skeet (obtained on 25 Feb 2013) // http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file/411605#411605 var buffer = new byte[8 * 1024]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } } public static bool StreamEquals(Stream one, Stream two) { int onebyte, twobyte; while ((onebyte = one.ReadByte()) >= 0 && (twobyte = two.ReadByte()) >= 0) { if (onebyte != twobyte) return false; } return true; } public void AssertBelongsToARepository<T>(IRepository repo, T instance) where T : IBelongToARepository { Assert.Same(repo, ((IBelongToARepository)instance).Repository); } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using GameLibrary.Dependencies.Physics.Common; using Microsoft.Xna.Framework; using System.Diagnostics; namespace GameLibrary.Dependencies.Physics.Dynamics.Joints { // Point-to-point constraint // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Angle constraint // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 /// <summary> /// Friction joint. This is used for top-down friction. /// It provides 2D translational friction and angular friction. /// </summary> public class FrictionJoint : PhysicsJoint { public Vector2 LocalAnchorA; public Vector2 LocalAnchorB; private float _angularImpulse; private float _angularMass; private Vector2 _linearImpulse; private Mat22 _linearMass; internal FrictionJoint() { JointType = JointType.Friction; } public FrictionJoint(PhysicsBody bodyA, PhysicsBody bodyB, Vector2 localAnchorA, Vector2 localAnchorB) : base(bodyA, bodyB) { JointType = JointType.Friction; LocalAnchorA = localAnchorA; LocalAnchorB = localAnchorB; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// The maximum friction force in N. /// </summary> public float MaxForce { get; set; } /// <summary> /// The maximum friction torque in N-m. /// </summary> public float MaxTorque { get; set; } public override Vector2 GetReactionForce(float inv_dt) { return inv_dt * _linearImpulse; } public override float GetReactionTorque(float inv_dt) { return inv_dt * _angularImpulse; } internal override void InitVelocityConstraints(ref TimeStep step) { PhysicsBody bA = BodyA; PhysicsBody bB = BodyB; Transform xfA, xfB; bA.GetTransform(out xfA); bB.GetTransform(out xfB); // Compute the effective mass matrix. Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter); Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = bA.InvMass, mB = bB.InvMass; float iA = bA.InvI, iB = bB.InvI; Mat22 K1 = new Mat22(); K1.Col1.X = mA + mB; K1.Col2.X = 0.0f; K1.Col1.Y = 0.0f; K1.Col2.Y = mA + mB; Mat22 K2 = new Mat22(); K2.Col1.X = iA * rA.Y * rA.Y; K2.Col2.X = -iA * rA.X * rA.Y; K2.Col1.Y = -iA * rA.X * rA.Y; K2.Col2.Y = iA * rA.X * rA.X; Mat22 K3 = new Mat22(); K3.Col1.X = iB * rB.Y * rB.Y; K3.Col2.X = -iB * rB.X * rB.Y; K3.Col1.Y = -iB * rB.X * rB.Y; K3.Col2.Y = iB * rB.X * rB.X; Mat22 K12; Mat22.Add(ref K1, ref K2, out K12); Mat22 K; Mat22.Add(ref K12, ref K3, out K); _linearMass = K.Inverse; _angularMass = iA + iB; if (_angularMass > 0.0f) { _angularMass = 1.0f / _angularMass; } if (Settings.EnableWarmstarting) { // Scale impulses to support a variable time step. _linearImpulse *= step.dtRatio; _angularImpulse *= step.dtRatio; Vector2 P = new Vector2(_linearImpulse.X, _linearImpulse.Y); bA.LinearVelocityInternal -= mA * P; bA.AngularVelocityInternal -= iA * (MathUtils.Cross(rA, P) + _angularImpulse); bB.LinearVelocityInternal += mB * P; bB.AngularVelocityInternal += iB * (MathUtils.Cross(rB, P) + _angularImpulse); } else { _linearImpulse = Vector2.Zero; _angularImpulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { PhysicsBody bA = BodyA; PhysicsBody bB = BodyB; Vector2 vA = bA.LinearVelocityInternal; float wA = bA.AngularVelocityInternal; Vector2 vB = bB.LinearVelocityInternal; float wB = bB.AngularVelocityInternal; float mA = bA.InvMass, mB = bB.InvMass; float iA = bA.InvI, iB = bB.InvI; Transform xfA, xfB; bA.GetTransform(out xfA); bB.GetTransform(out xfB); Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter); Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter); // Solve angular friction { float Cdot = wB - wA; float impulse = -_angularMass * Cdot; float oldImpulse = _angularImpulse; float maxImpulse = step.dt * MaxTorque; _angularImpulse = MathUtils.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = _angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { Vector2 Cdot = vB + MathUtils.Cross(wB, rB) - vA - MathUtils.Cross(wA, rA); Vector2 impulse = -MathUtils.Multiply(ref _linearMass, Cdot); Vector2 oldImpulse = _linearImpulse; _linearImpulse += impulse; float maxImpulse = step.dt * MaxForce; if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { _linearImpulse.Normalize(); _linearImpulse *= maxImpulse; } impulse = _linearImpulse - oldImpulse; vA -= mA * impulse; wA -= iA * MathUtils.Cross(rA, impulse); vB += mB * impulse; wB += iB * MathUtils.Cross(rB, impulse); } bA.LinearVelocityInternal = vA; bA.AngularVelocityInternal = wA; bB.LinearVelocityInternal = vB; bB.AngularVelocityInternal = wB; } internal override bool SolvePositionConstraints() { return true; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Holoville.HOTween; public class GameGUI : MonoBehaviour { public List<HUD.GUIelement> GUIelements = new List<HUD.GUIelement>(); public GameObject myPlayer = null; public GUISkin guiSkin,inGameSkin,pauseSkin; public bool paused = false; private float originalWidth = 800; private float originalHeight = 480; private Vector3 scale; public float alphaFadeValue = 1; public Texture loadingTexture = null; public enum MenuState { MAIN, PAUSE, CONTROLSETTINGS, VISUALEFFECTS } public MenuState menuPosition = MenuState.MAIN; // Use this for initialization void Start () { HOTween.Init(false, false, true); HOTween.EnableOverwriteManager(); GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); foreach (GameObject player in players) { if (player.GetComponent<CharacterController>().controlMe && !player.GetComponent<CharacterController>().networkControl) myPlayer = player; else if (PhotonNetwork.room != null) GameObject.Find("GUI").GetComponent<GameGUI>().GUIelements.Add(new HUD.GUIelement(HUD.GUIelement.ElementType.HEALTH, new Rect(Screen.width - 100, 0, 100, 50), player.gameObject)); } if (myPlayer == null) myPlayer = players[players.Length - 1]; if (Application.isEditor) { if (!PhotonNetwork.offlineMode) GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().photonView.RPC("netPause", PhotonTargets.All, !paused); else GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().netPause(!paused); } HOTween.Kill(); HOTween.To(this, 1, "alphaFadeValue", 0f); SetAudioLevels (); } // Update is called once per frame void Update () { for (int i = 0; i < GUIelements.Count; i++) { switch (GUIelements[i].type) { case HUD.GUIelement.ElementType.MESSAGE : break; case HUD.GUIelement.ElementType.OTHERTEXT : break; case HUD.GUIelement.ElementType.SCORE : break; case HUD.GUIelement.ElementType.HEALTH : GUIelements[i].text = GUIelements[i].relatesTo.GetComponent<CharacterController>().damage.ToString(); // TODO the GUI element may cover other players, so we need to check for that HOTween.To (GUIelements[i], 0.1f, "rectangle", new Rect(Camera.main.WorldToScreenPoint(GUIelements[i].relatesTo.transform.position).x - GUIelements[i].rectangle.width / 2, Screen.height - Camera.main.WorldToScreenPoint(GUIelements[i].relatesTo.transform.position).y - 100, GUIelements[i].rectangle.width, GUIelements[i].rectangle.height)); for (int j = 0; j < GUIelements.Count; j++) { if (GUIelements[i] != GUIelements[j] && rectangleCollision(GUIelements[i].rectangle, GUIelements[j].rectangle, 10)) { // decide where to push the score element to HOTween.To (GUIelements[i], 0.5f, "rectangle", new Rect((GUIelements[i].rectangle.x + GUIelements[i].rectangle.width / 2 > GUIelements[j].rectangle.x + GUIelements[j].rectangle.width / 2) ? GUIelements[j].rectangle.x + GUIelements[j].rectangle.width + 11 : GUIelements[j].rectangle.x - GUIelements[i].rectangle.width - 11, GUIelements[i].rectangle.y, GUIelements[i].rectangle.width, GUIelements[i].rectangle.height)); // GUIelements[i].rectangle.x = (GUIelements[i].rectangle.x + GUIelements[i].rectangle.width / 2 > GUIelements[j].rectangle.x + GUIelements[j].rectangle.width / 2) ? GUIelements[j].rectangle.x + GUIelements[j].rectangle.width + 11 : GUIelements[j].rectangle.x - GUIelements[i].rectangle.width - 11; } } break; case HUD.GUIelement.ElementType.LIVES : break; case HUD.GUIelement.ElementType.POSITIONINDICATOR : break; } } // Global keys if (Input.GetKeyDown(KeyCode.Escape)) { if (!PhotonNetwork.offlineMode) GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().photonView.RPC("netPause", PhotonTargets.All, !paused); else GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().netPause(!paused); } } void FixedUpdate () { for (int i = 0; i < GUIelements.Count; i++) { if (GUIelements[i].displayTime > 0) { GUIelements[i].displayTime--; } else if (GUIelements[i].displayTime != -1) { GUIelements.RemoveAt(i); } } if (alphaFadeValue > 0 && Time.frameCount > 120) { alphaFadeValue = 0; } } void OnGUI () { GUI.skin = guiSkin; foreach (HUD.GUIelement element in GUIelements) { switch (element.type) { case HUD.GUIelement.ElementType.MESSAGE : break; case HUD.GUIelement.ElementType.OTHERTEXT : break; case HUD.GUIelement.ElementType.SCORE : break; case HUD.GUIelement.ElementType.HEALTH : GUI.Box(element.rectangle, element.text); break; case HUD.GUIelement.ElementType.LIVES : break; case HUD.GUIelement.ElementType.POSITIONINDICATOR : break; case HUD.GUIelement.ElementType.LINE : LineDraw.Drawing.DrawLine (new Vector2 (element.rectangle.x, element.rectangle.y), new Vector2 (element.rectangle.width, element.rectangle.height), Color.blue, 2, false); break; } } GUI.skin = null; GUI.Label (new Rect (5, 5, 200, 20), "status: " + PhotonNetwork.connectionStateDetailed.ToString() + ((PhotonNetwork.room != null) ? " " + PhotonNetwork.room.name + " room" : "")); GUI.skin = guiSkin; int _btnSize = (int) (Screen.dpi != 0 ? Screen.dpi / 2.5 : 100); if (PlayerPrefs.GetInt("controlScheme") == 2) { if (GUI.RepeatButton (new Rect(0, Screen.height - _btnSize, _btnSize, _btnSize), "<")) { myPlayer.GetComponent<CharacterController>().onscreenKeyLeftDown = true; } else { myPlayer.GetComponent<CharacterController>().onscreenKeyLeftDown = false; } if (GUI.RepeatButton (new Rect(Screen.width - _btnSize, Screen.height - _btnSize, _btnSize, _btnSize), ">")) { myPlayer.GetComponent<CharacterController>().onscreenKeyRightDown = true; } else { myPlayer.GetComponent<CharacterController>().onscreenKeyRightDown = false; } if (GUI.Button (new Rect(0, Screen.height - (_btnSize) * 2, _btnSize, _btnSize), "*") && myPlayer.GetComponent<CharacterController>().currentAttack == null) { if(!PhotonNetwork.offlineMode) myPlayer.GetComponent<CharacterController>().photonView.RPC ("attack", PhotonTargets.All); else myPlayer.GetComponent<CharacterController>().attack(); } if (GUI.Button (new Rect(Screen.width - _btnSize, Screen.height - (_btnSize) * 2, _btnSize, _btnSize), "^")) { myPlayer.GetComponent<CharacterController>().jump(); } } scale.x = Screen.width / originalWidth; // calculate hor scale scale.y = Screen.height / originalHeight; // calculate vert scale scale.z = 1; var svMat = GUI.matrix; // save current matrix //substitute matrix - only scale is altered from standard GUI.matrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, scale); switch (menuPosition) { case MenuState.MAIN: if (GUI.Button (new Rect (720, 5, 50, 50), "||")) { menuPosition = MenuState.PAUSE; if (!PhotonNetwork.offlineMode) GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().photonView.RPC("netPause", PhotonTargets.All, !paused); else GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().netPause(!paused); } break; case MenuState.PAUSE: GUI.skin = pauseSkin; GUI.Box (new Rect (150, 100, 500, 72), "Paused"); if (GUI.Button (new Rect (150, 165, 500, 55), "Resume")) { menuPosition = MenuState.MAIN; if (!PhotonNetwork.offlineMode) GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().photonView.RPC("netPause", PhotonTargets.All, !paused); else GameObject.Find ("Multiplayer").GetComponent<MultiplayerSyncer>().netPause(!paused); } else if (GUI.Button (new Rect (150, 215, 500, 55), "Control Settings")) { menuPosition = MenuState.CONTROLSETTINGS; } else if (GUI.Button (new Rect (150, 265, 500, 55), "Visual Effects")) { menuPosition = MenuState.VISUALEFFECTS; } else if (GUI.Button (new Rect (150, 315, 500, 55), "Disconnect")) { PhotonNetwork.LeaveRoom(); Application.LoadLevel("MainMenu"); } break; case MenuState.CONTROLSETTINGS: GUI.skin = pauseSkin; GUI.Box (new Rect (150, 100, 500, 72), "Control Setting"); //GUILayout.BeginArea (new Rect (200, 170, 400, 500)); if (GUI.Button (new Rect (150, 165, 500, 55), "Full Tilt")) PlayerPrefs.SetInt ("controlScheme", 0); if (GUI.Button (new Rect (150, 215, 500, 55),"Tilt with buttons")) PlayerPrefs.SetInt ("controlScheme", 1); if (GUI.Button (new Rect (150, 265, 500, 55),"On screen buttons")) PlayerPrefs.SetInt ("controlScheme", 2); if(GUI.Button (new Rect (150, 315, 500, 55),"Back")) menuPosition = MenuState.PAUSE; //GUILayout.EndArea (); break; case MenuState.VISUALEFFECTS: GUI.skin = pauseSkin; GUI.Box (new Rect (150, 10, 500, 72), "Visual Effects");; var names = QualitySettings.names; int pausey = 75; //GUILayout.BeginArea (new Rect (200, 80, 400, 500)); for (var i = 0; i < names.Length; i++) { if (GUI.Button (new Rect(150, pausey, 500, 55),names [i])) QualitySettings.SetQualityLevel (i, true); pausey += 50; } if(GUI.Button (new Rect (150, 375, 500, 55),"Back")) menuPosition = MenuState.PAUSE; //GUILayout.EndArea (); break; } if (alphaFadeValue > 0) { GUI.color = new Color(0, 0, 0, alphaFadeValue); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), loadingTexture ); GUI.color = new Color(255, 255, 255); } GUI.matrix = svMat; // restore matrix } bool rectangleCollision(Rect r1, Rect r2, int padding) { return !(r1.x > r2.x + r2.width + padding || r1.x + r1.width + padding < r2.x || r1.y > r2.y + r2.height + padding || r1.y + r1.height + padding < r2.y); // bool widthOverlap = (r1.xMin >= r2.xMin) && (r1.xMin <= r2.xMax) || (r2.xMin >= r1.xMin) && (r2.xMin <= r1.xMax); // bool heightOverlap = (r1.yMin >= r2.yMin) && (r1.yMin <= r2.yMax) || (r2.yMin >= r1.yMin) && (r2.yMin <= r1.yMax); // return (widthOverlap && heightOverlap); } void OnDestroy () { HOTween.Kill (); GUIelements.Clear (); Time.timeScale = 1; // Destroy all players GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); foreach (GameObject player in players) { Destroy(player); } } void SetAudioLevels () { AudioListener.volume = (float) ((double) PlayerPrefs.GetInt ("masterVolume") / 100.0); GameObject.Find("Music").GetComponent<AudioSource>().volume = (float) (((double) PlayerPrefs.GetInt ("musicVolume") / 100.0) * 0.3); } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function WorldEditor::onSelect( %this, %obj ) { EditorTree.addSelection( %obj ); _setShadowVizLight( %obj ); //Inspector.inspect( %obj ); if ( isObject( %obj ) && %obj.isMethod( "onEditorSelect" ) ) %obj.onEditorSelect( %this.getSelectionSize() ); EditorGui.currentEditor.onObjectSelected( %obj ); // Inform the camera commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid()); EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize()); // Update the materialEditorList $Tools::materialEditorList = %obj.getId(); // Used to help the Material Editor( the M.E doesn't utilize its own TS control ) // so this dirty extension is used to fake it if ( MaterialEditorPreviewWindow.isVisible() ) MaterialEditorGui.prepareActiveObject(); // Update the Transform Selection window ETransformSelection.onSelectionChanged(); } function WorldEditor::onMultiSelect( %this, %set ) { // This is called when completing a drag selection ( on3DMouseUp ) // so we can avoid calling onSelect for every object. We can only // do most of this stuff, like inspecting, on one object at a time anyway. %count = %set.getCount(); %i = 0; foreach( %obj in %set ) { if ( %obj.isMethod( "onEditorSelect" ) ) %obj.onEditorSelect( %count ); %i ++; EditorTree.addSelection( %obj, %i == %count ); EditorGui.currentEditor.onObjectSelected( %obj ); } // Inform the camera commandToServer( 'EditorOrbitCameraSelectChange', %count, %this.getSelectionCentroid() ); EditorGuiStatusBar.setSelectionObjectsByCount( EWorldEditor.getSelectionSize() ); // Update the Transform Selection window, if it is // visible. if( ETransformSelection.isVisible() ) ETransformSelection.onSelectionChanged(); } function WorldEditor::onUnSelect( %this, %obj ) { if ( isObject( %obj ) && %obj.isMethod( "onEditorUnselect" ) ) %obj.onEditorUnselect(); EditorGui.currentEditor.onObjectDeselected( %obj ); Inspector.removeInspect( %obj ); EditorTree.removeSelection(%obj); // Inform the camera commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid()); EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize()); // Update the Transform Selection window ETransformSelection.onSelectionChanged(); } function WorldEditor::onClearSelection( %this ) { EditorGui.currentEditor.onSelectionCleared(); EditorTree.clearSelection(); // Inform the camera commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid()); EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize()); // Update the Transform Selection window ETransformSelection.onSelectionChanged(); } function WorldEditor::onSelectionCentroidChanged( %this ) { // Inform the camera commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid()); // Refresh inspector. Inspector.refresh(); } ////////////////////////////////////////////////////////////////////////// function WorldEditor::init(%this) { // add objclasses which we do not want to collide with %this.ignoreObjClass(Sky); // editing modes %this.numEditModes = 3; %this.editMode[0] = "move"; %this.editMode[1] = "rotate"; %this.editMode[2] = "scale"; // context menu new GuiControl(WEContextPopupDlg, EditorGuiGroup) { profile = "ToolsGuiModelessDialogProfile"; horizSizing = "width"; vertSizing = "height"; position = "0 0"; extent = "640 480"; minExtent = "8 8"; visible = "1"; setFirstResponder = "0"; modal = "1"; new GuiPopUpMenuCtrl(WEContextPopup) { profile = "ToolsGuiScrollProfile"; position = "0 0"; extent = "0 0"; minExtent = "0 0"; maxPopupHeight = "200"; command = "canvas.popDialog(WEContextPopupDlg);"; }; }; WEContextPopup.setVisible(false); // Make sure we have an active selection set. if( !%this.getActiveSelection() ) %this.setActiveSelection( new WorldEditorSelection( EWorldEditorSelection ) ); } //------------------------------------------------------------------------------ function WorldEditor::onDblClick(%this, %obj) { // Commented out because making someone double click to do this is stupid // and has the possibility of moving hte object //Inspector.inspect(%obj); //InspectorNameEdit.setValue(%obj.getName()); } function WorldEditor::onClick( %this, %obj ) { Inspector.inspect( %obj ); } function WorldEditor::onEndDrag( %this, %obj ) { Inspector.inspect( %obj ); Inspector.apply(); } //------------------------------------------------------------------------------ function WorldEditor::export(%this) { getSaveFilename("~/editor/*.mac|mac file", %this @ ".doExport", "selection.mac"); } function WorldEditor::doExport(%this, %file) { missionGroup.save("~/editor/" @ %file, true); } function WorldEditor::import(%this) { getLoadFilename("~/editor/*.mac|mac file", %this @ ".doImport"); } function WorldEditor::doImport(%this, %file) { exec("~/editor/" @ %file); } function WorldEditor::onGuiUpdate(%this, %text) { } function WorldEditor::getSelectionLockCount(%this) { %ret = 0; for(%i = 0; %i < %this.getSelectionSize(); %i++) { %obj = %this.getSelectedObject(%i); if(%obj.locked) %ret++; } return %ret; } function WorldEditor::getSelectionHiddenCount(%this) { %ret = 0; for(%i = 0; %i < %this.getSelectionSize(); %i++) { %obj = %this.getSelectedObject(%i); if(%obj.hidden) %ret++; } return %ret; } function WorldEditor::dropCameraToSelection(%this) { if(%this.getSelectionSize() == 0) return; %pos = %this.getSelectionCentroid(); %cam = LocalClientConnection.camera.getTransform(); // set the pnt %cam = setWord(%cam, 0, getWord(%pos, 0)); %cam = setWord(%cam, 1, getWord(%pos, 1)); %cam = setWord(%cam, 2, getWord(%pos, 2)); LocalClientConnection.camera.setTransform(%cam); } /// Pastes the selection at the same place (used to move obj from a group to another) function WorldEditor::moveSelectionInPlace(%this) { %saveDropType = %this.dropType; %this.dropType = "atCentroid"; %this.copySelection(); %this.deleteSelection(); %this.pasteSelection(); %this.dropType = %saveDropType; } function WorldEditor::addSelectionToAddGroup(%this) { for(%i = 0; %i < %this.getSelectionSize(); %i++) { %obj = %this.getSelectedObject(%i); $InstantGroup.add(%obj); } } // resets the scale and rotation on the selection set function WorldEditor::resetTransforms(%this) { %this.addUndoState(); for(%i = 0; %i < %this.getSelectionSize(); %i++) { %obj = %this.getSelectedObject(%i); %transform = %obj.getTransform(); %transform = setWord(%transform, 3, "0"); %transform = setWord(%transform, 4, "0"); %transform = setWord(%transform, 5, "1"); %transform = setWord(%transform, 6, "0"); // %obj.setTransform(%transform); %obj.setScale("1 1 1"); } } function WorldEditorToolbarDlg::init(%this) { WorldEditorInspectorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolInspectorGui" ) ); WorldEditorMissionAreaCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolMissionAreaGui" ) ); WorldEditorTreeCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolTreeViewGui" ) ); WorldEditorCreatorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolCreatorGui" ) ); } function WorldEditor::onAddSelected(%this,%obj) { EditorTree.addSelection(%obj); } function WorldEditor::onWorldEditorUndo( %this ) { Inspector.refresh(); } function Inspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue ) { // The instant group will try to add our // UndoAction if we don't disable it. pushInstantGroup(); %nameOrClass = %object.getName(); if ( %nameOrClass $= "" ) %nameOrClass = %object.getClassname(); %action = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ %fieldName @ " Change"; objectId = %object.getId(); fieldName = %fieldName; fieldValue = %oldValue; arrayIndex = %arrayIndex; inspectorGui = %this; }; // If it's a datablock, initiate a retransmit. Don't do so // immediately so as the actual field value will only be set // by the inspector code after this method has returned. if( %object.isMemberOfClass( "SimDataBlock" ) ) %object.schedule( 1, "reloadOnLocalClient" ); // Restore the instant group. popInstantGroup(); %action.addToManager( Editor.getUndoManager() ); EWorldEditor.isDirty = true; // Update the selection if(EWorldEditor.getSelectionSize() > 0 && (%fieldName $= "position" || %fieldName $= "rotation" || %fieldName $= "scale")) { EWorldEditor.invalidateSelectionCentroid(); } } function Inspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc ) { FieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc ); } // The following three methods are for fields that edit field value live and thus cannot record // undo information during edits. For these fields, undo information is recorded in advance and // then either queued or disarded when the field edit is finished. function Inspector::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex ) { pushInstantGroup(); %undoManager = Editor.getUndoManager(); %numObjects = %this.getNumInspectObjects(); if( %numObjects > 1 ) %action = %undoManager.pushCompound( "Multiple Field Edit" ); for( %i = 0; %i < %numObjects; %i ++ ) { %object = %this.getInspectObject( %i ); %nameOrClass = %object.getName(); if ( %nameOrClass $= "" ) %nameOrClass = %object.getClassname(); %undo = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ %fieldName @ " Change"; objectId = %object.getId(); fieldName = %fieldName; fieldValue = %object.getFieldValue( %fieldName, %arrayIndex ); arrayIndex = %arrayIndex; inspectorGui = %this; }; if( %numObjects > 1 ) %undo.addToManager( %undoManager ); else { %action = %undo; break; } } %this.currentFieldEditAction = %action; popInstantGroup(); } function Inspector::onInspectorPostFieldModification( %this ) { if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) ) { // Finish multiple field edit. Editor.getUndoManager().popCompound(); } else { // Queue single field undo. %this.currentFieldEditAction.addToManager( Editor.getUndoManager() ); } %this.currentFieldEditAction = ""; EWorldEditor.isDirty = true; } function Inspector::onInspectorDiscardFieldModification( %this ) { %this.currentFieldEditAction.undo(); if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) ) { // Multiple field editor. Pop and discard. Editor.getUndoManager().popCompound( true ); } else { // Single field edit. Just kill undo action. %this.currentFieldEditAction.delete(); } %this.currentFieldEditAction = ""; } function Inspector::inspect( %this, %obj ) { //echo( "inspecting: " @ %obj ); %name = ""; if ( isObject( %obj ) ) %name = %obj.getName(); else FieldInfoControl.setText( "" ); //InspectorNameEdit.setValue( %name ); Parent::inspect( %this, %obj ); } function Inspector::onBeginCompoundEdit( %this ) { Editor.getUndoManager().pushCompound( "Multiple Field Edit" ); } function Inspector::onEndCompoundEdit( %this ) { Editor.getUndoManager().popCompound(); } function Inspector::onCancelCompoundEdit( %this ) { Editor.getUndoManager().popCompound( true ); } function foCollaps (%this, %tab){ switch$ (%tab){ case "container0": %tab.visible = "0"; buttxon1.position = getWord(buttxon0.position, 0)+32 SPC getWord(buttxon1.position, 1); buttxon2.position = getWord(buttxon1.position, 0)+32 SPC getWord(buttxon2.position, 1); case "container1": %tab.visible = "0"; case "container2": %tab.visible = "0"; } }
// // 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.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operation to return the status of the most recent synchronization /// between configuration database and the Git repository. /// </summary> internal partial class TenantConfigurationSyncStateOperation : IServiceOperations<ApiManagementClient>, ITenantConfigurationSyncStateOperation { /// <summary> /// Initializes a new instance of the /// TenantConfigurationSyncStateOperation class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TenantConfigurationSyncStateOperation(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Gets Tenant Configuration Synchronization State operation result. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get Tenant Configuration Synchronization State response details. /// </returns> public async Task<TenantConfigurationSyncStateResponse> GetAsync(string resourceGroupName, string serviceName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); 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/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/tenant/configuration/syncState"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); 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 TenantConfigurationSyncStateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TenantConfigurationSyncStateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { TenantConfigurationSyncStateContract valueInstance = new TenantConfigurationSyncStateContract(); result.Value = valueInstance; JToken branchValue = responseDoc["branch"]; if (branchValue != null && branchValue.Type != JTokenType.Null) { string branchInstance = ((string)branchValue); valueInstance.Branch = branchInstance; } JToken commitIdValue = responseDoc["commitId"]; if (commitIdValue != null && commitIdValue.Type != JTokenType.Null) { string commitIdInstance = ((string)commitIdValue); valueInstance.CommitId = commitIdInstance; } JToken isExportValue = responseDoc["isExport"]; if (isExportValue != null && isExportValue.Type != JTokenType.Null) { bool isExportInstance = ((bool)isExportValue); valueInstance.IsExport = isExportInstance; } JToken isSyncedValue = responseDoc["isSynced"]; if (isSyncedValue != null && isSyncedValue.Type != JTokenType.Null) { bool isSyncedInstance = ((bool)isSyncedValue); valueInstance.IsSynced = isSyncedInstance; } JToken isGitEnabledValue = responseDoc["isGitEnabled"]; if (isGitEnabledValue != null && isGitEnabledValue.Type != JTokenType.Null) { bool isGitEnabledInstance = ((bool)isGitEnabledValue); valueInstance.IsGitEnabled = isGitEnabledInstance; } JToken syncDateValue = responseDoc["syncDate"]; if (syncDateValue != null && syncDateValue.Type != JTokenType.Null) { DateTime syncDateInstance = ((DateTime)syncDateValue); valueInstance.SyncDate = syncDateInstance; } JToken configurationChangeDateValue = responseDoc["configurationChangeDate"]; if (configurationChangeDateValue != null && configurationChangeDateValue.Type != JTokenType.Null) { DateTime configurationChangeDateInstance = ((DateTime)configurationChangeDateValue); valueInstance.ConfigurationChangeDate = configurationChangeDateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; /// <summary> /// Base namespace for %Dokan. /// </summary> namespace DokanNet { /// <summary> /// %Dokan API callbacks interface. /// /// A interface of callbacks that describe all %Dokan API operation /// that will be called when Windows access to the file system. /// /// All this callbacks can return <see cref="NtStatus.NotImplemented"/> /// if you dont want to support one of them. Be aware that returning such value to important callbacks /// such <see cref="CreateFile"/>/<see cref="ReadFile"/>/... would make the filesystem not working or unstable. /// </summary> /// <remarks>This is the same struct as <c>DOKAN_OPERATIONS</c> (dokan.h) in the C version of Dokan.</remarks> public interface IDokanOperations { /// <summary> /// CreateFile is called each time a request is made on a file system object. /// /// In case <paramref name="mode"/> is <c><see cref="FileMode.OpenOrCreate"/></c> and /// <c><see cref="FileMode.Create"/></c> and CreateFile are successfully opening a already /// existing file, you have to return <see cref="DokanResult.AlreadyExists"/> instead of <see cref="NtStatus.Success"/>. /// /// If the file is a directory, CreateFile is also called. /// In this case, CreateFile should return <see cref="NtStatus.Success"/> when that directory /// can be opened and <see cref="IDokanFileInfo.IsDirectory"/> must be set to <c>true</c>. /// On the other hand, if <see cref="IDokanFileInfo.IsDirectory"/> is set to <c>true</c> /// but the path target a file, you need to return <see cref="DokanResult.NotADirectory"/> /// /// <see cref="IDokanFileInfo.Context"/> can be used to store data (like <c><see cref="FileStream"/></c>) /// that can be retrieved in all other request related to the context. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="access">A <see cref="FileAccess"/> with permissions for file or directory.</param> /// <param name="share">Type of share access to other threads, which is specified as /// <see cref="FileShare.None"/> or any combination of <see cref="FileShare"/>. /// Device and intermediate drivers usually set ShareAccess to zero, /// which gives the caller exclusive access to the open file.</param> /// <param name="mode">Specifies how the operating system should open a file. See <a href="https://msdn.microsoft.com/en-us/library/system.io.filemode(v=vs.110).aspx">FileMode Enumeration (MSDN)</a>.</param> /// <param name="options">Represents advanced options for creating a FileStream object. See <a href="https://msdn.microsoft.com/en-us/library/system.io.fileoptions(v=vs.110).aspx">FileOptions Enumeration (MSDN)</a>.</param> /// <param name="attributes">Provides attributes for files and directories. See <a href="https://msdn.microsoft.com/en-us/library/system.io.fileattributes(v=vs.110).aspx">FileAttributes Enumeration (MSDN></a>.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see See <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff566424(v=vs.85).aspx">ZwCreateFile (MSDN)</a> for more information about the parameters of this callback. NtStatus CreateFile( string fileName, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, IDokanFileInfo info); /// <summary> /// Receipt of this request indicates that the last handle for a file object that is associated /// with the target device object has been closed (but, due to outstanding I/O requests, /// might not have been released). /// /// Cleanup is requested before <see cref="CloseFile"/> is called. /// </summary> /// <remarks> /// When <see cref="IDokanFileInfo.DeleteOnClose"/> is <c>true</c>, you must delete the file in Cleanup. /// Refer to <see cref="DeleteFile"/> and <see cref="DeleteDirectory"/> for explanation. /// </remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <seealso cref="DeleteFile"/> /// <seealso cref="DeleteDirectory"/> /// <seealso cref="CloseFile"/> void Cleanup(string fileName, IDokanFileInfo info); /// <summary> /// CloseFile is called at the end of the life of the context. /// /// Receipt of this request indicates that the last handle of the file object that is associated /// with the target device object has been closed and released. All outstanding I/O requests /// have been completed or canceled. /// /// CloseFile is requested after <see cref="Cleanup"/> is called. /// /// Remainings in <see cref="IDokanFileInfo.Context"/> has to be cleared before return. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <seealso cref="Cleanup"/> void CloseFile(string fileName, IDokanFileInfo info); /// <summary> /// ReadFile callback on the file previously opened in <see cref="CreateFile"/>. /// It can be called by different thread at the same time, /// therefor the read has to be thread safe. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="buffer">Read buffer that has to be fill with the read result. /// The buffer size depend of the read size requested by the kernel.</param> /// <param name="bytesRead">Total number of bytes that has been read.</param> /// <param name="offset">Offset from where the read has to be proceed.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="WriteFile"/> NtStatus ReadFile(string fileName, byte[] buffer, out int bytesRead, long offset, IDokanFileInfo info); /// <summary> /// WriteFile callback on the file previously opened in <see cref="CreateFile"/> /// It can be called by different thread at the same time, /// therefor the write/context has to be thread safe. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="buffer">Data that has to be written.</param> /// <param name="bytesWritten">Total number of bytes that has been write.</param> /// <param name="offset">Offset from where the write has to be proceed.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="ReadFile"/> NtStatus WriteFile(string fileName, byte[] buffer, out int bytesWritten, long offset, IDokanFileInfo info); /// <summary> /// Clears buffers for this context and causes any buffered data to be written to the file. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus FlushFileBuffers(string fileName, IDokanFileInfo info); /// <summary> /// Get specific informations on a file. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="fileInfo"><see cref="FileInformation"/> struct to fill</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus GetFileInformation(string fileName, out FileInformation fileInfo, IDokanFileInfo info); /// <summary> /// List all files in the path requested /// /// <see cref="FindFilesWithPattern"/> is checking first. If it is not implemented or /// returns <see cref="NtStatus.NotImplemented"/>, then FindFiles is called. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="files">A list of <see cref="FileInformation"/> to return.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="FindFilesWithPattern"/> NtStatus FindFiles(string fileName, out IList<FileInformation> files, IDokanFileInfo info); /// <summary> /// Same as <see cref="FindFiles"/> but with a search pattern to filter the result. /// </summary> /// <param name="fileName">Path requested by the Kernel on the FileSystem.</param> /// <param name="searchPattern">Search pattern</param> /// <param name="files">A list of <see cref="FileInformation"/> to return.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="FindFiles"/> NtStatus FindFilesWithPattern( string fileName, string searchPattern, out IList<FileInformation> files, IDokanFileInfo info); /// <summary> /// Set file attributes on a specific file. /// </summary> /// <remarks>SetFileAttributes and <see cref="SetFileTime"/> are called only if both of them are implemented.</remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="attributes"><see cref="FileAttributes"/> to set on file</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetFileAttributes(string fileName, FileAttributes attributes, IDokanFileInfo info); /// <summary> /// Set file times on a specific file. /// If <see cref="DateTime"/> is <c>null</c>, this should not be updated. /// </summary> /// <remarks><see cref="SetFileAttributes"/> and SetFileTime are called only if both of them are implemented.</remarks> /// <param name="fileName">File or directory name.</param> /// <param name="creationTime"><see cref="DateTime"/> when the file was created.</param> /// <param name="lastAccessTime"><see cref="DateTime"/> when the file was last accessed.</param> /// <param name="lastWriteTime"><see cref="DateTime"/> when the file was last written to.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetFileTime( string fileName, DateTime? creationTime, DateTime? lastAccessTime, DateTime? lastWriteTime, IDokanFileInfo info); /// <summary> /// Check if it is possible to delete a file. /// </summary> /// <remarks> /// You should NOT delete the file in DeleteFile, but instead /// you must only check whether you can delete the file or not, /// and return <see cref="NtStatus.Success"/> (when you can delete it) or appropriate error /// codes such as <see cref="NtStatus.AccessDenied"/>, <see cref="NtStatus.ObjectNameNotFound"/>. /// /// DeleteFile will also be called with <see cref="IDokanFileInfo.DeleteOnClose"/> set to <c>false</c> /// to notify the driver when the file is no longer requested to be deleted. /// /// When you return <see cref="NtStatus.Success"/>, you get a <see cref="Cleanup"/> call afterwards with /// <see cref="IDokanFileInfo.DeleteOnClose"/> set to <c>true</c> and only then you have to actually /// delete the file being closed. /// </remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns>Return <see cref="DokanResult.Success"/> if file can be delete or <see cref="NtStatus"/> appropriate.</returns> /// <seealso cref="DeleteDirectory"/> /// <seealso cref="Cleanup"/> NtStatus DeleteFile(string fileName, IDokanFileInfo info); /// <summary> /// Check if it is possible to delete a directory. /// </summary> /// <remarks> /// You should NOT delete the file in <see cref="DeleteDirectory"/>, but instead /// you must only check whether you can delete the file or not, /// and return <see cref="NtStatus.Success"/> (when you can delete it) or appropriate error /// codes such as <see cref="NtStatus.AccessDenied"/>, <see cref="NtStatus.ObjectPathNotFound"/>, /// <see cref="NtStatus.ObjectNameNotFound"/>. /// /// DeleteFile will also be called with <see cref="IDokanFileInfo.DeleteOnClose"/> set to <c>false</c> /// to notify the driver when the file is no longer requested to be deleted. /// /// When you return <see cref="NtStatus.Success"/>, you get a <see cref="Cleanup"/> call afterwards with /// <see cref="IDokanFileInfo.DeleteOnClose"/> set to <c>true</c> and only then you have to actually /// delete the file being closed. /// </remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns>Return <see cref="DokanResult.Success"/> if file can be delete or <see cref="NtStatus"/> appropriate.</returns> /// <seealso cref="DeleteFile"/> /// <seealso cref="Cleanup"/> NtStatus DeleteDirectory(string fileName, IDokanFileInfo info); /// <summary> /// Move a file or directory to a new location. /// </summary> /// <param name="oldName">Path to the file to move.</param> /// <param name="newName">Path to the new location for the file.</param> /// <param name="replace">If the file should be replaced if it already exist a file with path <paramref name="newName"/>.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus MoveFile(string oldName, string newName, bool replace, IDokanFileInfo info); /// <summary> /// SetEndOfFile is used to truncate or extend a file (physical file size). /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="length">File length to set</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetEndOfFile(string fileName, long length, IDokanFileInfo info); /// <summary> /// SetAllocationSize is used to truncate or extend a file. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="length">File length to set</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetAllocationSize(string fileName, long length, IDokanFileInfo info); /// <summary> /// Lock file at a specific offset and data length. /// This is only used if <see cref="DokanOptions.UserModeLock"/> is enabled. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="offset">Offset from where the lock has to be proceed.</param> /// <param name="length">Data length to lock.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="UnlockFile"/> NtStatus LockFile(string fileName, long offset, long length, IDokanFileInfo info); /// <summary> /// Unlock file at a specific offset and data length. /// This is only used if <see cref="DokanOptions.UserModeLock"/> is enabled. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="offset">Offset from where the unlock has to be proceed.</param> /// <param name="length">Data length to lock.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="LockFile"/> NtStatus UnlockFile(string fileName, long offset, long length, IDokanFileInfo info); /// <summary> /// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, /// the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread. /// </summary> /// <remarks> /// Neither GetDiskFreeSpace nor <see cref="GetVolumeInformation"/> save the <see cref="IDokanFileInfo.Context"/>. /// Before these methods are called, <see cref="CreateFile"/> may not be called. (ditto <see cref="CloseFile"/> and <see cref="Cleanup"/>). /// </remarks> /// <param name="freeBytesAvailable">Amount of available space.</param> /// <param name="totalNumberOfBytes">Total size of storage space.</param> /// <param name="totalNumberOfFreeBytes">Amount of free space.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx"> GetDiskFreeSpaceEx function (MSDN)</a> /// <seealso cref="GetVolumeInformation"/> NtStatus GetDiskFreeSpace( out long freeBytesAvailable, out long totalNumberOfBytes, out long totalNumberOfFreeBytes, IDokanFileInfo info); /// <summary> /// Retrieves information about the file system and volume associated with the specified root directory. /// </summary> /// <remarks> /// Neither GetVolumeInformation nor <see cref="GetDiskFreeSpace"/> save the <see cref="IDokanFileInfo.Context"/>. /// Before these methods are called, <see cref="CreateFile"/> may not be called. (ditto <see cref="CloseFile"/> and <see cref="Cleanup"/>). /// /// <see cref="FileSystemFeatures.ReadOnlyVolume"/> is automatically added to the <paramref name="features"/> if <see cref="DokanOptions.WriteProtection"/> was /// specified when the volume was mounted. /// /// If <see cref="NtStatus.NotImplemented"/> is returned, the %Dokan kernel driver use following settings by default: /// | Parameter | Default value | /// |------------------------------|--------------------------------------------------------------------------------------------------| /// | \a rawVolumeNameBuffer | <c>"DOKAN"</c> | /// | \a rawVolumeSerialNumber | <c>0x19831116</c> | /// | \a rawMaximumComponentLength | <c>256</c> | /// | \a rawFileSystemFlags | <c>CaseSensitiveSearch \|\| CasePreservedNames \|\| SupportsRemoteStorage \|\| UnicodeOnDisk</c> | /// | \a rawFileSystemNameBuffer | <c>"NTFS"</c> | /// </remarks> /// <param name="volumeLabel">Volume name</param> /// <param name="features"><see cref="FileSystemFeatures"/> with features enabled on the volume.</param> /// <param name="fileSystemName">The name of the specified volume.</param> /// <param name="maximumComponentLength">File name component that the specified file system supports.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364993(v=vs.85).aspx"> GetVolumeInformation function (MSDN)</a> NtStatus GetVolumeInformation( out string volumeLabel, out FileSystemFeatures features, out string fileSystemName, out uint maximumComponentLength, IDokanFileInfo info); /// <summary> /// Get specified information about the security of a file or directory. /// </summary> /// <remarks> /// If <see cref="NtStatus.NotImplemented"/> is returned, dokan library will handle the request by /// building a sddl of the current process user with authenticate user rights for context menu. /// </remarks> /// \since Supported since version 0.6.0. You must specify the version in <see cref="Dokan.Mount(IDokanOperations, string, DokanOptions,int, int, TimeSpan, string, int,int, Logging.ILogger)"/>. /// /// <param name="fileName">File or directory name.</param> /// <param name="security">A <see cref="FileSystemSecurity"/> with security information to return.</param> /// <param name="sections">A <see cref="AccessControlSections"/> with access sections to return.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="SetFileSecurity"/> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa446639(v=vs.85).aspx">GetFileSecurity function (MSDN)</a> NtStatus GetFileSecurity( string fileName, out FileSystemSecurity security, AccessControlSections sections, IDokanFileInfo info); /// <summary> /// Sets the security of a file or directory object. /// </summary> /// \since Supported since version 0.6.0. You must specify the version in <see cref="Dokan.Mount(IDokanOperations, string, DokanOptions,int, int, TimeSpan, string, int,int, Logging.ILogger)"/>. /// /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="security">A <see cref="FileSystemSecurity"/> with security information to set.</param> /// <param name="sections">A <see cref="AccessControlSections"/> with access sections on which.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="GetFileSecurity"/> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa379577(v=vs.85).aspx">SetFileSecurity function (MSDN)</a> NtStatus SetFileSecurity( string fileName, FileSystemSecurity security, AccessControlSections sections, IDokanFileInfo info); /// <summary> /// Is called when %Dokan succeed to mount the volume. /// /// If <see cref="DokanOptions.MountManager"/> is enabled and the drive letter requested is busy, /// the <paramref name="mountPoint"/> can contain a different drive letter that the mount manager assigned us. /// </summary> /// <param name="mountPoint">The mount point assign to the instance.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <see cref="Unmounted"/> NtStatus Mounted(string mountPoint, IDokanFileInfo info); /// <summary> /// Is called when %Dokan is unmounting the volume. /// </summary> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="Mounted"/> NtStatus Unmounted(IDokanFileInfo info); /// <summary> /// Retrieve all NTFS Streams informations on the file. /// This is only called if <see cref="DokanOptions.AltStream"/> is enabled. /// </summary> /// <remarks>For files, the first item in <paramref name="streams"/> is information about the /// default data stream <c>"::$DATA"</c>.</remarks> /// \since Supported since version 0.8.0. You must specify the version in <see cref="Dokan.Mount(IDokanOperations, string, DokanOptions,int, int, TimeSpan, string, int,int, Logging.ILogger)"/>. /// /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="streams">List of <see cref="FileInformation"/> for each streams present on the file.</param> /// <param name="info">An <see cref="IDokanFileInfo"/> with information about the file or directory.</param> /// <returns>Return <see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364424(v=vs.85).aspx">FindFirstStreamW function (MSDN)</a> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365993(v=vs.85).aspx">About KTM (MSDN)</a> NtStatus FindStreams(string fileName, out IList<FileInformation> streams, IDokanFileInfo info); } } /// <summary> /// Namespace for AssemblyInfo and resource strings /// </summary> namespace DokanNet.Properties { // This is only for documentation of the DokanNet.Properties namespace. }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Abstractions; using System.IO.Abstractions.TestingHelpers; using NSubstitute; using NUnit.Framework; using TSQLLint.Common; using TSQLLint.Core.Interfaces; using TSQLLint.Infrastructure.Parser; using TSQLLint.Tests.Helpers; namespace TSQLLint.Tests.UnitTests.Parser { [TestFixture] public class SqlFileProcessorTests { [Test] public void ProcessPath_SingleFile_ShouldProcessFile() { // arrange const string filePath = "c:\\dbscripts\\myfile.sql"; var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var fileSystem = Substitute.For<IFileSystem>(); var fileBase = Substitute.For<FileBase>(); var pluginHandler = Substitute.For<IPluginHandler>(); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); fileBase.Exists(filePath).Returns(true); fileBase.OpenRead(filePath).Returns(ParsingUtility.GenerateStreamFromString("Some Sql To Parse")); fileSystem.File.Returns(fileBase); // act processor.ProcessPath("\" " + filePath + " \""); // Also testing removal of quotes and leading/trailing spaces // assert fileBase.Received().Exists(filePath); fileBase.Received().OpenRead(filePath); ruleVisitor.Received().VisitRules(filePath, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(1, processor.FileCount); } [Test] public void ProcessPath_PathWithSpaces_ShouldProcessFiles() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.SQL"); var filePath2 = TestHelper.GetTestFilePath(@"c:\dbscripts\file2.txt"); var filePath3 = TestHelper.GetTestFilePath(@"c:\dbscripts\file3.sql"); var filePath4 = TestHelper.GetTestFilePath(@"c:\dbscripts\file4.Sql"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var pluginHandler = Substitute.For<IPluginHandler>(); var reporter = Substitute.For<IReporter>(); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData("File1SQL") }, { filePath2, new MockFileData("File2SQL") }, { filePath3, new MockFileData("File3SQL") }, { filePath4, new MockFileData("File4SQL") } }); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(TestHelper.GetTestFilePath(@"c:\dbscripts")); // assert ruleVisitor.Received().VisitRules(filePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath3, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath4, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.DidNotReceive().VisitRules(filePath2, Arg.Any<IEnumerable<IRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(3, processor.FileCount); } [Test] public void ProcessPath_DirectorySpecified_ShouldProcessSubDirectories() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.SQL"); var filePath2 = TestHelper.GetTestFilePath(@"c:\dbscripts\db1\file2.sql"); var filePath3 = TestHelper.GetTestFilePath(@"c:\dbscripts\db2\file3.sql"); var filePath4 = TestHelper.GetTestFilePath(@"c:\dbscripts\db2\sproc\file4.Sql"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData("File1SQL") }, { filePath2, new MockFileData("File2SQL") }, { filePath3, new MockFileData("File3SQL") }, { filePath4, new MockFileData("File4SQL") } }); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(TestHelper.GetTestFilePath(@"c:\dbscripts")); // assert ruleVisitor.Received().VisitRules(filePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath2, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath3, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath4, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(4, processor.FileCount); } [Test] public void ProcessPath_InvalidPathSpecified_ShouldNotProcessFiles() { // arrange const string filePath = "This doesnt exist"; var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var fileSystem = Substitute.For<IFileSystem>(); var fileBase = Substitute.For<FileBase>(); var pluginHandler = Substitute.For<IPluginHandler>(); fileBase.Exists(filePath).Returns(false); fileSystem.File.Returns(fileBase); var directoryBase = Substitute.For<DirectoryBase>(); directoryBase.Exists(filePath).Returns(false); fileSystem.Directory.Returns(directoryBase); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(filePath); // assert fileBase.Received().Exists(filePath); directoryBase.Received().Exists(filePath); ruleVisitor.DidNotReceive().VisitRules(filePath, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); reporter.Received().Report($"{filePath} is not a valid file path."); Assert.AreEqual(0, processor.FileCount); } [Test] public void ProcessPath_QuestionMarkWildCard_ShouldProcessFilesWithWildcard() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.SQL"); var filePath2 = TestHelper.GetTestFilePath(@"c:\dbscripts\file2.txt"); var filePath3 = TestHelper.GetTestFilePath(@"c:\dbscripts\file3.sql"); var filePath4 = TestHelper.GetTestFilePath(@"c:\dbscripts\file4.Sql"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData("File1SQL") }, { filePath2, new MockFileData("File2SQL") }, { filePath3, new MockFileData("File3SQL") }, { filePath4, new MockFileData("File4SQL") } }); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(TestHelper.GetTestFilePath(@"c:\dbscripts\file?.sql")); // assert ruleVisitor.Received().VisitRules(filePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath3, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath4, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.DidNotReceive().VisitRules(filePath2, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(3, processor.FileCount); } [Test] public void ProcessPath_DirectorSpecifiedWildcard_ShouldOnlyProcessSqlFilesInSpecificDirectory() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.SQL"); var filePath2 = TestHelper.GetTestFilePath(@"c:\dbscripts\file2.txt"); var filePath3 = TestHelper.GetTestFilePath(@"c:\dbscripts\file3.sql"); var filePath4 = TestHelper.GetTestFilePath(@"c:\dbscripts\file4.Sql"); var filePath5 = TestHelper.GetTestFilePath(@"c:\file4.Sql"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData("File1SQL") }, { filePath2, new MockFileData("File2SQL") }, { filePath3, new MockFileData("File3SQL") }, { filePath4, new MockFileData("File4SQL") }, { filePath5, new MockFileData("File5SQL") } }); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(TestHelper.GetTestFilePath(@"c:\dbscripts\file*.*")); // assert ruleVisitor.Received().VisitRules(filePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath3, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath4, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.DidNotReceive().VisitRules(filePath2, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.DidNotReceive().VisitRules(filePath5, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(3, processor.FileCount); } [Test] public void ProcessPath_WildcardInvalidDirectory_ShouldNotProcess() { // arrange var sqlFilePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.SQL"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem( new Dictionary<string, MockFileData> { { sqlFilePath1, new MockFileData("File1SQL") } }, TestHelper.GetTestFilePath(@"c:\dbscripts")); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(TestHelper.GetTestFilePath(@"c:\doesntExist\file*.*")); // assert ruleVisitor.DidNotReceive().VisitRules(sqlFilePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(0, processor.FileCount); } [Test] public void ProcessPath_Wildcard_ShouldOnlyProcessSqlFilesInCurrentDirectory() { // arrange var sqlFilePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.SQL"); var txtFilePath2 = TestHelper.GetTestFilePath(@"c:\dbscripts\file2.txt"); var sqlFilePath3 = TestHelper.GetTestFilePath(@"c:\dbscripts\file3.sql"); var sqlFilePath4 = TestHelper.GetTestFilePath(@"c:\dbscripts\file4.Sql"); var sqlFilePath5 = TestHelper.GetTestFilePath(@"c:\file4.Sql"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem( new Dictionary<string, MockFileData> { { sqlFilePath1, new MockFileData("File1SQL") }, { txtFilePath2, new MockFileData("File2SQL") }, { sqlFilePath3, new MockFileData("File3SQL") }, { sqlFilePath4, new MockFileData("File4SQL") }, { sqlFilePath5, new MockFileData("File5SQL") } }, TestHelper.GetTestFilePath(@"c:\dbscripts")); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(@"file*.*"); // assert ruleVisitor.Received().VisitRules(sqlFilePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(sqlFilePath3, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(sqlFilePath4, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); // should not visit text files ruleVisitor.DidNotReceive().VisitRules(txtFilePath2, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); // should only visit files in current directory ruleVisitor.DidNotReceive().VisitRules(sqlFilePath5, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(3, processor.FileCount); } [Test] public void ProcessPath_InvalidPath_ShouldNotProcess() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.txt"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData("File1SQL") } }); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessPath(TestHelper.GetTestFilePath(@"c:\dbscripts\invalid*.*")); // assert ruleVisitor.DidNotReceive().VisitRules(filePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); reporter.DidNotReceive().Report(Arg.Any<string>()); Assert.AreEqual(0, processor.FileCount); } [Test] public void ProcessList_EmptyList_ShouldNotProcess() { // arrange var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var fileSystem = Substitute.For<IFileSystem>(); var pluginHandler = Substitute.For<IPluginHandler>(); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessList(new List<string>()); // assert ruleVisitor.DidNotReceive().VisitRules(Arg.Any<string>(), Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(0, processor.FileCount); } [Test] public void ProcessList_ListOfPaths_ShouldOnlyProcessFilesInList() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\file1.SQL"); var filePath2 = TestHelper.GetTestFilePath(@"c:\dbscripts\db1\file2.sql"); var filePath3 = TestHelper.GetTestFilePath(@"c:\dbscripts\db2\file3.sql"); var filePath4 = TestHelper.GetTestFilePath(@"c:\dbscripts\db2\sproc\file4.Sql"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData("File1SQL") }, { filePath2, new MockFileData("File2SQL") }, { filePath3, new MockFileData("File3SQL") }, { filePath4, new MockFileData("File4SQL") } }); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); var f1 = TestHelper.GetTestFilePath(@"c:\dbscripts\db2\sproc"); var f2 = TestHelper.GetTestFilePath(@"c:\dbscripts\db2\file3.sql"); var multiPathString = $@" {f1}, {f2}"; // act // tests quotes, extra spaces, commas, multiple items in the list processor.ProcessList(new List<string> { multiPathString, TestHelper.GetTestFilePath(@"c:\dbscripts\db1\") }); // assert ruleVisitor.DidNotReceive().VisitRules(filePath1, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath2, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath3, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath4, Arg.Any<IEnumerable<IExtendedRuleException>>(), Arg.Any<Stream>()); Assert.AreEqual(3, processor.FileCount); } [Test] public void ProcessList_InvalidPaths_ShouldProcessValidPaths() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\dbscripts\db1\file2.sql"); var filePath2 = TestHelper.GetTestFilePath(@"c:\dbscripts\db1\file3.sql"); var invalidFilePath = TestHelper.GetTestFilePath(@"c:\invalid\invalid.sql"); var ruleVisitor = Substitute.For<IRuleVisitor>(); var reporter = Substitute.For<IReporter>(); var pluginHandler = Substitute.For<IPluginHandler>(); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData("File1SQL") }, { filePath2, new MockFileData("File2SQL") } }); var processor = new SqlFileProcessor(ruleVisitor, pluginHandler, reporter, fileSystem); // act processor.ProcessList(new List<string> { invalidFilePath, TestHelper.GetTestFilePath(@"c:\dbscripts\db1\") }); // assert ruleVisitor.DidNotReceive().VisitRules(invalidFilePath, Arg.Any<IEnumerable<IRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath1, Arg.Any<IEnumerable<IRuleException>>(), Arg.Any<Stream>()); ruleVisitor.Received().VisitRules(filePath2, Arg.Any<IEnumerable<IRuleException>>(), Arg.Any<Stream>()); reporter.Received().Report($@"{invalidFilePath} is not a valid file path."); Assert.AreEqual(2, processor.FileCount); } } }
/* * 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Util; namespace QuantConnect.Securities { /// <summary> /// Base class caching caching spot for security data and any other temporary properties. /// </summary> /// <remarks> /// This class is virtually unused and will soon be made obsolete. /// This comment made in a remark to prevent obsolete errors in all users algorithms /// </remarks> public class SecurityCache { // this is used to prefer quote bar data over the tradebar data private DateTime _lastQuoteBarUpdate; private DateTime _lastOHLCUpdate; private BaseData _lastData; private IReadOnlyList<BaseData> _lastTickQuotes = new List<BaseData>(); private IReadOnlyList<BaseData> _lastTickTrades = new List<BaseData>(); private ConcurrentDictionary<Type, IReadOnlyList<BaseData>> _dataByType = new ConcurrentDictionary<Type, IReadOnlyList<BaseData>>(); /// <summary> /// Gets the most recent price submitted to this cache /// </summary> public decimal Price { get; private set; } /// <summary> /// Gets the most recent open submitted to this cache /// </summary> public decimal Open { get; private set; } /// <summary> /// Gets the most recent high submitted to this cache /// </summary> public decimal High { get; private set; } /// <summary> /// Gets the most recent low submitted to this cache /// </summary> public decimal Low { get; private set; } /// <summary> /// Gets the most recent close submitted to this cache /// </summary> public decimal Close { get; private set; } /// <summary> /// Gets the most recent bid submitted to this cache /// </summary> public decimal BidPrice { get; private set; } /// <summary> /// Gets the most recent ask submitted to this cache /// </summary> public decimal AskPrice { get; private set; } /// <summary> /// Gets the most recent bid size submitted to this cache /// </summary> public decimal BidSize { get; private set; } /// <summary> /// Gets the most recent ask size submitted to this cache /// </summary> public decimal AskSize { get; private set; } /// <summary> /// Gets the most recent volume submitted to this cache /// </summary> public decimal Volume { get; private set; } /// <summary> /// Gets the most recent open interest submitted to this cache /// </summary> public long OpenInterest { get; private set; } /// <summary> /// Add a list of market data points to the local security cache for the current market price. /// </summary> /// <remarks>Internally uses <see cref="AddData"/> using the last data point of the provided list /// and it stores by type the non fill forward points using <see cref="StoreData"/></remarks> public void AddDataList(IReadOnlyList<BaseData> data, Type dataType, bool? containsFillForwardData = null) { var nonFillForwardData = data; // maintaining regression requires us to NOT cache FF data if (containsFillForwardData != false) { var dataFiltered = new List<BaseData>(data.Count); for (var i = 0; i < data.Count; i++) { var dataPoint = data[i]; if (!dataPoint.IsFillForward) { dataFiltered.Add(dataPoint); } } nonFillForwardData = dataFiltered; } if (nonFillForwardData.Count != 0) { StoreData(nonFillForwardData, dataType); } else if (dataType == typeof(OpenInterest)) { StoreData(data, typeof(OpenInterest)); } var last = data[data.Count - 1]; AddDataImpl(last, cacheByType: false); } /// <summary> /// Add a new market data point to the local security cache for the current market price. /// Rules: /// Don't cache fill forward data. /// Always return the last observation. /// If two consecutive data has the same time stamp and one is Quotebars and the other Tradebar, prioritize the Quotebar. /// </summary> public void AddData(BaseData data) { AddDataImpl(data, cacheByType: true); } private void AddDataImpl(BaseData data, bool cacheByType) { var tick = data as Tick; if (tick?.TickType == TickType.OpenInterest) { if (cacheByType) { StoreDataPoint(data); } OpenInterest = (long)tick.Value; return; } // Only cache non fill-forward data. if (data.IsFillForward) return; if (cacheByType) { StoreDataPoint(data); } var isDefaultDataType = SubscriptionManager.IsDefaultDataType(data); // don't set _lastData if receive quotebar then tradebar w/ same end time. this // was implemented to grant preference towards using quote data in the fill // models and provide a level of determinism on the values exposed via the cache. if ((_lastData == null || _lastQuoteBarUpdate != data.EndTime || data.DataType != MarketDataType.TradeBar) // we will only set the default data type to preserve determinism and backwards compatibility && isDefaultDataType) { _lastData = data; } if (tick != null) { if (tick.Value != 0) Price = tick.Value; switch (tick.TickType) { case TickType.Trade: if (tick.Quantity != 0) Volume = tick.Quantity; break; case TickType.Quote: if (tick.BidPrice != 0) BidPrice = tick.BidPrice; if (tick.BidSize != 0) BidSize = tick.BidSize; if (tick.AskPrice != 0) AskPrice = tick.AskPrice; if (tick.AskSize != 0) AskSize = tick.AskSize; break; } return; } var bar = data as IBar; if (bar != null) { // we will only set OHLC values using the default data type to preserve determinism and backwards compatibility. // Gives priority to QuoteBar over TradeBar, to be removed when default data type completely addressed GH issue 4196 if ((_lastQuoteBarUpdate != data.EndTime || _lastOHLCUpdate != data.EndTime) && isDefaultDataType) { _lastOHLCUpdate = data.EndTime; if (bar.Open != 0) Open = bar.Open; if (bar.High != 0) High = bar.High; if (bar.Low != 0) Low = bar.Low; if (bar.Close != 0) { Price = bar.Close; Close = bar.Close; } } var tradeBar = bar as TradeBar; if (tradeBar != null) { if (tradeBar.Volume != 0) Volume = tradeBar.Volume; } var quoteBar = bar as QuoteBar; if (quoteBar != null) { _lastQuoteBarUpdate = quoteBar.EndTime; if (quoteBar.Ask != null && quoteBar.Ask.Close != 0) AskPrice = quoteBar.Ask.Close; if (quoteBar.Bid != null && quoteBar.Bid.Close != 0) BidPrice = quoteBar.Bid.Close; if (quoteBar.LastBidSize != 0) BidSize = quoteBar.LastBidSize; if (quoteBar.LastAskSize != 0) AskSize = quoteBar.LastAskSize; } } else if (data.DataType != MarketDataType.Auxiliary) { Price = data.Price; } } /// <summary> /// Stores the specified data list in the cache WITHOUT updating any of the cache properties, such as Price /// </summary> /// <param name="data">The collection of data to store in this cache</param> /// <param name="dataType">The data type</param> public void StoreData(IReadOnlyList<BaseData> data, Type dataType) { if (dataType == typeof(Tick)) { var tick = data[data.Count - 1] as Tick; switch (tick?.TickType) { case TickType.Trade: _lastTickTrades = data; return; case TickType.Quote: _lastTickQuotes = data; return; } } _dataByType[dataType] = data; } /// <summary> /// Get last data packet received for this security /// </summary> /// <returns>BaseData type of the security</returns> public BaseData GetData() { return _lastData; } /// <summary> /// Get last data packet received for this security of the specified type /// </summary> /// <typeparam name="T">The data type</typeparam> /// <returns>The last data packet, null if none received of type</returns> public T GetData<T>() where T : BaseData { IReadOnlyList<BaseData> list; if (!TryGetValue(typeof(T), out list) || list.Count == 0) { return default(T); } return list[list.Count - 1] as T; } /// <summary> /// Gets all data points of the specified type from the most recent time step /// that produced data for that type /// </summary> public IEnumerable<T> GetAll<T>() { if (typeof(T) == typeof(Tick)) { return _lastTickTrades.Concat(_lastTickQuotes).Cast<T>(); } IReadOnlyList<BaseData> list; if (!_dataByType.TryGetValue(typeof(T), out list)) { return new List<T>(); } return list.Cast<T>(); } /// <summary> /// Reset cache storage and free memory /// </summary> public void Reset() { _dataByType.Clear(); _lastTickQuotes = new List<BaseData>(); _lastTickTrades = new List<BaseData>(); } /// <summary> /// Gets whether or not this dynamic data instance has data stored for the specified type /// </summary> public bool HasData(Type type) { IReadOnlyList<BaseData> data; return TryGetValue(type, out data); } /// <summary> /// Gets whether or not this dynamic data instance has data stored for the specified type /// </summary> public bool TryGetValue(Type type, out IReadOnlyList<BaseData> data) { if (type == typeof(Tick)) { var quote = _lastTickQuotes.LastOrDefault(); var trade = _lastTickTrades.LastOrDefault(); var isQuoteDefaultDataType = quote != null && SubscriptionManager.IsDefaultDataType(quote); var isTradeDefaultDataType = trade != null && SubscriptionManager.IsDefaultDataType(trade); // Currently, IsDefaultDataType returns true for both cases, // So we will return the list with the tick with the most recent timestamp if (isQuoteDefaultDataType && isTradeDefaultDataType) { data = quote.EndTime > trade.EndTime ? _lastTickQuotes : _lastTickTrades; return true; } data = isQuoteDefaultDataType ? _lastTickQuotes : _lastTickTrades; return data?.Count > 0; } return _dataByType.TryGetValue(type, out data); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void StoreDataPoint(BaseData data) { if (data.GetType() == typeof(Tick)) { var tick = data as Tick; switch (tick?.TickType) { case TickType.Trade: _lastTickTrades = new List<BaseData> { tick }; break; case TickType.Quote: _lastTickQuotes = new List<BaseData> { tick }; break; } } else { // Always keep track of the last observation IReadOnlyList<BaseData> list; if (!_dataByType.TryGetValue(data.GetType(), out list)) { list = new List<BaseData> { data }; _dataByType[data.GetType()] = list; } else { // we KNOW this one is actually a list, so this is safe // we overwrite the zero entry so we're not constantly newing up lists ((List<BaseData>)list)[0] = data; } } } /// <summary> /// Helper method that modifies the target security cache instance to use the /// type cache of the source /// </summary> /// <remarks>Will set in the source cache any data already present in the target cache</remarks> /// <remarks>This is useful for custom data securities which also have an underlying security, /// will allow both securities to access the same data by type</remarks> /// <param name="sourceToShare">The source cache to use</param> /// <param name="targetToModify">The target security cache that will be modified</param> public static void ShareTypeCacheInstance(SecurityCache sourceToShare, SecurityCache targetToModify) { foreach (var kvp in targetToModify._dataByType) { sourceToShare._dataByType.TryAdd(kvp.Key, kvp.Value); } targetToModify._dataByType = sourceToShare._dataByType; targetToModify._lastTickTrades = sourceToShare._lastTickTrades; targetToModify._lastTickQuotes = sourceToShare._lastTickQuotes; } } }
using System; using System.ComponentModel; using Android.Graphics; using Java.Lang; using TXTCommunication.Fischertechnik.Txt; using TXTCommunication.Fischertechnik.Txt.Camera; using Exception = System.Exception; namespace FtApp.Droid.Activities.ControlInterface { /// <summary> /// This static class handles the communication with the camera of the TXT Controller /// </summary> internal static class FtInterfaceCameraProxy { /// <summary> /// This event is fired when a new frame arrived and is stored in the ImageBitmap object /// </summary> public static event CameraFrameDecodedEventHandler CameraFrameDecoded; public delegate void CameraFrameDecodedEventHandler(object sender, FrameDecodedEventArgs eventArgs); /// <summary> /// This event is fired when the bitmap was cleaned up and is now recycled /// </summary> public static event ImageBitmapCleanupEventHandler ImageBitmapCleanup; public delegate void ImageBitmapCleanupEventHandler(object sender, EventArgs eventArgs); /// <summary> /// This event is fired when the bitmap was initialized and contains data /// </summary> public static event ImageBitmapInitializedEventHandler ImageBitmapInitialized; public delegate void ImageBitmapInitializedEventHandler(object sender, EventArgs eventArgs); private static TxtInterface Interface { get; set; } /// <summary> /// This bitmap object contains the actual frame /// </summary> public static Bitmap ImageBitmap { get; private set; } private static BitmapFactory.Options ImageOptions { get; set; } /// <summary> /// true when the first frame arrived otherwise false /// </summary> public static bool FirstFrame { get; private set; } /// <summary> /// true when a camera is available otherwise false /// </summary> public static bool CameraAvailable { get; private set; } /// <summary> /// true when the camera stream is running otherwise false /// </summary> public static bool CameraStreaming { get; private set; } static FtInterfaceCameraProxy() { FtInterfaceInstanceProvider.InstanceChanged += FtInterfaceInstanceProviderOnInstanceChanged; } private static void FtInterfaceInstanceProviderOnInstanceChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { if (FtInterfaceInstanceProvider.Instance == null) { // Clean the bitmap memory when the instance is null CleanupBitmapMemory(); return; } Interface = FtInterfaceInstanceProvider.Instance as TxtInterface; CameraAvailable = Interface != null; } private static void TxtCameraOnFrameReceived(object sender, FrameReceivedEventArgs frameReceivedEventArgs) { // When a new frame arrived we decode it and fire an event DecodeBitmap(frameReceivedEventArgs.FrameData, frameReceivedEventArgs.DataLength); CameraFrameDecoded?.Invoke(null, new FrameDecodedEventArgs(FirstFrame)); FirstFrame = false; } /// <summary> /// Starts the camera stream /// </summary> public static void StartCameraStream() { // ReSharper disable once UseNullPropagation if (CameraAvailable && Interface != null && !CameraStreaming) { if (Interface.TxtCamera != null) { CameraStreaming = true; SetupBitmap(); FirstFrame = true; Interface.TxtCamera.FrameReceived += TxtCameraOnFrameReceived; Interface.TxtCamera.StartCamera(); } } } /// <summary> /// Stops the camera stream /// </summary> public static void StopCameraStream() { if (CameraAvailable && Interface != null && CameraStreaming) { if (Interface.TxtCamera != null) { try { CameraStreaming = false; Interface.TxtCamera.FrameReceived -= TxtCameraOnFrameReceived; // Stop the stream and cleanup the frame bitmap Interface.TxtCamera.StopCamera(); CleanupBitmapMemory(); } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } } } } private static void DecodeBitmap(byte[] bytes, int length) { if (ImageBitmap != null && !ImageBitmap.IsRecycled && !FirstFrame) { // When the bitmap is initialized and not recycled we set it as InBitmap in the ImageOptions to reuse the frame memory of the frame before ImageOptions.InBitmap = ImageBitmap; } // We decode the frame using ImageOptions try { ImageBitmap = BitmapFactory.DecodeByteArray(bytes, 0, length, ImageOptions); } catch (IllegalArgumentException) { // Sometimes when the image changes very fast (i.e. you shake the camera) we are unable to decode the frame return; } if (FirstFrame) { ImageBitmapInitialized?.Invoke(null, EventArgs.Empty); } } private static void SetupBitmap() { // First clean the bitmap memory to prevent memory leaks CleanupBitmapMemory(); ImageOptions = new BitmapFactory.Options { InMutable = true }; } private static void CleanupBitmapMemory() { if (ImageBitmap != null) { ImageBitmapCleanup?.Invoke(null, EventArgs.Empty); // Recycle and Dispose the bitmap if (!ImageBitmap.IsRecycled) { ImageBitmap.Recycle(); } ImageBitmap.Dispose(); ImageBitmap = null; } if (ImageOptions != null) { ImageOptions.Dispose(); ImageBitmap = null; } } } internal class FrameDecodedEventArgs : EventArgs { public readonly bool FirstFrame; internal FrameDecodedEventArgs(bool firstFrame) { FirstFrame = firstFrame; } } }
namespace Nancy { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Nancy.Configuration; using Nancy.ModelBinding; using Nancy.Responses.Negotiation; using Nancy.Routing; using Nancy.Session; using Nancy.Validation; using Nancy.ViewEngines; /// <summary> /// Basic class containing the functionality for defining routes and actions in Nancy. /// </summary> public abstract class NancyModule : INancyModule, IHideObjectMembers { private readonly List<Route> routes; /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> protected NancyModule() : this(String.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> /// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param> protected NancyModule(string modulePath) { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.OnError = new ErrorPipeline(); this.ModulePath = modulePath; this.routes = new List<Route>(); } /// <summary> /// Non-model specific data for rendering in the response /// </summary> public dynamic ViewBag { get { return this.Context == null ? null : this.Context.ViewBag; } } public dynamic Text { get { return this.Context.Text; } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for DELETE requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Delete { get { return new RouteBuilder("DELETE", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for GET requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Get { get { return new RouteBuilder("GET", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for HEAD requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Head { get { return new RouteBuilder("HEAD", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for OPTIONS requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Options { get { return new RouteBuilder("OPTIONS", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PATCH requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Patch { get { return new RouteBuilder("PATCH", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for POST requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Post { get { return new RouteBuilder("POST", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PUT requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Put { get { return new RouteBuilder("PUT", this); } } /// <summary> /// Get the root path of the routes in the current module. /// </summary> /// <value> /// A <see cref="T:System.String" /> containing the root path of the module or <see langword="null" /> /// if no root path should be used.</value><remarks>All routes will be relative to this root path. /// </remarks> public string ModulePath { get; protected set; } /// <summary> /// Gets all declared routes by the module. /// </summary> /// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public virtual IEnumerable<Route> Routes { get { return this.routes.AsReadOnly(); } } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get { return this.Request.Session; } } /// <summary> /// Renders a view from inside a route handler. /// </summary> /// <value>A <see cref="ViewRenderer"/> instance that is used to determine which view that should be rendered.</value> public ViewRenderer View { get { return new ViewRenderer(this); } } /// <summary> /// Used to negotiate the content returned based on Accepts header. /// </summary> /// <value>A <see cref="Negotiator"/> instance that is used to negotiate the content returned.</value> public Negotiator Negotiate { get { return new Negotiator(this.Context); } } /// <summary> /// Gets or sets the validator locator. /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelValidatorLocator ValidatorLocator { get; set; } /// <summary> /// Gets or sets an <see cref="Request"/> instance that represents the current request. /// </summary> /// <value>An <see cref="Request"/> instance.</value> public virtual Request Request { get { return this.Context.Request; } set { this.Context.Request = value; } } /// <summary> /// The extension point for accessing the view engines in Nancy. /// </summary><value>An <see cref="IViewFactory" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IViewFactory ViewFactory { get; set; } /// <summary><para> /// The post-request hook /// </para><para> /// The post-request hook is called after the response is created by the route execution. /// It can be used to rewrite the response or add/remove items from the context. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public AfterPipeline After { get; set; } /// <summary> /// <para> /// The pre-request hook /// </para> /// <para> /// The PreRequest hook is called prior to executing a route. If any item in the /// pre-request pipeline returns a response then the route is not executed and the /// response is returned. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public BeforePipeline Before { get; set; } /// <summary> /// <para> /// The error hook /// </para> /// <para> /// The error hook is called if an exception is thrown at any time during executing /// the PreRequest hook, a route and the PostRequest hook. It can be used to set /// the response and/or finish any ongoing tasks (close database session, etc). /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public ErrorPipeline OnError { get; set; } /// <summary> /// Gets or sets the current Nancy context /// </summary> /// <value>A <see cref="NancyContext" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> public NancyContext Context { get; set; } /// <summary> /// An extension point for adding support for formatting response contents. /// </summary><value>This property will always return <see langword="null" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref="P:Nancy.NancyModuleBase.Response" /> or one of the types that can implicitly be types into a <see cref="P:Nancy.NancyModuleBase.Response" />.</remarks> public IResponseFormatter Response { get; set; } /// <summary> /// Gets or sets the model binder locator /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelBinderLocator ModelBinderLocator { get; set; } /// <summary> /// Gets or sets the model validation result /// </summary> /// <remarks>This is automatically set by Nancy at runtime when you run validation.</remarks> public virtual ModelValidationResult ModelValidationResult { get { return this.Context == null ? null : this.Context.ModelValidationResult; } set { if (this.Context != null) { this.Context.ModelValidationResult = value; } } } /// <summary> /// Helper class for configuring a route handler in a module. /// </summary> public class RouteBuilder : IHideObjectMembers { private readonly string method; private readonly NancyModule parentModule; /// <summary> /// Initializes a new instance of the <see cref="RouteBuilder"/> class. /// </summary> /// <param name="method">The HTTP request method that the route should be available for.</param> /// <param name="parentModule">The <see cref="INancyModule"/> that the route is being configured for.</param> public RouteBuilder(string method, NancyModule parentModule) { this.method = method; this.parentModule = parentModule; } /// <summary> /// Defines an async route for the specified <paramref name="path"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string path] { set { this.AddRoute(string.Empty, path, null, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> and <paramref name="condition"/>. /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, Func<NancyContext, bool> condition] { set { this.AddRoute(string.Empty, path, condition, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> and <paramref name="name"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path] { set { this.AddRoute(name, path, null, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, Func<NancyContext, bool> condition] { set { this.AddRoute(name, path, condition, value); } } protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, CancellationToken, Task<dynamic>> value) { var fullPath = GetFullPath(path); this.parentModule.routes.Add(new Route(name, this.method, fullPath, condition, value)); } private string GetFullPath(string path) { var relativePath = (path ?? string.Empty).Trim('/'); var parentPath = (this.parentModule.ModulePath ?? string.Empty).Trim('/'); if (string.IsNullOrEmpty(parentPath)) { return string.Concat("/", relativePath); } if (string.IsNullOrEmpty(relativePath)) { return string.Concat("/", parentPath); } return string.Concat("/", parentPath, "/", relativePath); } } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using VR = UnityEngine.VR; /// <summary> /// A head-tracked stereoscopic virtual reality camera rig. /// </summary> [ExecuteInEditMode] public class OVRCameraRig : MonoBehaviour { /// <summary> /// The left eye camera. /// </summary> public Camera leftEyeCamera { get { return (usePerEyeCameras) ? _leftEyeCamera : _centerEyeCamera; } } /// <summary> /// The right eye camera. /// </summary> public Camera rightEyeCamera { get { return (usePerEyeCameras) ? _rightEyeCamera : _centerEyeCamera; } } /// <summary> /// Provides a root transform for all anchors in tracking space. /// </summary> public Transform trackingSpace { get; private set; } /// <summary> /// Always coincides with the pose of the left eye. /// </summary> public Transform leftEyeAnchor { get; private set; } /// <summary> /// Always coincides with average of the left and right eye poses. /// </summary> public Transform centerEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right eye. /// </summary> public Transform rightEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the left hand. /// </summary> public Transform leftHandAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right hand. /// </summary> public Transform rightHandAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the sensor. /// </summary> public Transform trackerAnchor { get; private set; } /// <summary> /// Occurs when the eye pose anchors have been set. /// </summary> public event System.Action<OVRCameraRig> UpdatedAnchors; /// <summary> /// If true, separate cameras will be used for the left and right eyes. /// </summary> public bool usePerEyeCameras = false; private readonly string trackingSpaceName = "TrackingSpace"; private readonly string trackerAnchorName = "TrackerAnchor"; private readonly string eyeAnchorName = "EyeAnchor"; private readonly string handAnchorName = "HandAnchor"; private readonly string legacyEyeAnchorName = "Camera"; private Camera _centerEyeCamera; private Camera _leftEyeCamera; private Camera _rightEyeCamera; #if UNITY_ANDROID && !UNITY_EDITOR bool correctedTrackingSpace = false; #endif #region Unity Messages private void Awake() { EnsureGameObjectIntegrity(); } private void Start() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateAnchors(); } private void Update() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateAnchors(); #if UNITY_ANDROID && !UNITY_EDITOR if (!correctedTrackingSpace) { //HACK: Unity 5.1.1p3 double-counts the head model on Android. Subtract it off in the reference frame. var headModel = new Vector3(0f, OVRManager.profile.eyeHeight - OVRManager.profile.neckHeight, OVRManager.profile.eyeDepth); var eyePos = -headModel + centerEyeAnchor.localRotation * headModel; if ((eyePos - centerEyeAnchor.localPosition).magnitude > 0.01f) { trackingSpace.localPosition = trackingSpace.localPosition - 2f * (trackingSpace.localRotation * headModel); correctedTrackingSpace = true; } } #endif } #endregion private void UpdateAnchors() { bool monoscopic = OVRManager.instance.monoscopic; OVRPose tracker = OVRManager.tracker.GetPose(); trackerAnchor.localRotation = tracker.orientation; centerEyeAnchor.localRotation = VR.InputTracking.GetLocalRotation(VR.VRNode.CenterEye); leftEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : VR.InputTracking.GetLocalRotation(VR.VRNode.LeftEye); rightEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : VR.InputTracking.GetLocalRotation(VR.VRNode.RightEye); leftHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch); rightHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch); trackerAnchor.localPosition = tracker.position; centerEyeAnchor.localPosition = Vector3.zero; VR.InputTracking.GetLocalPosition(VR.VRNode.CenterEye); leftEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : VR.InputTracking.GetLocalPosition(VR.VRNode.LeftEye); rightEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : VR.InputTracking.GetLocalPosition(VR.VRNode.RightEye); leftHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch); rightHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch); if (UpdatedAnchors != null) { UpdatedAnchors(this); } } public void EnsureGameObjectIntegrity() { if (trackingSpace == null) trackingSpace = ConfigureRootAnchor(trackingSpaceName); if (leftEyeAnchor == null) leftEyeAnchor = ConfigureEyeAnchor(trackingSpace, VR.VRNode.LeftEye); if (centerEyeAnchor == null) centerEyeAnchor = ConfigureEyeAnchor(trackingSpace, VR.VRNode.CenterEye); if (rightEyeAnchor == null) rightEyeAnchor = ConfigureEyeAnchor(trackingSpace, VR.VRNode.RightEye); if (leftHandAnchor == null) leftHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.HandLeft); if (rightHandAnchor == null) rightHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.HandRight); if (trackerAnchor == null) trackerAnchor = ConfigureTrackerAnchor(trackingSpace); if (_centerEyeCamera == null || _leftEyeCamera == null || _rightEyeCamera == null) { _centerEyeCamera = centerEyeAnchor.GetComponent<Camera>(); _leftEyeCamera = leftEyeAnchor.GetComponent<Camera>(); _rightEyeCamera = rightEyeAnchor.GetComponent<Camera>(); if (_centerEyeCamera == null) { _centerEyeCamera = centerEyeAnchor.gameObject.AddComponent<Camera>(); _centerEyeCamera.tag = "MainCamera"; } if (_leftEyeCamera == null) { _leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>(); _leftEyeCamera.tag = "MainCamera"; #if !UNITY_5_4_OR_NEWER usePerEyeCameras = false; Debug.Log("Please set left eye Camera's Target Eye to Left before using."); #endif } if (_rightEyeCamera == null) { _rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>(); _rightEyeCamera.tag = "MainCamera"; #if !UNITY_5_4_OR_NEWER usePerEyeCameras = false; Debug.Log("Please set right eye Camera's Target Eye to Right before using."); #endif } #if UNITY_5_4_OR_NEWER _centerEyeCamera.stereoTargetEye = StereoTargetEyeMask.Both; _leftEyeCamera.stereoTargetEye = StereoTargetEyeMask.Left; _rightEyeCamera.stereoTargetEye = StereoTargetEyeMask.Right; #endif } _centerEyeCamera.enabled = !usePerEyeCameras; _leftEyeCamera.enabled = usePerEyeCameras; _rightEyeCamera.enabled = usePerEyeCameras; } private Transform ConfigureRootAnchor(string name) { Transform root = transform.Find(name); if (root == null) { root = new GameObject(name).transform; } root.parent = transform; root.localScale = Vector3.one; root.localPosition = Vector3.zero; root.localRotation = Quaternion.identity; return root; } private Transform ConfigureEyeAnchor(Transform root, VR.VRNode eye) { string eyeName = (eye == VR.VRNode.CenterEye) ? "Center" : (eye == VR.VRNode.LeftEye) ? "Left" : "Right"; string name = eyeName + eyeAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = transform.Find(name); } if (anchor == null) { string legacyName = legacyEyeAnchorName + eye.ToString(); anchor = transform.Find(legacyName); } if (anchor == null) { anchor = new GameObject(name).transform; } anchor.name = name; anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Transform ConfigureHandAnchor(Transform root, OVRPlugin.Node hand) { string handName = (hand == OVRPlugin.Node.HandLeft) ? "Left" : "Right"; string name = handName + handAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = transform.Find(name); } if (anchor == null) { anchor = new GameObject(name).transform; } anchor.name = name; anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Transform ConfigureTrackerAnchor(Transform root) { string name = trackerAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = new GameObject(name).transform; } anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Swagger { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// &gt; the above JSON query pushes this markdown section into node /// `$.info.description` of the OpenAPI definition. /// /// This client that can be used to manage Azure Search services and API /// keys. /// </summary> public partial class SearchManagementClient : ServiceClient<SearchManagementClient>, ISearchManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. /// The subscription ID forms part of the URI for every service call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The client API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IQueryKeysOperations. /// </summary> public virtual IQueryKeysOperations QueryKeys { get; private set; } /// <summary> /// Gets the IServicesOperations. /// </summary> public virtual IServicesOperations Services { get; private set; } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SearchManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SearchManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { QueryKeys = new QueryKeysOperations(this); Services = new ServicesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2015-02-28"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Reflection; /* * Regression tests for the mono JIT. * * Each test needs to be of the form: * * public static int test_<result>_<name> (); * * where <result> is an integer (the value that needs to be returned by * the method to make it pass. * <name> is a user-displayed name used to identify the test. * * The tests can be driven in two ways: * *) running the program directly: Main() uses reflection to find and invoke * the test methods (this is useful mostly to check that the tests are correct) * *) with the --regression switch of the jit (this is the preferred way since * all the tests will be run with optimizations on and off) * * The reflection logic could be moved to a .dll since we need at least another * regression test file written in IL code to have better control on how * the IL code looks. */ #if MOBILE class CallsTests #else class Tests #endif { #if !MOBILE public static int Main (string[] args) { return TestDriver.RunTests (typeof (Tests), args); } #endif static void dummy () { } public static int test_0_return () { dummy (); return 0; } static int dummy1 () { return 1; } public static int test_2_int_return () { int r = dummy1 (); if (r == 1) return 2; return 0; } static int add1 (int val) { return val + 1; } public static int test_1_int_pass () { int r = add1 (5); if (r == 6) return 1; return 0; } static int add_many (int val, short t, byte b, int da) { return val + t + b + da; } public static int test_1_int_pass_many () { byte b = 6; int r = add_many (5, 2, b, 1); if (r == 14) return 1; return 0; } unsafe static float GetFloat (byte *ptr) { return *(float*)ptr; } unsafe public static float GetFloat(float value) { return GetFloat((byte *)&value); } /* bug #42134 */ public static int test_2_inline_saved_arg_type () { float f = 100.0f; return GetFloat (f) == f? 2: 1; } static int pass_many_types (int a, long b, int c, long d) { return a + (int)b + c + (int)d; } public static int test_5_pass_longs () { return pass_many_types (1, 2, -5, 7); } static int overflow_registers (int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) { return a+b+c+d+e+f+g+h+i+j; } public static int test_55_pass_even_more () { return overflow_registers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } static int pass_ints_longs (int a, long b, long c, long d, long e, int f, long g) { return (int)(a + b + c + d + e + f + g); } public static int test_1_sparc_argument_passing () { // The 4. argument tests split reg/mem argument passing // The 5. argument tests mem argument passing // The 7. argument tests passing longs in misaligned memory // The MaxValues are needed so the MS word of the long is not 0 return pass_ints_longs (1, 2, System.Int64.MaxValue, System.Int64.MinValue, System.Int64.MaxValue, 0, System.Int64.MinValue); } static int pass_bytes (byte a, byte b, byte c, byte d, byte e, byte f, byte g) { return (int)(a + b + c + d + e + f + g); } public static int test_21_sparc_byte_argument_passing () { return pass_bytes (0, 1, 2, 3, 4, 5, 6); } static int pass_sbytes (sbyte a, sbyte b, sbyte c, sbyte d, sbyte e, sbyte f, sbyte g, sbyte h1, sbyte h2, sbyte h3, sbyte h4) { return (int)(a + b + c + d + e + f + g + h1 + h2 + h3 + h4); } public static int test_55_sparc_sbyte_argument_passing () { return pass_sbytes (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } static int pass_shorts (short a, short b, short c, short d, short e, short f, short g) { return (int)(a + b + c + d + e + f + g); } public static int test_21_sparc_short_argument_passing () { return pass_shorts (0, 1, 2, 3, 4, 5, 6); } static int pass_floats_doubles (float a, double b, double c, double d, double e, float f, double g) { return (int)(a + b + c + d + e + f + g); } public static int test_721_sparc_float_argument_passing () { return pass_floats_doubles (100.0f, 101.0, 102.0, 103.0, 104.0, 105.0f, 106.0); } static float pass_floats (float a, float b, float c, float d, float e, float f, float g, float h, float i, float j) { return a + b + c + d + e + f + g + h + i + j; } public static int test_55_sparc_float_argument_passing2 () { return (int)pass_floats (1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); } public static bool is_small (float value) { double d = (double)value; double d2 = 7.183757E-41; return d - d2 < 0.000001; } public static int test_0_float_argument_passing_precision () { float f = 7.183757E-41f; return is_small (f) ? 0 : 1; } // The first argument must be passed on a dword aligned stack location static int pass_byref_ints_longs (ref long a, ref int b, ref byte c, ref short d, ref long e, ref int f, ref long g) { return (int)(a + b + c + d + e + f + g); } static int pass_takeaddr_ints_longs (long a, int b, byte c, short d, long e, int f, long g) { return pass_byref_ints_longs (ref a, ref b, ref c, ref d, ref e, ref f, ref g); } // Test that arguments are moved to the stack from incoming registers // when the argument must reside in the stack because its address is taken public static int test_2_sparc_takeaddr_argument_passing () { return pass_takeaddr_ints_longs (1, 2, 253, -253, System.Int64.MaxValue, 0, System.Int64.MinValue); } static int pass_byref_floats_doubles (ref float a, ref double b, ref double c, ref double d, ref double e, ref float f, ref double g) { return (int)(a + b + c + d + e + f + g); } static int pass_takeaddr_floats_doubles (float a, double b, double c, double d, double e, float f, double g) { return pass_byref_floats_doubles (ref a, ref b, ref c, ref d, ref e, ref f, ref g); } public static int test_721_sparc_takeaddr_argument_passing2 () { return pass_takeaddr_floats_doubles (100.0f, 101.0, 102.0, 103.0, 104.0, 105.0f, 106.0); } static void pass_byref_double (out double d) { d = 5.0; } // Test byref double argument passing public static int test_0_sparc_byref_double_argument_passing () { double d; pass_byref_double (out d); return (d == 5.0) ? 0 : 1; } static void shift_un_arg (ulong value) { do { value = value >> 4; } while (value != 0); } // Test that assignment to long arguments work public static int test_0_long_arg_assign () { ulong c = 0x800000ff00000000; shift_un_arg (c >> 4); return 0; } static unsafe void* ptr_return (void *ptr) { return ptr; } public static unsafe int test_0_ptr_return () { void *ptr = new IntPtr (55).ToPointer (); if (ptr_return (ptr) == ptr) return 0; else return 1; } static bool isnan (float f) { return (f != f); } public static int test_0_isnan () { float f = 1.0f; return isnan (f) ? 1 : 0; } static int first_is_zero (int v1, int v2) { if (v1 != 0) return -1; return v2; } public static int test_1_handle_dup_stloc () { int index = 0; int val = first_is_zero (index, ++index); if (val != 1) return 2; return 1; } static long return_5low () { return 5; } static long return_5high () { return 0x500000000; } public static int test_3_long_ret () { long val = return_5low (); return (int) (val - 2); } public static int test_1_long_ret2 () { long val = return_5high (); if (val > 0xffffffff) return 1; return 0; } public static void use_long_arg (ulong l) { for (int i = 0; i < 10; ++i) l ++; } public static ulong return_long_arg (object o, ulong perm) { use_long_arg (perm); perm = 0x8000000000000FFF; use_long_arg (perm); return perm; } public static int test_0_sparc_long_ret_regress_541577 () { ulong perm = 0x8000000000000FFF; ulong work = return_long_arg (null, perm); return work == perm ? 0 : 1; } static void doit (double value, out long m) { m = (long) value; } public static int test_0_ftol_clobber () { long m; doit (1.3, out m); if (m != 1) return 2; return 0; } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Services.Events; namespace Nop.Services.Catalog { /// <summary> /// Product attribute service /// </summary> public partial class ProductAttributeService : IProductAttributeService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : page index /// {1} : page size /// </remarks> private const string PRODUCTATTRIBUTES_ALL_KEY = "Nop.productattribute.all-{0}-{1}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product attribute ID /// </remarks> private const string PRODUCTATTRIBUTES_BY_ID_KEY = "Nop.productattribute.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product ID /// </remarks> private const string PRODUCTVARIANTATTRIBUTES_ALL_KEY = "Nop.productvariantattribute.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product variant attribute ID /// </remarks> private const string PRODUCTVARIANTATTRIBUTES_BY_ID_KEY = "Nop.productvariantattribute.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product variant attribute ID /// </remarks> private const string PRODUCTVARIANTATTRIBUTEVALUES_ALL_KEY = "Nop.productvariantattributevalue.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product variant attribute value ID /// </remarks> private const string PRODUCTVARIANTATTRIBUTEVALUES_BY_ID_KEY = "Nop.productvariantattributevalue.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : product ID /// </remarks> private const string PRODUCTVARIANTATTRIBUTECOMBINATIONS_ALL_KEY = "Nop.productvariantattributecombination.all-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTATTRIBUTES_PATTERN_KEY = "Nop.productattribute."; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTVARIANTATTRIBUTES_PATTERN_KEY = "Nop.productvariantattribute."; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY = "Nop.productvariantattributevalue."; /// <summary> /// Key pattern to clear cache /// </summary> private const string PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY = "Nop.productvariantattributecombination."; #endregion #region Fields private readonly IRepository<ProductAttribute> _productAttributeRepository; private readonly IRepository<ProductVariantAttribute> _productVariantAttributeRepository; private readonly IRepository<ProductVariantAttributeCombination> _productVariantAttributeCombinationRepository; private readonly IRepository<ProductVariantAttributeValue> _productVariantAttributeValueRepository; private readonly IEventPublisher _eventPublisher; private readonly ICacheManager _cacheManager; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="productAttributeRepository">Product attribute repository</param> /// <param name="productVariantAttributeRepository">Product variant attribute mapping repository</param> /// <param name="productVariantAttributeCombinationRepository">Product variant attribute combination repository</param> /// <param name="productVariantAttributeValueRepository">Product variant attribute value repository</param> /// <param name="eventPublisher">Event published</param> public ProductAttributeService(ICacheManager cacheManager, IRepository<ProductAttribute> productAttributeRepository, IRepository<ProductVariantAttribute> productVariantAttributeRepository, IRepository<ProductVariantAttributeCombination> productVariantAttributeCombinationRepository, IRepository<ProductVariantAttributeValue> productVariantAttributeValueRepository, IEventPublisher eventPublisher ) { _cacheManager = cacheManager; _productAttributeRepository = productAttributeRepository; _productVariantAttributeRepository = productVariantAttributeRepository; _productVariantAttributeCombinationRepository = productVariantAttributeCombinationRepository; _productVariantAttributeValueRepository = productVariantAttributeValueRepository; _eventPublisher = eventPublisher; } #endregion #region Methods #region Product attributes /// <summary> /// Deletes a product attribute /// </summary> /// <param name="productAttribute">Product attribute</param> public virtual void DeleteProductAttribute(ProductAttribute productAttribute) { if (productAttribute == null) throw new ArgumentNullException("productAttribute"); _productAttributeRepository.Delete(productAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productAttribute); } /// <summary> /// Gets all product attributes /// </summary> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns>Product attribute collection</returns> public virtual IPagedList<ProductAttribute> GetAllProductAttributes(int pageIndex = 0, int pageSize = int.MaxValue) { string key = string.Format(PRODUCTATTRIBUTES_ALL_KEY, pageIndex, pageSize); return _cacheManager.Get(key, () => { var query = from pa in _productAttributeRepository.Table orderby pa.Name select pa; var productAttributes = new PagedList<ProductAttribute>(query, pageIndex, pageSize); return productAttributes; }); } /// <summary> /// Gets a product attribute /// </summary> /// <param name="productAttributeId">Product attribute identifier</param> /// <returns>Product attribute </returns> public virtual ProductAttribute GetProductAttributeById(int productAttributeId) { if (productAttributeId == 0) return null; string key = string.Format(PRODUCTATTRIBUTES_BY_ID_KEY, productAttributeId); return _cacheManager.Get(key, () => { return _productAttributeRepository.GetById(productAttributeId); }); } /// <summary> /// Inserts a product attribute /// </summary> /// <param name="productAttribute">Product attribute</param> public virtual void InsertProductAttribute(ProductAttribute productAttribute) { if (productAttribute == null) throw new ArgumentNullException("productAttribute"); _productAttributeRepository.Insert(productAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(productAttribute); } /// <summary> /// Updates the product attribute /// </summary> /// <param name="productAttribute">Product attribute</param> public virtual void UpdateProductAttribute(ProductAttribute productAttribute) { if (productAttribute == null) throw new ArgumentNullException("productAttribute"); _productAttributeRepository.Update(productAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(productAttribute); } #endregion #region Product variant attributes mappings (ProductVariantAttribute) /// <summary> /// Deletes a product variant attribute mapping /// </summary> /// <param name="productVariantAttribute">Product variant attribute mapping</param> public virtual void DeleteProductVariantAttribute(ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) throw new ArgumentNullException("productVariantAttribute"); _productVariantAttributeRepository.Delete(productVariantAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productVariantAttribute); } /// <summary> /// Gets product variant attribute mappings by product identifier /// </summary> /// <param name="productId">The product identifier</param> /// <returns>Product variant attribute mapping collection</returns> public virtual IList<ProductVariantAttribute> GetProductVariantAttributesByProductId(int productId) { string key = string.Format(PRODUCTVARIANTATTRIBUTES_ALL_KEY, productId); return _cacheManager.Get(key, () => { var query = from pva in _productVariantAttributeRepository.Table orderby pva.DisplayOrder where pva.ProductId == productId select pva; var productVariantAttributes = query.ToList(); return productVariantAttributes; }); } /// <summary> /// Gets a product variant attribute mapping /// </summary> /// <param name="productVariantAttributeId">Product variant attribute mapping identifier</param> /// <returns>Product variant attribute mapping</returns> public virtual ProductVariantAttribute GetProductVariantAttributeById(int productVariantAttributeId) { if (productVariantAttributeId == 0) return null; string key = string.Format(PRODUCTVARIANTATTRIBUTES_BY_ID_KEY, productVariantAttributeId); return _cacheManager.Get(key, () => { return _productVariantAttributeRepository.GetById(productVariantAttributeId); }); } /// <summary> /// Inserts a product variant attribute mapping /// </summary> /// <param name="productVariantAttribute">The product variant attribute mapping</param> public virtual void InsertProductVariantAttribute(ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) throw new ArgumentNullException("productVariantAttribute"); _productVariantAttributeRepository.Insert(productVariantAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(productVariantAttribute); } /// <summary> /// Updates the product variant attribute mapping /// </summary> /// <param name="productVariantAttribute">The product variant attribute mapping</param> public virtual void UpdateProductVariantAttribute(ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) throw new ArgumentNullException("productVariantAttribute"); _productVariantAttributeRepository.Update(productVariantAttribute); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(productVariantAttribute); } #endregion #region Product variant attribute values (ProductVariantAttributeValue) /// <summary> /// Deletes a product variant attribute value /// </summary> /// <param name="productVariantAttributeValue">Product variant attribute value</param> public virtual void DeleteProductVariantAttributeValue(ProductVariantAttributeValue productVariantAttributeValue) { if (productVariantAttributeValue == null) throw new ArgumentNullException("productVariantAttributeValue"); _productVariantAttributeValueRepository.Delete(productVariantAttributeValue); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productVariantAttributeValue); } /// <summary> /// Gets product variant attribute values by product identifier /// </summary> /// <param name="productVariantAttributeId">The product variant attribute mapping identifier</param> /// <returns>Product variant attribute mapping collection</returns> public virtual IList<ProductVariantAttributeValue> GetProductVariantAttributeValues(int productVariantAttributeId) { string key = string.Format(PRODUCTVARIANTATTRIBUTEVALUES_ALL_KEY, productVariantAttributeId); return _cacheManager.Get(key, () => { var query = from pvav in _productVariantAttributeValueRepository.Table orderby pvav.DisplayOrder where pvav.ProductVariantAttributeId == productVariantAttributeId select pvav; var productVariantAttributeValues = query.ToList(); return productVariantAttributeValues; }); } /// <summary> /// Gets a product variant attribute value /// </summary> /// <param name="productVariantAttributeValueId">Product variant attribute value identifier</param> /// <returns>Product variant attribute value</returns> public virtual ProductVariantAttributeValue GetProductVariantAttributeValueById(int productVariantAttributeValueId) { if (productVariantAttributeValueId == 0) return null; string key = string.Format(PRODUCTVARIANTATTRIBUTEVALUES_BY_ID_KEY, productVariantAttributeValueId); return _cacheManager.Get(key, () => { return _productVariantAttributeValueRepository.GetById(productVariantAttributeValueId); }); } /// <summary> /// Inserts a product variant attribute value /// </summary> /// <param name="productVariantAttributeValue">The product variant attribute value</param> public virtual void InsertProductVariantAttributeValue(ProductVariantAttributeValue productVariantAttributeValue) { if (productVariantAttributeValue == null) throw new ArgumentNullException("productVariantAttributeValue"); _productVariantAttributeValueRepository.Insert(productVariantAttributeValue); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(productVariantAttributeValue); } /// <summary> /// Updates the product variant attribute value /// </summary> /// <param name="productVariantAttributeValue">The product variant attribute value</param> public virtual void UpdateProductVariantAttributeValue(ProductVariantAttributeValue productVariantAttributeValue) { if (productVariantAttributeValue == null) throw new ArgumentNullException("productVariantAttributeValue"); _productVariantAttributeValueRepository.Update(productVariantAttributeValue); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(productVariantAttributeValue); } #endregion #region Product variant attribute combinations (ProductVariantAttributeCombination) /// <summary> /// Deletes a product variant attribute combination /// </summary> /// <param name="combination">Product variant attribute combination</param> public virtual void DeleteProductVariantAttributeCombination(ProductVariantAttributeCombination combination) { if (combination == null) throw new ArgumentNullException("combination"); _productVariantAttributeCombinationRepository.Delete(combination); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(combination); } /// <summary> /// Gets all product variant attribute combinations /// </summary> /// <param name="productId">Product identifier</param> /// <returns>Product variant attribute combination collection</returns> public virtual IList<ProductVariantAttributeCombination> GetAllProductVariantAttributeCombinations(int productId) { if (productId == 0) return new List<ProductVariantAttributeCombination>(); string key = string.Format(PRODUCTVARIANTATTRIBUTECOMBINATIONS_ALL_KEY, productId); return _cacheManager.Get(key, () => { var query = from pvac in _productVariantAttributeCombinationRepository.Table orderby pvac.Id where pvac.ProductId == productId select pvac; var combinations = query.ToList(); return combinations; }); } /// <summary> /// Gets a product variant attribute combination /// </summary> /// <param name="productVariantAttributeCombinationId">Product variant attribute combination identifier</param> /// <returns>Product variant attribute combination</returns> public virtual ProductVariantAttributeCombination GetProductVariantAttributeCombinationById(int productVariantAttributeCombinationId) { if (productVariantAttributeCombinationId == 0) return null; return _productVariantAttributeCombinationRepository.GetById(productVariantAttributeCombinationId); } /// <summary> /// Inserts a product variant attribute combination /// </summary> /// <param name="combination">Product variant attribute combination</param> public virtual void InsertProductVariantAttributeCombination(ProductVariantAttributeCombination combination) { if (combination == null) throw new ArgumentNullException("combination"); _productVariantAttributeCombinationRepository.Insert(combination); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(combination); } /// <summary> /// Updates a product variant attribute combination /// </summary> /// <param name="combination">Product variant attribute combination</param> public virtual void UpdateProductVariantAttributeCombination(ProductVariantAttributeCombination combination) { if (combination == null) throw new ArgumentNullException("combination"); _productVariantAttributeCombinationRepository.Update(combination); //cache _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTECOMBINATIONS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(combination); } #endregion #endregion } }
// 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.Diagnostics.Contracts; using System; namespace System.IO { public class Path { #if !SILVERLIGHT && !NETFRAMEWORK_3_5 // // Summary: // Combines an array of strings into a path. // // Parameters: // paths: // An array of parts of the path. // // Returns: // The combined paths. // // Exceptions: // System.ArgumentException: // One of the strings in the array contains one or more of the invalid characters // defined in System.IO.Path.GetInvalidPathChars(). // // System.ArgumentNullException: // One of the strings in the array is null. [Pure] public static string Combine(params string[] paths) { Contract.Requires(paths != null); Contract.Requires(Contract.ForAll(paths, path => path != null)); Contract.Ensures(Contract.Result<string>() != null); return default(string); } // // Summary: // Combines three strings into a path. // // Parameters: // path1: // The first path to combine. // // path2: // The second path to combine. // // path3: // The third path to combine. // // Returns: // The combined paths. // // Exceptions: // System.ArgumentException: // path1, path2, or path3 contains one or more of the invalid characters defined // in System.IO.Path.GetInvalidPathChars(). // // System.ArgumentNullException: // path1, path2, or path3 is null. [Pure] public static string Combine(string path1, string path2, string path3) { Contract.Requires(path1 != null); Contract.Requires(path2 != null); Contract.Requires(path3 != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } // // Summary: // Combines four strings into a path. // // Parameters: // path1: // The first path to combine. // // path2: // The second path to combine. // // path3: // The third path to combine. // // path4: // The fourth path to combine. // // Returns: // The combined paths. // // Exceptions: // System.ArgumentException: // path1, path2, path3, or path4 contains one or more of the invalid characters // defined in System.IO.Path.GetInvalidPathChars(). // // System.ArgumentNullException: // path1, path2, path3, or path4 is null. [Pure] public static string Combine(string path1, string path2, string path3, string path4) { Contract.Requires(path1 != null); Contract.Requires(path2 != null); Contract.Requires(path3 != null); Contract.Requires(path4 != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } #endif [Pure] public static string Combine(string path1, string path2) { Contract.Requires(path1 != null); Contract.Requires(path2 != null); Contract.Ensures(Contract.Result<string>() != null); Contract.Ensures(Contract.Result<string>().Length >= path2.Length); Contract.Ensures(!IsPathRooted(path2) || Contract.Result<string>() == path2); Contract.Ensures(IsPathRooted(path2) || Contract.Result<string>().Length >= path1.Length + path2.Length); //This was wrong: Contract.Ensures(Contract.Result<string>().Length >= path1.Length + path2.Length); //MSDN: If path2 includes a root, path2 is returned return default(string); } [Pure] public static bool IsPathRooted(string path) { Contract.Ensures(!Contract.Result<bool>() || path.Length > 0); return default(bool); } [Pure] public static bool HasExtension(string path) { Contract.Ensures(!Contract.Result<bool>() || path.Length > 0); return default(bool); } [Pure] public static string GetPathRoot(string path) { Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length); return default(string); } [Pure] public static string GetFileNameWithoutExtension(string path) { Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length); return default(string); } [Pure] public static string GetFileName(string path) { Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length); return default(string); } [Pure] public static string GetFullPath(string path) { Contract.Requires(path != null); Contract.Ensures(Contract.Result<string>() != null); Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length."); return default(string); } [Pure] public static string GetExtension(string path) { Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length); return default(string); } [Pure] public static string GetDirectoryName(string path) { Contract.Ensures(path == null || Contract.Result<string>().Length <= path.Length); Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs."); return default(string); } [Pure] public static string ChangeExtension(string path, string extension) { Contract.Ensures(path == null || Contract.Result<string>() != null); return default(string); } #if !SILVERLIGHT [Pure] public static char[] GetInvalidFileNameChars() { Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } #endif [Pure] public static char[] GetInvalidPathChars() { Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } #if !SILVERLIGHT public static string GetRandomFileName() { Contract.Ensures(Contract.Result<string>() != null); return default(string); } #endif public static string GetTempFileName() { Contract.Ensures(Contract.Result<string>() != null); Contract.Ensures(Contract.Result<string>().Length >= 4, @" length >= 4 since file name must end with '.TMP'"); Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurs, such as no unique temporary file name is available. - or - This method was unable to create a temporary file."); return default(string); } public static string GetTempPath() { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** #if !NETCF_1_0 using System; using System.Runtime.InteropServices; namespace PclUnit.Constraints.Pieces { /// <summary>Helper routines for working with floating point numbers</summary> /// <remarks> /// <para> /// The floating point comparison code is based on this excellent article: /// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm /// </para> /// <para> /// "ULP" means Unit in the Last Place and in the context of this library refers to /// the distance between two adjacent floating point numbers. IEEE floating point /// numbers can only represent a finite subset of natural numbers, with greater /// accuracy for smaller numbers and lower accuracy for very large numbers. /// </para> /// <para> /// If a comparison is allowed "2 ulps" of deviation, that means the values are /// allowed to deviate by up to 2 adjacent floating point values, which might be /// as low as 0.0000001 for small numbers or as high as 10.0 for large numbers. /// </para> /// </remarks> public class FloatingPointNumerics { #region struct FloatIntUnion /// <summary>Union of a floating point variable and an integer</summary> [StructLayout(LayoutKind.Explicit)] private struct FloatIntUnion { /// <summary>The union's value as a floating point variable</summary> [FieldOffset(0)] public float Float; /// <summary>The union's value as an integer</summary> [FieldOffset(0)] public int Int; /// <summary>The union's value as an unsigned integer</summary> [FieldOffset(0)] public uint UInt; } #endregion // struct FloatIntUnion #region struct DoubleLongUnion /// <summary>Union of a double precision floating point variable and a long</summary> [StructLayout(LayoutKind.Explicit)] private struct DoubleLongUnion { /// <summary>The union's value as a double precision floating point variable</summary> [FieldOffset(0)] public double Double; /// <summary>The union's value as a long</summary> [FieldOffset(0)] public long Long; /// <summary>The union's value as an unsigned long</summary> [FieldOffset(0)] public ulong ULong; } #endregion // struct DoubleLongUnion /// <summary>Compares two floating point values for equality</summary> /// <param name="left">First floating point value to be compared</param> /// <param name="right">Second floating point value t be compared</param> /// <param name="maxUlps"> /// Maximum number of representable floating point values that are allowed to /// be between the left and the right floating point values /// </param> /// <returns>True if both numbers are equal or close to being equal</returns> /// <remarks> /// <para> /// Floating point values can only represent a finite subset of natural numbers. /// For example, the values 2.00000000 and 2.00000024 can be stored in a float, /// but nothing inbetween them. /// </para> /// <para> /// This comparison will count how many possible floating point values are between /// the left and the right number. If the number of possible values between both /// numbers is less than or equal to maxUlps, then the numbers are considered as /// being equal. /// </para> /// <para> /// Implementation partially follows the code outlined here: /// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ /// </para> /// </remarks> public static bool AreAlmostEqualUlps(float left, float right, int maxUlps) { FloatIntUnion leftUnion = new FloatIntUnion(); FloatIntUnion rightUnion = new FloatIntUnion(); leftUnion.Float = left; rightUnion.Float = right; uint leftSignMask = (leftUnion.UInt >> 31); uint rightSignMask = (rightUnion.UInt >> 31); uint leftTemp = ((0x80000000 - leftUnion.UInt) & leftSignMask); leftUnion.UInt = leftTemp | (leftUnion.UInt & ~leftSignMask); uint rightTemp = ((0x80000000 - rightUnion.UInt) & rightSignMask); rightUnion.UInt = rightTemp | (rightUnion.UInt & ~rightSignMask); return (Math.Abs(leftUnion.Int - rightUnion.Int) <= maxUlps); } /// <summary>Compares two double precision floating point values for equality</summary> /// <param name="left">First double precision floating point value to be compared</param> /// <param name="right">Second double precision floating point value t be compared</param> /// <param name="maxUlps"> /// Maximum number of representable double precision floating point values that are /// allowed to be between the left and the right double precision floating point values /// </param> /// <returns>True if both numbers are equal or close to being equal</returns> /// <remarks> /// <para> /// Double precision floating point values can only represent a limited series of /// natural numbers. For example, the values 2.0000000000000000 and 2.0000000000000004 /// can be stored in a double, but nothing inbetween them. /// </para> /// <para> /// This comparison will count how many possible double precision floating point /// values are between the left and the right number. If the number of possible /// values between both numbers is less than or equal to maxUlps, then the numbers /// are considered as being equal. /// </para> /// <para> /// Implementation partially follows the code outlined here: /// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/ /// </para> /// </remarks> public static bool AreAlmostEqualUlps(double left, double right, long maxUlps) { DoubleLongUnion leftUnion = new DoubleLongUnion(); DoubleLongUnion rightUnion = new DoubleLongUnion(); leftUnion.Double = left; rightUnion.Double = right; ulong leftSignMask = (leftUnion.ULong >> 63); ulong rightSignMask = (rightUnion.ULong >> 63); ulong leftTemp = ((0x8000000000000000 - leftUnion.ULong) & leftSignMask); leftUnion.ULong = leftTemp | (leftUnion.ULong & ~leftSignMask); ulong rightTemp = ((0x8000000000000000 - rightUnion.ULong) & rightSignMask); rightUnion.ULong = rightTemp | (rightUnion.ULong & ~rightSignMask); return (Math.Abs(leftUnion.Long - rightUnion.Long) <= maxUlps); } /// <summary> /// Reinterprets the memory contents of a floating point value as an integer value /// </summary> /// <param name="value"> /// Floating point value whose memory contents to reinterpret /// </param> /// <returns> /// The memory contents of the floating point value interpreted as an integer /// </returns> public static int ReinterpretAsInt(float value) { FloatIntUnion union = new FloatIntUnion(); union.Float = value; return union.Int; } /// <summary> /// Reinterprets the memory contents of a double precision floating point /// value as an integer value /// </summary> /// <param name="value"> /// Double precision floating point value whose memory contents to reinterpret /// </param> /// <returns> /// The memory contents of the double precision floating point value /// interpreted as an integer /// </returns> public static long ReinterpretAsLong(double value) { DoubleLongUnion union = new DoubleLongUnion(); union.Double = value; return union.Long; } /// <summary> /// Reinterprets the memory contents of an integer as a floating point value /// </summary> /// <param name="value">Integer value whose memory contents to reinterpret</param> /// <returns> /// The memory contents of the integer value interpreted as a floating point value /// </returns> public static float ReinterpretAsFloat(int value) { FloatIntUnion union = new FloatIntUnion(); union.Int = value; return union.Float; } /// <summary> /// Reinterprets the memory contents of an integer value as a double precision /// floating point value /// </summary> /// <param name="value">Integer whose memory contents to reinterpret</param> /// <returns> /// The memory contents of the integer interpreted as a double precision /// floating point value /// </returns> public static double ReinterpretAsDouble(long value) { DoubleLongUnion union = new DoubleLongUnion(); union.Long = value; return union.Double; } private FloatingPointNumerics() { } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Threading; using Xunit; namespace System.Buffers.ArrayPool.Tests { public partial class ArrayPoolUnitTests { private const int MaxEventWaitTimeoutInMs = 200; private struct TestStruct { internal string InternalRef; } /* NOTE - due to test parallelism and sharing, use an instance pool for testing unless necessary */ [Fact] public static void SharedInstanceCreatesAnInstanceOnFirstCall() { Assert.NotNull(ArrayPool<byte>.Shared); } [Fact] public static void SharedInstanceOnlyCreatesOneInstanceOfOneTypep() { ArrayPool<byte> instance = ArrayPool<byte>.Shared; Assert.Same(instance, ArrayPool<byte>.Shared); } [Fact] public static void CreateWillCreateMultipleInstancesOfTheSameType() { Assert.NotSame(ArrayPool<byte>.Create(), ArrayPool<byte>.Create()); } [Theory] [InlineData(0)] [InlineData(-1)] public static void CreatingAPoolWithInvalidArrayCountThrows(int length) { Assert.Throws<ArgumentOutOfRangeException>("maxArraysPerBucket", () => ArrayPool<byte>.Create(maxArraysPerBucket: length, maxArrayLength: 16)); } [Theory] [InlineData(0)] [InlineData(-1)] public static void CreatingAPoolWithInvalidMaximumArraySizeThrows(int length) { Assert.Throws<ArgumentOutOfRangeException>("maxArrayLength", () => ArrayPool<byte>.Create(maxArrayLength: length, maxArraysPerBucket: 1)); } [Theory] [InlineData(1)] [InlineData(16)] [InlineData(0x40000000)] [InlineData(0x7FFFFFFF)] public static void CreatingAPoolWithValidMaximumArraySizeSucceeds(int length) { var pool = ArrayPool<byte>.Create(maxArrayLength: length, maxArraysPerBucket: 1); Assert.NotNull(pool); Assert.NotNull(pool.Rent(1)); } [Theory] [InlineData(-1)] public static void RentingWithInvalidLengthThrows(int length) { ArrayPool<byte> pool = ArrayPool<byte>.Create(); Assert.Throws<ArgumentOutOfRangeException>("minimumLength", () => pool.Rent(length)); } [Fact] public static void RentingGiganticArraySucceedsOrOOMs() { try { int len = 0x70000000; byte[] buffer = ArrayPool<byte>.Shared.Rent(len); Assert.NotNull(buffer); Assert.True(buffer.Length >= len); } catch (OutOfMemoryException) { } } [Fact] public static void Renting0LengthArrayReturnsSingleton() { byte[] zero0 = ArrayPool<byte>.Shared.Rent(0); byte[] zero1 = ArrayPool<byte>.Shared.Rent(0); byte[] zero2 = ArrayPool<byte>.Shared.Rent(0); byte[] one = ArrayPool<byte>.Shared.Rent(1); Assert.Same(zero0, zero1); Assert.Same(zero1, zero2); Assert.NotSame(zero2, one); ArrayPool<byte>.Shared.Return(zero0); ArrayPool<byte>.Shared.Return(zero1); ArrayPool<byte>.Shared.Return(zero2); ArrayPool<byte>.Shared.Return(one); Assert.Same(zero0, ArrayPool<byte>.Shared.Rent(0)); } [Fact] public static void RentingMultipleArraysGivesBackDifferentInstances() { ArrayPool<byte> instance = ArrayPool<byte>.Create(maxArraysPerBucket: 2, maxArrayLength: 16); Assert.NotSame(instance.Rent(100), instance.Rent(100)); } [Fact] public static void RentingMoreArraysThanSpecifiedInCreateWillStillSucceed() { ArrayPool<byte> instance = ArrayPool<byte>.Create(maxArraysPerBucket: 1, maxArrayLength: 16); Assert.NotNull(instance.Rent(100)); Assert.NotNull(instance.Rent(100)); } [Fact] public static void RentCanReturnBiggerArraySizeThanRequested() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArraysPerBucket: 1, maxArrayLength: 32); byte[] rented = pool.Rent(27); Assert.NotNull(rented); Assert.Equal(rented.Length, 32); } [Fact] public static void RentingAnArrayWithLengthGreaterThanSpecifiedInCreateStillSucceeds() { Assert.NotNull(ArrayPool<byte>.Create(maxArrayLength: 100, maxArraysPerBucket: 1).Rent(200)); } [Fact] public static void CallingReturnBufferWithNullBufferThrows() { ArrayPool<byte> pool = ArrayPool<byte>.Create(); Assert.Throws<ArgumentNullException>("array", () => pool.Return(null)); } private static void FillArray(byte[] buffer) { for (byte i = 0; i < buffer.Length; i++) buffer[i] = i; } private static void CheckFilledArray(byte[] buffer, Action<byte, byte> assert) { for (byte i = 0; i < buffer.Length; i++) { assert(buffer[i], i); } } [Fact] public static void CallingReturnWithoutClearingDoesNotClearTheBuffer() { ArrayPool<byte> pool = ArrayPool<byte>.Create(); byte[] buffer = pool.Rent(4); FillArray(buffer); pool.Return(buffer, clearArray: false); CheckFilledArray(buffer, (byte b1, byte b2) => Assert.Equal(b1, b2)); } [Fact] public static void CallingReturnWithClearingDoesClearTheBuffer() { ArrayPool<byte> pool = ArrayPool<byte>.Create(); byte[] buffer = pool.Rent(4); FillArray(buffer); // Note - yes this is bad to hold on to the old instance but we need to validate the contract pool.Return(buffer, clearArray: true); CheckFilledArray(buffer, (byte b1, byte b2) => Assert.Equal(b1, default(byte))); } [Fact] public static void CallingReturnOnReferenceTypeArrayDoesNotClearTheArray() { ArrayPool<string> pool = ArrayPool<string>.Create(); string[] array = pool.Rent(2); array[0] = "foo"; array[1] = "bar"; pool.Return(array, clearArray: false); Assert.NotNull(array[0]); Assert.NotNull(array[1]); } [Fact] public static void CallingReturnOnReferenceTypeArrayAndClearingSetsTypesToNull() { ArrayPool<string> pool = ArrayPool<string>.Create(); string[] array = pool.Rent(2); array[0] = "foo"; array[1] = "bar"; pool.Return(array, clearArray: true); Assert.Null(array[0]); Assert.Null(array[1]); } [Fact] public static void CallingReturnOnValueTypeWithInternalReferenceTypesAndClearingSetsValueTypeToDefault() { ArrayPool<TestStruct> pool = ArrayPool<TestStruct>.Create(); TestStruct[] array = pool.Rent(2); array[0].InternalRef = "foo"; array[1].InternalRef = "bar"; pool.Return(array, clearArray: true); Assert.Equal(array[0], default(TestStruct)); Assert.Equal(array[1], default(TestStruct)); } [Fact] public static void TakingAllBuffersFromABucketPlusAnAllocatedOneShouldAllowReturningAllBuffers() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); byte[] rented = pool.Rent(16); byte[] allocated = pool.Rent(16); pool.Return(rented); pool.Return(allocated); } [Fact] public static void NewDefaultArrayPoolWithSmallBufferSizeRoundsToOurSmallestSupportedSize() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 8, maxArraysPerBucket: 1); byte[] rented = pool.Rent(8); Assert.True(rented.Length == 16); } [Fact] public static void ReturningABufferGreaterThanMaxSizeDoesNotThrow() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); byte[] rented = pool.Rent(32); pool.Return(rented); } [Fact] public static void RentingAllBuffersAndCallingRentAgainWillAllocateBufferAndReturnIt() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); byte[] rented1 = pool.Rent(16); byte[] rented2 = pool.Rent(16); Assert.NotNull(rented1); Assert.NotNull(rented2); } [Fact] public static void RentingReturningThenRentingABufferShouldNotAllocate() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); byte[] bt = pool.Rent(16); int id = bt.GetHashCode(); pool.Return(bt); bt = pool.Rent(16); Assert.Equal(id, bt.GetHashCode()); } [Fact] public static void CanRentManySizedBuffers() { var pool = ArrayPool<byte>.Create(); for (int i = 1; i < 10000; i++) { byte[] buffer = pool.Rent(i); Assert.Equal(i <= 16 ? 16 : RoundUpToPowerOf2(i), buffer.Length); pool.Return(buffer); } } private static int RoundUpToPowerOf2(int i) { // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 --i; i |= i >> 1; i |= i >> 2; i |= i >> 4; i |= i >> 8; i |= i >> 16; return i + 1; } [Theory] [InlineData(1, 16)] [InlineData(15, 16)] [InlineData(16, 16)] [InlineData(1023, 1024)] [InlineData(1024, 1024)] [InlineData(4096, 4096)] [InlineData(1024 * 1024, 1024 * 1024)] [InlineData(1024 * 1024 + 1, 1024 * 1024 + 1)] [InlineData(1024 * 1024 * 2, 1024 * 1024 * 2)] public static void RentingSpecificLengthsYieldsExpectedLengths(int requestedMinimum, int expectedLength) { byte[] buffer = ArrayPool<byte>.Create().Rent(requestedMinimum); Assert.NotNull(buffer); Assert.Equal(expectedLength, buffer.Length); } [Fact] public static void RentingAfterPoolExhaustionReturnsSizeForCorrespondingBucket_SmallerThanLimit() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 64, maxArraysPerBucket: 2); Assert.Equal(16, pool.Rent(15).Length); // try initial bucket Assert.Equal(16, pool.Rent(15).Length); Assert.Equal(32, pool.Rent(15).Length); // try one more level Assert.Equal(32, pool.Rent(15).Length); Assert.Equal(16, pool.Rent(15).Length); // fall back to original size } [Fact] public static void RentingAfterPoolExhaustionReturnsSizeForCorrespondingBucket_JustBelowLimit() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 64, maxArraysPerBucket: 2); Assert.Equal(32, pool.Rent(31).Length); // try initial bucket Assert.Equal(32, pool.Rent(31).Length); Assert.Equal(64, pool.Rent(31).Length); // try one more level Assert.Equal(64, pool.Rent(31).Length); Assert.Equal(32, pool.Rent(31).Length); // fall back to original size } [Fact] public static void RentingAfterPoolExhaustionReturnsSizeForCorrespondingBucket_AtLimit() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 64, maxArraysPerBucket: 2); Assert.Equal(64, pool.Rent(63).Length); // try initial bucket Assert.Equal(64, pool.Rent(63).Length); Assert.Equal(64, pool.Rent(63).Length); // still get original size } private static int RunWithListener(Action body, EventLevel level, Action<EventWrittenEventArgs> callback) { using (TestEventListener listener = new TestEventListener("System.Buffers.ArrayPoolEventSource", level)) { int count = 0; listener.RunWithCallback(e => { Interlocked.Increment(ref count); callback(e); }, body); return count; } } [Fact] public static void RentBufferFiresRentedDiagnosticEvent() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); byte[] buffer = pool.Rent(16); pool.Return(buffer); Assert.Equal(1, RunWithListener(() => pool.Rent(16), EventLevel.Verbose, e => { Assert.Equal(1, e.EventId); Assert.Equal(buffer.GetHashCode(), e.Payload[0]); Assert.Equal(buffer.Length, e.Payload[1]); Assert.Equal(pool.GetHashCode(), e.Payload[2]); })); } [Fact] public static void ReturnBufferFiresDiagnosticEvent() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); byte[] buffer = pool.Rent(16); Assert.Equal(1, RunWithListener(() => pool.Return(buffer), EventLevel.Verbose, e => { Assert.Equal(3, e.EventId); Assert.Equal(buffer.GetHashCode(), e.Payload[0]); Assert.Equal(buffer.Length, e.Payload[1]); Assert.Equal(pool.GetHashCode(), e.Payload[2]); })); } [Fact] public static void RentingNonExistentBufferFiresAllocatedDiagnosticEvent() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); Assert.Equal(1, RunWithListener(() => pool.Rent(16), EventLevel.Informational, e => Assert.Equal(2, e.EventId))); } [Fact] public static void RentingBufferOverConfiguredMaximumSizeFiresDiagnosticEvent() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); Assert.Equal(1, RunWithListener(() => pool.Rent(64), EventLevel.Informational, e => Assert.Equal(2, e.EventId))); } [Fact] public static void RentingManyBuffersFiresExpectedDiagnosticEvents() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 10); var list = new List<EventWrittenEventArgs>(); Assert.Equal(60, RunWithListener(() => { for (int i = 0; i < 10; i++) pool.Return(pool.Rent(16)); // 10 rents + 10 allocations, 10 returns for (int i = 0; i < 10; i++) pool.Return(pool.Rent(0)); // 0 events for empty arrays for (int i = 0; i < 10; i++) pool.Rent(16); // 10 rents for (int i = 0; i < 10; i++) pool.Rent(16); // 10 rents + 10 allocations }, EventLevel.Verbose, list.Add)); Assert.Equal(30, list.Where(e => e.EventId == 1).Count()); // rents Assert.Equal(20, list.Where(e => e.EventId == 2).Count()); // allocations Assert.Equal(10, list.Where(e => e.EventId == 3).Count()); // returns } [Fact] public static void ReturningANonPooledBufferOfDifferentSizeToThePoolThrows() { ArrayPool<byte> pool = ArrayPool<byte>.Create(maxArrayLength: 16, maxArraysPerBucket: 1); byte[] buffer = pool.Rent(15); Assert.Throws<ArgumentException>("array", () => pool.Return(new byte[1])); buffer = pool.Rent(15); Assert.Equal(buffer.Length, 16); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedLicenseCodesClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); GetLicenseCodeRequest request = new GetLicenseCodeRequest { LicenseCode = "license_code196a50c0", Project = "projectaa6ff846", }; LicenseCode expectedResponse = new LicenseCode { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", LicenseAlias = { new LicenseCodeLicenseAlias(), }, State = "state2e9ed39e", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); LicenseCode response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); GetLicenseCodeRequest request = new GetLicenseCodeRequest { LicenseCode = "license_code196a50c0", Project = "projectaa6ff846", }; LicenseCode expectedResponse = new LicenseCode { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", LicenseAlias = { new LicenseCodeLicenseAlias(), }, State = "state2e9ed39e", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LicenseCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); LicenseCode responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LicenseCode responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); GetLicenseCodeRequest request = new GetLicenseCodeRequest { LicenseCode = "license_code196a50c0", Project = "projectaa6ff846", }; LicenseCode expectedResponse = new LicenseCode { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", LicenseAlias = { new LicenseCodeLicenseAlias(), }, State = "state2e9ed39e", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); LicenseCode response = client.Get(request.Project, request.LicenseCode); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); GetLicenseCodeRequest request = new GetLicenseCodeRequest { LicenseCode = "license_code196a50c0", Project = "projectaa6ff846", }; LicenseCode expectedResponse = new LicenseCode { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", LicenseAlias = { new LicenseCodeLicenseAlias(), }, State = "state2e9ed39e", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LicenseCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); LicenseCode responseCallSettings = await client.GetAsync(request.Project, request.LicenseCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LicenseCode responseCancellationToken = await client.GetAsync(request.Project, request.LicenseCode, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict); TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using NUnit.Framework.Interfaces; using NUnit.TestData.ParallelExecutionData; using NUnit.TestUtilities; namespace NUnit.Framework.Internal.Execution { [TestFixtureSource(nameof(GetParallelSuites))] [NonParallelizable] public class ParallelExecutionTests : ITestListener { private readonly TestSuite _testSuite; private readonly Expectations _expectations; private ConcurrentQueue<TestEvent> _events; private TestResult _result; private IEnumerable<TestEvent> AllEvents { get { return _events.AsEnumerable(); } } private IEnumerable<TestEvent> ShiftEvents { get { return AllEvents.Where(e => e.Action == TestAction.ShiftStarted || e.Action == TestAction.ShiftFinished); } } private IEnumerable<TestEvent> TestEvents { get { return AllEvents.Where(e => e.Action == TestAction.TestStarting || e.Action == TestAction.TestFinished); } } public ParallelExecutionTests(TestSuite testSuite) { _testSuite = testSuite; } public ParallelExecutionTests(TestSuite testSuite, Expectations expectations) { _testSuite = testSuite; _expectations = expectations; } [OneTimeSetUp] public void RunTestSuite() { _events = new ConcurrentQueue<TestEvent>(); var dispatcher = new ParallelWorkItemDispatcher(4); var context = new TestExecutionContext(); context.Dispatcher = dispatcher; context.Listener = this; dispatcher.ShiftStarting += (shift) => { _events.Enqueue(new TestEvent() { Action = TestAction.ShiftStarted, ShiftName = shift.Name }); }; dispatcher.ShiftFinished += (shift) => { _events.Enqueue(new TestEvent() { Action = TestAction.ShiftFinished, ShiftName = shift.Name }); }; var workItem = TestBuilder.CreateWorkItem(_testSuite, context); dispatcher.Start(workItem); workItem.WaitForCompletion(); _result = workItem.Result; } [Test] public void AllTestsPassed() { if (_result.ResultState != ResultState.Success || _result.PassCount != _testSuite.TestCaseCount) Assert.Fail(DumpEvents("Not all tests passed")); } [Test] public void OnlyOneShiftIsActiveAtSameTime() { int count = 0; foreach (var e in _events) { if (e.Action == TestAction.ShiftStarted && ++count > 1) Assert.Fail(DumpEvents("Shift started while another shift was active")); if (e.Action == TestAction.ShiftFinished) --count; } } [Test] public void CorrectInitialShift() { string expected = "NonParallel"; if (_testSuite.Properties.ContainsKey(PropertyNames.ParallelScope)) { var scope = (ParallelScope)_testSuite.Properties.Get(PropertyNames.ParallelScope); if ((scope & ParallelScope.Self) != 0) expected = "Parallel"; } var e = _events.First(); Assert.That(e.Action, Is.EqualTo(TestAction.ShiftStarted)); Assert.That(e.ShiftName, Is.EqualTo(expected)); } [Test] public void TestsRunOnExpectedWorkers() { Assert.Multiple(() => { foreach (var e in TestEvents) _expectations.Verify(e); }); } #region Test Data static IEnumerable<TestFixtureData> GetParallelSuites() { yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1))))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("NUnit").RunsOn("NonParallelWorker"), That("Tests").RunsOn("NonParallelWorker"), That("TestFixture1").RunsOn("NonParallelWorker"), That("TestFixture1_Test").RunsOn("NonParallelWorker"))) .SetName("SingleFixture_Default"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1)).NonParallelizable()))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("NUnit").RunsOn("NonParallelWorker"), That("Tests").RunsOn("NonParallelWorker"), That("TestFixture1").RunsOn("NonParallelWorker"), That("TestFixture1_Test").RunsOn("NonParallelWorker"))) .SetName("SingleFixture_NonParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1)).Parallelizable()))), Expecting( That("fake-assembly.dll").StartsOn("NonParallelWorker").FinishesOn("ParallelWorker"), That("NUnit").StartsOn("NonParallelWorker").FinishesOn("ParallelWorker"), That("Tests").StartsOn("NonParallelWorker").FinishesOn("ParallelWorker"), That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"))) .SetName("SingleFixture_Parallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll").NonParallelizable() .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1))))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("NUnit").RunsOn("NonParallelWorker"), That("Tests").RunsOn("NonParallelWorker"), That("TestFixture1").RunsOn("NonParallelWorker"), That("TestFixture1_Test").RunsOn("NonParallelWorker"))) .SetName("SingleFixture_AssemblyNonParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll").Parallelizable() .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1))))), Expecting( That("fake-assembly.dll").StartsOn("ParallelWorker").FinishesOn("NonParallelWorker"), That("NUnit").StartsOn("ParallelWorker").FinishesOn("NonParallelWorker"), That("Tests").StartsOn("ParallelWorker").FinishesOn("NonParallelWorker"), That("TestFixture1").RunsOn("NonParallelWorker"), That("TestFixture1_Test").RunsOn("NonParallelWorker"))) .SetName("SingleFixture_AssemblyParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll").Parallelizable() .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1)).Parallelizable()))), Expecting( That("fake-assembly.dll").RunsOn("ParallelWorker"), That("NUnit").RunsOn("ParallelWorker"), That("Tests").RunsOn("ParallelWorker"), That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"))) .SetName("SingleFixture_AssemblyAndFixtureParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixtureWithParallelParameterizedTest))))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("NUnit").RunsOn("NonParallelWorker"), That("Tests").RunsOn("NonParallelWorker"), That("TestFixtureWithParallelParameterizedTest").RunsOn("NonParallelWorker"), That("ParameterizedTest").StartsOn("NonParallelWorker").FinishesOn("ParallelWorker"), That("ParameterizedTest(1)").RunsOn("ParallelWorker"), That("ParameterizedTest(2)").RunsOn("ParallelWorker"), That("ParameterizedTest(3)").RunsOn("ParallelWorker"))) .SetName("SingleFixture_ParameterizedTest"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing( Fixture(typeof(TestFixture1)), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)))))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("NUnit").RunsOn("NonParallelWorker"), That("TestData").RunsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("NonParallelWorker"), // SetUpFixture1 That("TestFixture1").RunsOn("NonParallelWorker"), That("TestFixture1_Test").RunsOn("NonParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"), That("TestFixture3").RunsOn("NonParallelWorker"), That("TestFixture3_Test").RunsOn("NonParallelWorker"))) .SetName("ThreeFixtures_SetUpFixture_Default"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable())))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("NUnit").RunsOn("NonParallelWorker"), That("TestData").RunsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("NonParallelWorker"), // SetUpFixture1 That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"), That("TestFixture3").RunsOn("ParallelWorker"), That("TestFixture3_Test").RunsOn("ParallelWorker"))) .SetName("ThreeFixtures_TwoParallelizable_SetUpFixture"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)).Parallelizable() .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable())))), Expecting( That("fake-assembly.dll").StartsOn("NonParallelWorker"), That("NUnit").StartsOn("NonParallelWorker"), That("TestData").StartsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("ParallelWorker"), // SetUpFixture1 That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"), That("TestFixture3").RunsOn("ParallelWorker"), That("TestFixture3_Test").RunsOn("ParallelWorker"))) .SetName("ThreeFixtures_TwoParallelizable_ParallelizableSetUpFixture"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)).Parallelizable() .Containing(Fixture(typeof(SetUpFixture2)).Parallelizable() .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").StartsOn("NonParallelWorker"), That("NUnit").StartsOn("NonParallelWorker"), That("TestData").StartsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("ParallelWorker"), // SetUpFixture1 && SetUpFixture2 That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"), That("TestFixture3").RunsOn("ParallelWorker"), That("TestFixture3_Test").RunsOn("ParallelWorker"))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_BothParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing(Fixture(typeof(SetUpFixture2)) .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("NUnit").RunsOn("NonParallelWorker"), That("TestData").RunsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("*"), // SetUpFixture1 && SetUpFixture2 That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"), That("TestFixture3").RunsOn("ParallelWorker"), That("TestFixture3_Test").RunsOn("ParallelWorker"))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_NeitherParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)).Parallelizable() .Containing(Fixture(typeof(SetUpFixture2)) .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").StartsOn("NonParallelWorker"), That("NUnit").StartsOn("NonParallelWorker"), That("TestData").StartsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("*"), // SetUpFixture1 && SetUpFixture2 (we can't distinguish the two) That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"), That("TestFixture3").RunsOn("ParallelWorker"), That("TestFixture3_Test").RunsOn("ParallelWorker"))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_FirstOneParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing(Fixture(typeof(SetUpFixture2)).Parallelizable() .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").StartsOn("NonParallelWorker"), That("NUnit").StartsOn("NonParallelWorker"), That("TestData").StartsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("*"), // SetUpFixture1 && SetUpFixture2 (we can't distinguish the two) That("TestFixture1").RunsOn("ParallelWorker"), That("TestFixture1_Test").RunsOn("ParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"), That("TestFixture3").RunsOn("ParallelWorker"), That("TestFixture3_Test").RunsOn("ParallelWorker"))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_SecondOneParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("SomeNamespace") .Containing(Fixture(typeof(SetUpFixture1))) .Containing(Fixture(typeof(TestFixture1)))) .Containing(Suite("OtherNamespace") .Containing(Fixture(typeof(TestFixture2)))), Expecting( That("fake-assembly.dll").RunsOn("NonParallelWorker"), That("SomeNamespace").RunsOn("NonParallelWorker"), That("ParallelExecutionData").RunsOn("NonParallelWorker"), // SetUpFixture1 That("TestFixture1").RunsOn("NonParallelWorker"), That("TestFixture1_Test").RunsOn("NonParallelWorker"), That("OtherNamespace").RunsOn("NonParallelWorker"), That("TestFixture2").RunsOn("NonParallelWorker"), That("TestFixture2_Test").RunsOn("NonParallelWorker"))) .SetName("Issue-2464"); if (new PlatformHelper().IsPlatformSupported(new PlatformAttribute { Include = "Win, Mono" })) { yield return new TestFixtureData( Suite("fake-assembly.dll").Parallelizable() .Containing(Fixture(typeof(STAFixture)).Parallelizable()), Expecting( That("fake-assembly.dll").StartsOn("ParallelWorker"), That("STAFixture").RunsOn("ParallelSTAWorker"), That("STAFixture_Test").RunsOn("ParallelSTAWorker"))) .SetName("Issue-2467"); } } #endregion #region ITestListener implementation public void TestStarted(ITest test) { _events.Enqueue(new TestEvent() { Action = TestAction.TestStarting, TestName = test.Name, ThreadName = Thread.CurrentThread.Name }); } public void TestFinished(ITestResult result) { _events.Enqueue(new TestEvent() { Action = TestAction.TestFinished, TestName = result.Name, Result = result.ResultState.ToString(), ThreadName = Thread.CurrentThread.Name }); } public void TestOutput(TestOutput output) { } public void SendMessage(TestMessage message) { } #endregion #region Helper Methods private static TestSuite Suite(string name) { return TestBuilder.MakeSuite(name); } private static TestSuite Fixture(Type type) { return TestBuilder.MakeFixture(type); } private static Expectations Expecting(params Expectation[] expectations) { return new Expectations(expectations); } private static Expectation That(string testName) { return new Expectation(testName); } private string DumpEvents(string message) { var sb = new StringBuilder().AppendLine(message); foreach (var e in _events) sb.AppendLine(e.ToString()); return sb.ToString(); } #endregion #region Nested Types public enum TestAction { ShiftStarted, ShiftFinished, TestStarting, TestFinished } public class TestEvent { public TestAction Action; public string TestName; public string ThreadName; public string ShiftName; public string Result; public override string ToString() { switch (Action) { case TestAction.ShiftStarted: return $"{Action} {ShiftName}"; default: case TestAction.TestStarting: return $"{Action} {TestName} [{ThreadName}]"; case TestAction.TestFinished: return $"{Action} {TestName} {Result} [{ThreadName}]"; } } } public class Expectation { public string TestName { get; } public string StartWorker { get; private set; } public string FinishWorker { get; private set; } public Expectation(string testName) { TestName = testName; StartWorker = FinishWorker = "*"; } // THe RunsOn method specifies that the work item will // run entirely on a particular worker. In the case of // a composite work item, this doesn't include its // children, which may run on a different thread. public Expectation RunsOn(string worker) { StartWorker = FinishWorker = worker; return this; } // Sometimes, the thread used to complete a composite work item // is unimportant because there is no actual user code to run. // In that case, we can just specify which worker is used to // initially run the item using StartsOn public Expectation StartsOn(string worker) { StartWorker = worker; return this; } // FinishesOn may be used if we know that the work item // starts and finishes on different threads and we want // to specify both of them. In most cases, this amounts // to over-specification since we usually don't care. public Expectation FinishesOn(string worker) { FinishWorker = worker; return this; } // Verify that a particular TestEvent meets all expectations public void Verify(TestEvent e) { var worker = e.Action == TestAction.TestStarting ? StartWorker : FinishWorker; if (worker != "*") Assert.That(e.ThreadName, Does.StartWith(worker), $"{e.Action} {e.TestName} running on wrong type of worker thread."); } } public class Expectations { private readonly Dictionary<string, Expectation> _expectations = new Dictionary<string, Expectation>(); public Expectations(params Expectation[] expectations) { foreach (var expectation in expectations) _expectations.Add(expectation.TestName, expectation); } public void Verify(TestEvent e) { Assert.That(_expectations, Does.ContainKey(e.TestName), $"The test {e.TestName} is not in the dictionary."); _expectations[e.TestName].Verify(e); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal { internal class HttpConnection : ITimeoutHandler { // Use C#7.3's ReadOnlySpan<byte> optimization for static data https://vcsjones.com/2019/02/01/csharp-readonly-span-bytes-static/ private static ReadOnlySpan<byte> Http2Id => new[] { (byte)'h', (byte)'2' }; private readonly BaseHttpConnectionContext _context; private readonly ISystemClock _systemClock; private readonly TimeoutControl _timeoutControl; private readonly object _protocolSelectionLock = new object(); private ProtocolSelectionState _protocolSelectionState = ProtocolSelectionState.Initializing; private Http1Connection? _http1Connection; // Internal for testing internal IRequestProcessor? _requestProcessor; public HttpConnection(BaseHttpConnectionContext context) { _context = context; _systemClock = _context.ServiceContext.SystemClock; _timeoutControl = new TimeoutControl(this); // Tests override the timeout control sometimes _context.TimeoutControl ??= _timeoutControl; } private KestrelTrace Log => _context.ServiceContext.Log; public async Task ProcessRequestsAsync<TContext>(IHttpApplication<TContext> httpApplication) where TContext : notnull { try { // Ensure TimeoutControl._lastTimestamp is initialized before anything that could set timeouts runs. _timeoutControl.Initialize(_systemClock.UtcNowTicks); IRequestProcessor? requestProcessor = null; switch (SelectProtocol()) { case HttpProtocols.Http1: // _http1Connection must be initialized before adding the connection to the connection manager requestProcessor = _http1Connection = new Http1Connection<TContext>((HttpConnectionContext)_context); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.Http2: // _http2Connection must be initialized before yielding control to the transport thread, // to prevent a race condition where _http2Connection.Abort() is called just as // _http2Connection is about to be initialized. requestProcessor = new Http2Connection((HttpConnectionContext)_context); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.Http3: requestProcessor = new Http3Connection((HttpMultiplexedConnectionContext)_context); _protocolSelectionState = ProtocolSelectionState.Selected; break; case HttpProtocols.None: // An error was already logged in SelectProtocol(), but we should close the connection. break; default: // SelectProtocol() only returns Http1, Http2, Http3 or None. throw new NotSupportedException($"{nameof(SelectProtocol)} returned something other than Http1, Http2 or None."); } _requestProcessor = requestProcessor; if (requestProcessor != null) { var connectionHeartbeatFeature = _context.ConnectionFeatures.Get<IConnectionHeartbeatFeature>(); var connectionLifetimeNotificationFeature = _context.ConnectionFeatures.Get<IConnectionLifetimeNotificationFeature>(); // These features should never be null in Kestrel itself, if this middleware is ever refactored to run outside of kestrel, // we'll need to handle these missing. Debug.Assert(connectionHeartbeatFeature != null, nameof(IConnectionHeartbeatFeature) + " is missing!"); Debug.Assert(connectionLifetimeNotificationFeature != null, nameof(IConnectionLifetimeNotificationFeature) + " is missing!"); // Register the various callbacks once we're going to start processing requests // The heart beat for various timeouts connectionHeartbeatFeature?.OnHeartbeat(state => ((HttpConnection)state).Tick(), this); // Register for graceful shutdown of the server using var shutdownRegistration = connectionLifetimeNotificationFeature?.ConnectionClosedRequested.Register(state => ((HttpConnection)state!).StopProcessingNextRequest(), this); // Register for connection close using var closedRegistration = _context.ConnectionContext.ConnectionClosed.Register(state => ((HttpConnection)state!).OnConnectionClosed(), this); await requestProcessor.ProcessRequestsAsync(httpApplication); } } catch (Exception ex) { Log.LogCritical(0, ex, $"Unexpected exception in {nameof(HttpConnection)}.{nameof(ProcessRequestsAsync)}."); } } // For testing only internal void Initialize(IRequestProcessor requestProcessor) { _requestProcessor = requestProcessor; _http1Connection = requestProcessor as Http1Connection; _protocolSelectionState = ProtocolSelectionState.Selected; } private void StopProcessingNextRequest() { ProtocolSelectionState previousState; lock (_protocolSelectionLock) { previousState = _protocolSelectionState; Debug.Assert(previousState != ProtocolSelectionState.Initializing, "The state should never be initializing"); switch (_protocolSelectionState) { case ProtocolSelectionState.Selected: case ProtocolSelectionState.Aborted: break; } } switch (previousState) { case ProtocolSelectionState.Selected: _requestProcessor!.StopProcessingNextRequest(); break; case ProtocolSelectionState.Aborted: break; } } private void OnConnectionClosed() { ProtocolSelectionState previousState; lock (_protocolSelectionLock) { previousState = _protocolSelectionState; Debug.Assert(previousState != ProtocolSelectionState.Initializing, "The state should never be initializing"); switch (_protocolSelectionState) { case ProtocolSelectionState.Selected: case ProtocolSelectionState.Aborted: break; } } switch (previousState) { case ProtocolSelectionState.Selected: _requestProcessor!.OnInputOrOutputCompleted(); break; case ProtocolSelectionState.Aborted: break; } } private void Abort(ConnectionAbortedException ex) { ProtocolSelectionState previousState; lock (_protocolSelectionLock) { previousState = _protocolSelectionState; Debug.Assert(previousState != ProtocolSelectionState.Initializing, "The state should never be initializing"); _protocolSelectionState = ProtocolSelectionState.Aborted; } switch (previousState) { case ProtocolSelectionState.Selected: _requestProcessor!.Abort(ex); break; case ProtocolSelectionState.Aborted: break; } } private HttpProtocols SelectProtocol() { var hasTls = _context.ConnectionFeatures.Get<ITlsConnectionFeature>() != null; var applicationProtocol = _context.ConnectionFeatures.Get<ITlsApplicationProtocolFeature>()?.ApplicationProtocol ?? new ReadOnlyMemory<byte>(); var isMultiplexTransport = _context is HttpMultiplexedConnectionContext; var http1Enabled = _context.Protocols.HasFlag(HttpProtocols.Http1); var http2Enabled = _context.Protocols.HasFlag(HttpProtocols.Http2); var http3Enabled = _context.Protocols.HasFlag(HttpProtocols.Http3); string? error = null; if (_context.Protocols == HttpProtocols.None) { error = CoreStrings.EndPointRequiresAtLeastOneProtocol; } if (isMultiplexTransport) { if (http3Enabled) { return HttpProtocols.Http3; } error = $"Protocols {_context.Protocols} not supported on multiplexed transport."; } if (!http1Enabled && http2Enabled && hasTls && !Http2Id.SequenceEqual(applicationProtocol.Span)) { error = CoreStrings.EndPointHttp2NotNegotiated; } if (error != null) { Log.LogError(0, error); return HttpProtocols.None; } if (!hasTls && http1Enabled) { // Even if Http2 was enabled, default to Http1 because it's ambiguous without ALPN. return HttpProtocols.Http1; } return http2Enabled && (!hasTls || Http2Id.SequenceEqual(applicationProtocol.Span)) ? HttpProtocols.Http2 : HttpProtocols.Http1; } private void Tick() { if (_protocolSelectionState == ProtocolSelectionState.Aborted) { // It's safe to check for timeouts on a dead connection, // but try not to in order to avoid extraneous logs. return; } // It's safe to use UtcNowUnsynchronized since Tick is called by the Heartbeat. var now = _systemClock.UtcNowUnsynchronized; _timeoutControl.Tick(now); _requestProcessor!.Tick(now); } public void OnTimeout(TimeoutReason reason) { // In the cases that don't log directly here, we expect the setter of the timeout to also be the input // reader, so when the read is canceled or aborted, the reader should write the appropriate log. switch (reason) { case TimeoutReason.KeepAlive: _requestProcessor!.StopProcessingNextRequest(); break; case TimeoutReason.RequestHeaders: _requestProcessor!.HandleRequestHeadersTimeout(); break; case TimeoutReason.ReadDataRate: _requestProcessor!.HandleReadDataRateTimeout(); break; case TimeoutReason.WriteDataRate: Log.ResponseMinimumDataRateNotSatisfied(_context.ConnectionId, _http1Connection?.TraceIdentifier); Abort(new ConnectionAbortedException(CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)); break; case TimeoutReason.RequestBodyDrain: case TimeoutReason.TimeoutFeature: Abort(new ConnectionAbortedException(CoreStrings.ConnectionTimedOutByServer)); break; default: Debug.Assert(false, "Invalid TimeoutReason"); break; } } private enum ProtocolSelectionState { Initializing, Selected, Aborted } } }
using System; using static OneOf.Functions; namespace OneOf { public struct OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> : IOneOf { readonly T0 _value0; readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; readonly T4 _value4; readonly T5 _value5; readonly T6 _value6; readonly T7 _value7; readonly T8 _value8; readonly T9 _value9; readonly T10 _value10; readonly T11 _value11; readonly T12 _value12; readonly T13 _value13; readonly int _index; OneOf(int index, T0 value0 = default, T1 value1 = default, T2 value2 = default, T3 value3 = default, T4 value4 = default, T5 value5 = default, T6 value6 = default, T7 value7 = default, T8 value8 = default, T9 value9 = default, T10 value10 = default, T11 value11 = default, T12 value12 = default, T13 value13 = default) { _index = index; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; _value5 = value5; _value6 = value6; _value7 = value7; _value8 = value8; _value9 = value9; _value10 = value10; _value11 = value11; _value12 = value12; _value13 = value13; } public object Value => _index switch { 0 => _value0, 1 => _value1, 2 => _value2, 3 => _value3, 4 => _value4, 5 => _value5, 6 => _value6, 7 => _value7, 8 => _value8, 9 => _value9, 10 => _value10, 11 => _value11, 12 => _value12, 13 => _value13, _ => throw new InvalidOperationException() }; public int Index => _index; public bool IsT0 => _index == 0; public bool IsT1 => _index == 1; public bool IsT2 => _index == 2; public bool IsT3 => _index == 3; public bool IsT4 => _index == 4; public bool IsT5 => _index == 5; public bool IsT6 => _index == 6; public bool IsT7 => _index == 7; public bool IsT8 => _index == 8; public bool IsT9 => _index == 9; public bool IsT10 => _index == 10; public bool IsT11 => _index == 11; public bool IsT12 => _index == 12; public bool IsT13 => _index == 13; public T0 AsT0 => _index == 0 ? _value0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}"); public T1 AsT1 => _index == 1 ? _value1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}"); public T2 AsT2 => _index == 2 ? _value2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}"); public T3 AsT3 => _index == 3 ? _value3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}"); public T4 AsT4 => _index == 4 ? _value4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}"); public T5 AsT5 => _index == 5 ? _value5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}"); public T6 AsT6 => _index == 6 ? _value6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}"); public T7 AsT7 => _index == 7 ? _value7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}"); public T8 AsT8 => _index == 8 ? _value8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}"); public T9 AsT9 => _index == 9 ? _value9 : throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}"); public T10 AsT10 => _index == 10 ? _value10 : throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}"); public T11 AsT11 => _index == 11 ? _value11 : throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}"); public T12 AsT12 => _index == 12 ? _value12 : throw new InvalidOperationException($"Cannot return as T12 as result is T{_index}"); public T13 AsT13 => _index == 13 ? _value13 : throw new InvalidOperationException($"Cannot return as T13 as result is T{_index}"); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T0 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(0, value0: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T1 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(1, value1: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T2 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(2, value2: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T3 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(3, value3: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T4 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(4, value4: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T5 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(5, value5: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T6 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(6, value6: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T7 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(7, value7: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T8 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(8, value8: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T9 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(9, value9: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T10 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(10, value10: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T11 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(11, value11: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T12 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(12, value12: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T13 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(13, value13: t); public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12, Action<T13> f13) { if (_index == 0 && f0 != null) { f0(_value0); return; } if (_index == 1 && f1 != null) { f1(_value1); return; } if (_index == 2 && f2 != null) { f2(_value2); return; } if (_index == 3 && f3 != null) { f3(_value3); return; } if (_index == 4 && f4 != null) { f4(_value4); return; } if (_index == 5 && f5 != null) { f5(_value5); return; } if (_index == 6 && f6 != null) { f6(_value6); return; } if (_index == 7 && f7 != null) { f7(_value7); return; } if (_index == 8 && f8 != null) { f8(_value8); return; } if (_index == 9 && f9 != null) { f9(_value9); return; } if (_index == 10 && f10 != null) { f10(_value10); return; } if (_index == 11 && f11 != null) { f11(_value11); return; } if (_index == 12 && f12 != null) { f12(_value12); return; } if (_index == 13 && f13 != null) { f13(_value13); return; } throw new InvalidOperationException(); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12, Func<T13, TResult> f13) { if (_index == 0 && f0 != null) { return f0(_value0); } if (_index == 1 && f1 != null) { return f1(_value1); } if (_index == 2 && f2 != null) { return f2(_value2); } if (_index == 3 && f3 != null) { return f3(_value3); } if (_index == 4 && f4 != null) { return f4(_value4); } if (_index == 5 && f5 != null) { return f5(_value5); } if (_index == 6 && f6 != null) { return f6(_value6); } if (_index == 7 && f7 != null) { return f7(_value7); } if (_index == 8 && f8 != null) { return f8(_value8); } if (_index == 9 && f9 != null) { return f9(_value9); } if (_index == 10 && f10 != null) { return f10(_value10); } if (_index == 11 && f11 != null) { return f11(_value11); } if (_index == 12 && f12 != null) { return f12(_value12); } if (_index == 13 && f13 != null) { return f13(_value13); } throw new InvalidOperationException(); } public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT0(T0 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT1(T1 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT2(T2 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT3(T3 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT4(T4 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT5(T5 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT6(T6 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT7(T7 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT8(T8 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT9(T9 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT10(T10 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT11(T11 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT12(T12 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> FromT13(T13 input) => input; public OneOf<TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> MapT0<TResult>(Func<T0, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => mapFunc(AsT0), 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, TResult, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> MapT1<TResult>(Func<T1, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => mapFunc(AsT1), 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, TResult, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> MapT2<TResult>(Func<T2, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => mapFunc(AsT2), 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, TResult, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> MapT3<TResult>(Func<T3, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => mapFunc(AsT3), 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, TResult, T5, T6, T7, T8, T9, T10, T11, T12, T13> MapT4<TResult>(Func<T4, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => mapFunc(AsT4), 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, TResult, T6, T7, T8, T9, T10, T11, T12, T13> MapT5<TResult>(Func<T5, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => mapFunc(AsT5), 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, TResult, T7, T8, T9, T10, T11, T12, T13> MapT6<TResult>(Func<T6, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => mapFunc(AsT6), 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, TResult, T8, T9, T10, T11, T12, T13> MapT7<TResult>(Func<T7, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => mapFunc(AsT7), 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, TResult, T9, T10, T11, T12, T13> MapT8<TResult>(Func<T8, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => mapFunc(AsT8), 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult, T10, T11, T12, T13> MapT9<TResult>(Func<T9, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => mapFunc(AsT9), 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult, T11, T12, T13> MapT10<TResult>(Func<T10, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => mapFunc(AsT10), 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult, T12, T13> MapT11<TResult>(Func<T11, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => mapFunc(AsT11), 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult, T13> MapT12<TResult>(Func<T12, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => mapFunc(AsT12), 13 => AsT13, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> MapT13<TResult>(Func<T13, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => mapFunc(AsT13), _ => throw new InvalidOperationException() }; } public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT0 ? AsT0 : default; remainder = _index switch { 0 => default, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT0; } public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT1 ? AsT1 : default; remainder = _index switch { 0 => AsT0, 1 => default, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT1; } public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT2 ? AsT2 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => default, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT2; } public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT3 ? AsT3 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => default, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT3; } public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT4 ? AsT4 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => default, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT4; } public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT5 ? AsT5 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => default, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT5; } public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT6 ? AsT6 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => default, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT6; } public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12, T13> remainder) { value = IsT7 ? AsT7 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => default, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT7; } public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12, T13> remainder) { value = IsT8 ? AsT8 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => default, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT8; } public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12, T13> remainder) { value = IsT9 ? AsT9 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => default, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT9; } public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12, T13> remainder) { value = IsT10 ? AsT10 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => default, 11 => AsT11, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT10; } public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12, T13> remainder) { value = IsT11 ? AsT11 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => default, 12 => AsT12, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT11; } public bool TryPickT12(out T12 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T13> remainder) { value = IsT12 ? AsT12 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => default, 13 => AsT13, _ => throw new InvalidOperationException() }; return this.IsT12; } public bool TryPickT13(out T13 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> remainder) { value = IsT13 ? AsT13 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => default, _ => throw new InvalidOperationException() }; return this.IsT13; } bool Equals(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> other) => _index == other._index && _index switch { 0 => Equals(_value0, other._value0), 1 => Equals(_value1, other._value1), 2 => Equals(_value2, other._value2), 3 => Equals(_value3, other._value3), 4 => Equals(_value4, other._value4), 5 => Equals(_value5, other._value5), 6 => Equals(_value6, other._value6), 7 => Equals(_value7, other._value7), 8 => Equals(_value8, other._value8), 9 => Equals(_value9, other._value9), 10 => Equals(_value10, other._value10), 11 => Equals(_value11, other._value11), 12 => Equals(_value12, other._value12), 13 => Equals(_value13, other._value13), _ => false }; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> o && Equals(o); } public override string ToString() => _index switch { 0 => FormatValue(_value0), 1 => FormatValue(_value1), 2 => FormatValue(_value2), 3 => FormatValue(_value3), 4 => FormatValue(_value4), 5 => FormatValue(_value5), 6 => FormatValue(_value6), 7 => FormatValue(_value7), 8 => FormatValue(_value8), 9 => FormatValue(_value9), 10 => FormatValue(_value10), 11 => FormatValue(_value11), 12 => FormatValue(_value12), 13 => FormatValue(_value13), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.") }; public override int GetHashCode() { unchecked { int hashCode = _index switch { 0 => _value0?.GetHashCode(), 1 => _value1?.GetHashCode(), 2 => _value2?.GetHashCode(), 3 => _value3?.GetHashCode(), 4 => _value4?.GetHashCode(), 5 => _value5?.GetHashCode(), 6 => _value6?.GetHashCode(), 7 => _value7?.GetHashCode(), 8 => _value8?.GetHashCode(), 9 => _value9?.GetHashCode(), 10 => _value10?.GetHashCode(), 11 => _value11?.GetHashCode(), 12 => _value12?.GetHashCode(), 13 => _value13?.GetHashCode(), _ => 0 } ?? 0; return (hashCode*397) ^ _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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; #if SRM using System.Reflection.PortableExecutable; #else using Roslyn.Reflection.PortableExecutable; #endif #if SRM namespace System.Reflection.Metadata.Ecma335 #else namespace Roslyn.Reflection.Metadata.Ecma335 #endif { #if SRM public #endif sealed class StandaloneDebugMetadataSerializer : MetadataSerializer { private const string DebugMetadataVersionString = "PDB v1.0"; private Blob _pdbIdBlob; private readonly MethodDefinitionHandle _entryPoint; public StandaloneDebugMetadataSerializer( MetadataBuilder builder, ImmutableArray<int> typeSystemRowCounts, MethodDefinitionHandle entryPoint, bool isMinimalDelta) : base(builder, CreateSizes(builder, typeSystemRowCounts, isMinimalDelta, isStandaloneDebugMetadata: true), DebugMetadataVersionString) { _entryPoint = entryPoint; } /// <summary> /// Serialized #Pdb stream. /// </summary> protected override void SerializeStandalonePdbStream(BlobBuilder builder) { int startPosition = builder.Position; // the id will be filled in later _pdbIdBlob = builder.ReserveBytes(MetadataSizes.PdbIdSize); builder.WriteInt32(_entryPoint.IsNil ? 0 : MetadataTokens.GetToken(_entryPoint)); builder.WriteUInt64(MetadataSizes.ExternalTablesMask); MetadataWriterUtilities.SerializeRowCounts(builder, MetadataSizes.ExternalRowCounts); int endPosition = builder.Position; Debug.Assert(MetadataSizes.CalculateStandalonePdbStreamSize() == endPosition - startPosition); } public void SerializeMetadata(BlobBuilder builder, Func<BlobBuilder, ContentId> idProvider, out ContentId contentId) { SerializeMetadataImpl(builder, methodBodyStreamRva: 0, mappedFieldDataStreamRva: 0); contentId = idProvider(builder); // fill in the id: var idWriter = new BlobWriter(_pdbIdBlob); idWriter.WriteBytes(contentId.Guid); idWriter.WriteBytes(contentId.Stamp); Debug.Assert(idWriter.RemainingBytes == 0); } } #if SRM public #endif sealed class TypeSystemMetadataSerializer : MetadataSerializer { private static readonly ImmutableArray<int> EmptyRowCounts = ImmutableArray.CreateRange(Enumerable.Repeat(0, MetadataTokens.TableCount)); public TypeSystemMetadataSerializer( MetadataBuilder tables, string metadataVersion, bool isMinimalDelta) : base(tables, CreateSizes(tables, EmptyRowCounts, isMinimalDelta, isStandaloneDebugMetadata: false), metadataVersion) { } protected override void SerializeStandalonePdbStream(BlobBuilder writer) { // nop } public void SerializeMetadata(BlobBuilder metadataWriter, int methodBodyStreamRva, int mappedFieldDataStreamRva) { SerializeMetadataImpl(metadataWriter, methodBodyStreamRva, mappedFieldDataStreamRva); } } #if SRM public #endif abstract class MetadataSerializer { protected readonly MetadataBuilder _tables; private readonly MetadataSizes _sizes; private readonly string _metadataVersion; public MetadataSerializer(MetadataBuilder tables, MetadataSizes sizes, string metadataVersion) { _tables = tables; _sizes = sizes; _metadataVersion = metadataVersion; } internal static MetadataSizes CreateSizes(MetadataBuilder tables, ImmutableArray<int> externalRowCounts, bool isMinimalDelta, bool isStandaloneDebugMetadata) { tables.CompleteHeaps(); return new MetadataSizes( tables.GetRowCounts(), externalRowCounts, tables.GetHeapSizes(), isMinimalDelta, isStandaloneDebugMetadata); } protected abstract void SerializeStandalonePdbStream(BlobBuilder writer); public MetadataSizes MetadataSizes => _sizes; protected void SerializeMetadataImpl(BlobBuilder metadataWriter, int methodBodyStreamRva, int mappedFieldDataStreamRva) { // header: SerializeMetadataHeader(metadataWriter); // #Pdb stream SerializeStandalonePdbStream(metadataWriter); // #~ or #- stream: _tables.SerializeMetadataTables(metadataWriter, _sizes, methodBodyStreamRva, mappedFieldDataStreamRva); // #Strings, #US, #Guid and #Blob streams: _tables.WriteHeapsTo(metadataWriter); } private void SerializeMetadataHeader(BlobBuilder writer) { int startOffset = writer.Position; // signature writer.WriteUInt32(0x424A5342); // major version writer.WriteUInt16(1); // minor version writer.WriteUInt16(1); // reserved writer.WriteUInt32(0); // metadata version length writer.WriteUInt32(MetadataSizes.MetadataVersionPaddedLength); int n = Math.Min(MetadataSizes.MetadataVersionPaddedLength, _metadataVersion.Length); for (int i = 0; i < n; i++) { writer.WriteByte((byte)_metadataVersion[i]); } for (int i = n; i < MetadataSizes.MetadataVersionPaddedLength; i++) { writer.WriteByte(0); } // reserved writer.WriteUInt16(0); // number of streams writer.WriteUInt16((ushort)(5 + (_sizes.IsMinimalDelta ? 1 : 0) + (_sizes.IsStandaloneDebugMetadata ? 1 : 0))); // stream headers int offsetFromStartOfMetadata = _sizes.MetadataHeaderSize; // emit the #Pdb stream first so that only a single page has to be read in order to find out PDB ID if (_sizes.IsStandaloneDebugMetadata) { SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.StandalonePdbStreamSize, "#Pdb", writer); } // Spec: Some compilers store metadata in a #- stream, which holds an uncompressed, or non-optimized, representation of metadata tables; // this includes extra metadata -Ptr tables. Such PE files do not form part of ECMA-335 standard. // // Note: EnC delta is stored as uncompressed metadata stream. SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.MetadataTableStreamSize, (_sizes.IsMetadataTableStreamCompressed ? "#~" : "#-"), writer); SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.String), "#Strings", writer); SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.UserString), "#US", writer); SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.Guid), "#GUID", writer); SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.Blob), "#Blob", writer); if (_sizes.IsMinimalDelta) { SerializeStreamHeader(ref offsetFromStartOfMetadata, 0, "#JTD", writer); } int endOffset = writer.Position; Debug.Assert(endOffset - startOffset == _sizes.MetadataHeaderSize); } private static void SerializeStreamHeader(ref int offsetFromStartOfMetadata, int alignedStreamSize, string streamName, BlobBuilder writer) { // 4 for the first uint (offset), 4 for the second uint (padded size), length of stream name + 1 for null terminator (then padded) int sizeOfStreamHeader = MetadataSizes.GetMetadataStreamHeaderSize(streamName); writer.WriteInt32(offsetFromStartOfMetadata); writer.WriteInt32(alignedStreamSize); foreach (char ch in streamName) { writer.WriteByte((byte)ch); } // After offset, size, and stream name, write 0-bytes until we reach our padded size. for (uint i = 8 + (uint)streamName.Length; i < sizeOfStreamHeader; i++) { writer.WriteByte(0); } offsetFromStartOfMetadata += alignedStreamSize; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AutoScaling.Model { /// <summary> /// Container for the parameters to the PutScheduledUpdateGroupAction operation. /// Creates or updates a scheduled scaling action for an Auto Scaling group. When updating /// a scheduled scaling action, if you leave a parameter unspecified, the corresponding /// value remains unchanged in the affected Auto Scaling group. /// /// /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/schedule_time.html">Scheduled /// Scaling</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// </summary> public partial class PutScheduledUpdateGroupActionRequest : AmazonAutoScalingRequest { private string _autoScalingGroupName; private int? _desiredCapacity; private DateTime? _endTime; private int? _maxSize; private int? _minSize; private string _recurrence; private string _scheduledActionName; private DateTime? _startTime; private DateTime? _time; /// <summary> /// Gets and sets the property AutoScalingGroupName. /// <para> /// The name or Amazon Resource Name (ARN) of the Auto Scaling group. /// </para> /// </summary> public string AutoScalingGroupName { get { return this._autoScalingGroupName; } set { this._autoScalingGroupName = value; } } // Check to see if AutoScalingGroupName property is set internal bool IsSetAutoScalingGroupName() { return this._autoScalingGroupName != null; } /// <summary> /// Gets and sets the property DesiredCapacity. /// <para> /// The number of EC2 instances that should be running in the group. /// </para> /// </summary> public int DesiredCapacity { get { return this._desiredCapacity.GetValueOrDefault(); } set { this._desiredCapacity = value; } } // Check to see if DesiredCapacity property is set internal bool IsSetDesiredCapacity() { return this._desiredCapacity.HasValue; } /// <summary> /// Gets and sets the property EndTime. /// <para> /// The time for this action to end. /// </para> /// </summary> public DateTime EndTime { get { return this._endTime.GetValueOrDefault(); } set { this._endTime = value; } } // Check to see if EndTime property is set internal bool IsSetEndTime() { return this._endTime.HasValue; } /// <summary> /// Gets and sets the property MaxSize. /// <para> /// The maximum size for the Auto Scaling group. /// </para> /// </summary> public int MaxSize { get { return this._maxSize.GetValueOrDefault(); } set { this._maxSize = value; } } // Check to see if MaxSize property is set internal bool IsSetMaxSize() { return this._maxSize.HasValue; } /// <summary> /// Gets and sets the property MinSize. /// <para> /// The minimum size for the Auto Scaling group. /// </para> /// </summary> public int MinSize { get { return this._minSize.GetValueOrDefault(); } set { this._minSize = value; } } // Check to see if MinSize property is set internal bool IsSetMinSize() { return this._minSize.HasValue; } /// <summary> /// Gets and sets the property Recurrence. /// <para> /// The time when recurring future actions will start. Start time is specified by the /// user following the Unix cron syntax format. For more information, see <a href="http://en.wikipedia.org/wiki/Cron">Cron</a> /// in Wikipedia. /// </para> /// /// <para> /// When <code>StartTime</code> and <code>EndTime</code> are specified with <code>Recurrence</code>, /// they form the boundaries of when the recurring action will start and stop. /// </para> /// </summary> public string Recurrence { get { return this._recurrence; } set { this._recurrence = value; } } // Check to see if Recurrence property is set internal bool IsSetRecurrence() { return this._recurrence != null; } /// <summary> /// Gets and sets the property ScheduledActionName. /// <para> /// The name of this scaling action. /// </para> /// </summary> public string ScheduledActionName { get { return this._scheduledActionName; } set { this._scheduledActionName = value; } } // Check to see if ScheduledActionName property is set internal bool IsSetScheduledActionName() { return this._scheduledActionName != null; } /// <summary> /// Gets and sets the property StartTime. /// <para> /// The time for this action to start, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only /// (for example, <code>2014-06-01T00:00:00Z</code>). /// </para> /// /// <para> /// If you try to schedule your action in the past, Auto Scaling returns an error message. /// /// </para> /// /// <para> /// When <code>StartTime</code> and <code>EndTime</code> are specified with <code>Recurrence</code>, /// they form the boundaries of when the recurring action starts and stops. /// </para> /// </summary> public DateTime StartTime { get { return this._startTime.GetValueOrDefault(); } set { this._startTime = value; } } // Check to see if StartTime property is set internal bool IsSetStartTime() { return this._startTime.HasValue; } /// <summary> /// Gets and sets the property Time. /// <para> /// This parameter is deprecated; use <code>StartTime</code> instead. /// </para> /// /// <para> /// The time for this action to start. If both <code>Time</code> and <code>StartTime</code> /// are specified, their values must be identical. /// </para> /// </summary> public DateTime Time { get { return this._time.GetValueOrDefault(); } set { this._time = value; } } // Check to see if Time property is set internal bool IsSetTime() { return this._time.HasValue; } } }
// 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.Win32.SafeHandles; using System.Security; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { /// <summary> /// Named pipe client. Use this to open the client end of a named pipes created with /// NamedPipeServerStream. /// </summary> public sealed partial class NamedPipeClientStream : PipeStream { // Maximum interval in milliseconds between which cancellation is checked. // Used by ConnectInternal. 50ms is fairly responsive time but really long time for processor. private const int CancellationCheckInterval = 50; private readonly string _normalizedPipePath; private readonly TokenImpersonationLevel _impersonationLevel; private readonly PipeOptions _pipeOptions; private readonly HandleInheritability _inheritability; private readonly PipeDirection _direction; // Creates a named pipe client using default server (same machine, or "."), and PipeDirection.InOut [SecuritySafeCritical] public NamedPipeClientStream(String pipeName) : this(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeClientStream(String serverName, String pipeName) : this(serverName, pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction) : this(serverName, pipeName, direction, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction, PipeOptions options) : this(serverName, pipeName, direction, options, TokenImpersonationLevel.None, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction, PipeOptions options, TokenImpersonationLevel impersonationLevel) : this(serverName, pipeName, direction, options, impersonationLevel, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability) : base(direction, 0) { if (pipeName == null) { throw new ArgumentNullException(nameof(pipeName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName), SR.ArgumentNull_ServerName); } if (pipeName.Length == 0) { throw new ArgumentException(SR.Argument_NeedNonemptyPipeName); } if (serverName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyServerName); } if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0) { throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid); } if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation) { throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable); } _normalizedPipePath = GetPipePath(serverName, pipeName); _direction = direction; _inheritability = inheritability; _impersonationLevel = impersonationLevel; _pipeOptions = options; } // Create a NamedPipeClientStream from an existing server pipe handle. [SecuritySafeCritical] public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, 0) { if (safePipeHandle == null) { throw new ArgumentNullException(nameof(safePipeHandle)); } if (safePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, nameof(safePipeHandle)); } ValidateHandleIsPipe(safePipeHandle); InitializeHandle(safePipeHandle, true, isAsync); if (isConnected) { State = PipeState.Connected; } } ~NamedPipeClientStream() { Dispose(false); } public void Connect() { Connect(Timeout.Infinite); } public void Connect(int timeout) { CheckConnectOperationsClient(); if (timeout < 0 && timeout != Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_InvalidTimeout); } ConnectInternal(timeout, CancellationToken.None, Environment.TickCount); } [SecurityCritical] private void ConnectInternal(int timeout, CancellationToken cancellationToken, int startTime) { // This is the main connection loop. It will loop until the timeout expires. int elapsed = 0; var sw = new SpinWait(); do { cancellationToken.ThrowIfCancellationRequested(); // Determine how long we should wait in this connection attempt int waitTime = timeout - elapsed; if (cancellationToken.CanBeCanceled && waitTime > CancellationCheckInterval) { waitTime = CancellationCheckInterval; } // Try to connect. if (TryConnect(waitTime, cancellationToken)) { return; } // Some platforms may return immediately from TryConnect if the connection could not be made, // e.g. WaitNamedPipe on Win32 will return immediately if the pipe hasn't yet been created, // and open on Unix will fail if the file isn't yet available. Rather than just immediately // looping around again, do slightly smarter busy waiting. sw.SpinOnce(); } while (timeout == Timeout.Infinite || (elapsed = unchecked(Environment.TickCount - startTime)) < timeout); throw new TimeoutException(); } public Task ConnectAsync() { // We cannot avoid creating lambda here by using Connect method // unless we don't care about start time to be measured before the thread is started return ConnectAsync(Timeout.Infinite, CancellationToken.None); } public Task ConnectAsync(int timeout) { return ConnectAsync(timeout, CancellationToken.None); } public Task ConnectAsync(CancellationToken cancellationToken) { return ConnectAsync(Timeout.Infinite, cancellationToken); } public Task ConnectAsync(int timeout, CancellationToken cancellationToken) { CheckConnectOperationsClient(); if (timeout < 0 && timeout != Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_InvalidTimeout); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } int startTime = Environment.TickCount; // We need to measure time here, not in the lambda return Task.Run(() => ConnectInternal(timeout, cancellationToken, startTime), cancellationToken); } // override because named pipe clients can't get/set properties when waiting to connect // or broken [SecurityCritical] protected internal override void CheckPipePropertyOperations() { base.CheckPipePropertyOperations(); if (State == PipeState.WaitingToConnect) { throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected); } if (State == PipeState.Broken) { throw new IOException(SR.IO_PipeBroken); } } // named client is allowed to connect from broken private void CheckConnectOperationsClient() { if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } if (State == PipeState.Closed) { throw Error.GetPipeNotOpen(); } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Layouts { using System; using System.Collections.Generic; using NLog.LayoutRenderers; using NLog.Targets; using Xunit; public class AllEventPropertiesTests : NLogTestBase { [Fact] public void AllParametersAreSetToDefault() { var renderer = new AllEventPropertiesLayoutRenderer(); var ev = BuildLogEventWithProperties(); var result = renderer.Render(ev); Assert.Equal("a=1, hello=world, 17=100", result); } [Fact] public void CustomSeparator() { var renderer = new AllEventPropertiesLayoutRenderer(); renderer.Separator = " | "; var ev = BuildLogEventWithProperties(); var result = renderer.Render(ev); Assert.Equal("a=1 | hello=world | 17=100", result); } [Fact] public void CustomFormat() { var renderer = new AllEventPropertiesLayoutRenderer(); renderer.Format = "[key] is [value]"; var ev = BuildLogEventWithProperties(); var result = renderer.Render(ev); Assert.Equal("a is 1, hello is world, 17 is 100", result); } [Fact] public void NoProperties() { var renderer = new AllEventPropertiesLayoutRenderer(); var ev = new LogEventInfo(); var result = renderer.Render(ev); Assert.Equal("", result); } [Fact] public void EventPropertyFormat() { var renderer = new AllEventPropertiesLayoutRenderer(); var ev = new LogEventInfo(LogLevel.Info, null, null, "{pi:0}", new object[] { 3.14159265359 }); var result = renderer.Render(ev); Assert.Equal("pi=3", result); } [Fact] public void StructuredLoggingProperties() { var renderer = new AllEventPropertiesLayoutRenderer(); var planetProperties = new System.Collections.Generic.Dictionary<string, object>() { { "Name", "Earth" }, { "PlanetType", "Water-world" }, }; var ev = new LogEventInfo(LogLevel.Info, null, null, "Hello Planet {@planet}", new object[] { planetProperties }); var result = renderer.Render(ev); Assert.Equal(@"planet=""Name""=""Earth"", ""PlanetType""=""Water-world""", result); } [Fact] public void IncludeScopeProperties() { var renderer = new AllEventPropertiesLayoutRenderer() { IncludeScopeProperties = true }; var ev = new LogEventInfo(LogLevel.Info, null, null, "{pi:0}", new object[] { 3.14159265359 }); using (ScopeContext.PushProperty("Figure", "Circle")) { var result = renderer.Render(ev); Assert.Equal("pi=3, Figure=Circle", result); } } [Fact] public void TestInvalidCustomFormatWithoutKeyPlaceholder() { var renderer = new AllEventPropertiesLayoutRenderer(); var ex = Assert.Throws<ArgumentException>(() => renderer.Format = "[key is [value]"); Assert.Equal("Invalid format: [key] placeholder is missing.", ex.Message); } [Fact] public void TestInvalidCustomFormatWithoutValuePlaceholder() { var renderer = new AllEventPropertiesLayoutRenderer(); var ex = Assert.Throws<ArgumentException>(() => renderer.Format = "[key] is [vlue]"); Assert.Equal("Invalid format: [value] placeholder is missing.", ex.Message); } [Fact] public void AllEventWithFluent_without_callerInformation() { //Arrange LogFactory logFactory = new LogFactory() .Setup() .LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget("debug") { Layout = "${all-event-properties}" }); }) .LogFactory; //Act logFactory.GetCurrentClassLogger() .WithProperty("Test", "InfoWrite") .WithProperty("coolness", "200%") .WithProperty("a", "not b") .Debug("This is a test message '{0}'.", DateTime.Now.Ticks); //Assert logFactory.AssertDebugLastMessage("Test=InfoWrite, coolness=200%, a=not b"); } [Fact] public void WithPropertiesTest() { //Arrange LogFactory logFactory = new LogFactory() .Setup() .LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget("debug") { Layout = "${all-event-properties}" }); }) .LogFactory; Dictionary<string, object> properties = new Dictionary<string, object>() { {"TestString", "myString" }, {"TestInt", 999 } }; //Act logFactory.GetCurrentClassLogger() .WithProperties(properties) .Debug("This is a test message '{0}'.", DateTime.Now.Ticks); //Assert logFactory.AssertDebugLastMessage("TestString=myString, TestInt=999"); } #if NET35 || NET40 [Fact(Skip = "NET35 not supporting Caller-Attributes")] #else [Fact] #endif public void AllEventWithFluent_with_callerInformation() { //Arrange LogFactory logFactory = new LogFactory() .Setup() .LoadConfiguration(builder => { builder.ForLogger().WriteTo(new DebugTarget("debug") { Layout = "${all-event-properties}${callsite}" }); }) .LogFactory; //Act logFactory.GetCurrentClassLogger() .WithProperty("Test", "InfoWrite") .WithProperty("coolness", "200%") .WithProperty("a", "not b") .Debug("This is a test message '{0}'.", DateTime.Now.Ticks); //Assert logFactory.AssertDebugLastMessageContains(nameof(AllEventWithFluent_with_callerInformation)); logFactory.AssertDebugLastMessageContains(nameof(AllEventPropertiesTests)); } [Theory] [InlineData(null, "a=1, hello=world, 17=100, notempty=0")] [InlineData(false, "a=1, hello=world, 17=100, notempty=0")] [InlineData(true, "a=1, hello=world, 17=100, empty1=, empty2=, notempty=0")] public void IncludeEmptyValuesTest(bool? includeEmptyValues, string expected) { // Arrange var renderer = new AllEventPropertiesLayoutRenderer(); if (includeEmptyValues != null) { renderer.IncludeEmptyValues = includeEmptyValues.Value; } var ev = BuildLogEventWithProperties(); ev.Properties["empty1"] = null; ev.Properties["empty2"] = ""; ev.Properties["notempty"] = 0; // Act var result = renderer.Render(ev); // Assert Assert.Equal(expected, result); } [Theory] [InlineData("", "a=1, hello=world, 17=100")] [InlineData("Wrong", "a=1, hello=world, 17=100")] [InlineData("hello", "a=1, 17=100")] [InlineData("Hello", "a=1, 17=100")] [InlineData("Hello, 17", "a=1")] public void ExcludeSingleProperty(string exclude, string result) { // Arrange var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog throwExceptions='true'> <targets> <target type='Debug' name='debug' layout='${all-event-properties:Exclude=" + exclude + @"}' /> </targets> <rules> <logger name='*' writeTo='debug' /> </rules> </nlog>").LogFactory; var logger = logFactory.GetCurrentClassLogger(); // Act var ev = BuildLogEventWithProperties(); logger.Log(ev); // Assert logFactory.AssertDebugLastMessageContains(result); } private static LogEventInfo BuildLogEventWithProperties() { var ev = new LogEventInfo() { Level = LogLevel.Info }; ev.Properties["a"] = 1; ev.Properties["hello"] = "world"; ev.Properties[17] = 100; return ev; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Configuration; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using ASC.Common.Logging; using ASC.Common.Module; using ASC.Core; using ASC.Core.Notify.Signalr; using WebSocketSharp; namespace ASC.Socket.IO.Svc { public class Launcher : IServiceController { private static Process proc; private static ProcessStartInfo startInfo; private static WebSocket webSocket; private static CancellationTokenSource cancellationTokenSource; private const int PingInterval = 10000; private static readonly ILog Logger = LogManager.GetLogger("ASC"); private static string LogDir; public void Start() { try { cancellationTokenSource = new CancellationTokenSource(); var cfg = (SocketIOCfgSectionHandler)ConfigurationManagerExtension.GetSection("socketio"); startInfo = new ProcessStartInfo { CreateNoWindow = false, UseShellExecute = false, FileName = "node", WindowStyle = ProcessWindowStyle.Hidden, Arguments = string.Format("\"{0}\"", Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), cfg.Path, "app.js"))), WorkingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) }; var appSettings = ConfigurationManagerExtension.AppSettings; startInfo.EnvironmentVariables.Add("core.machinekey", appSettings["core.machinekey"]); startInfo.EnvironmentVariables.Add("port", cfg.Port); if (cfg.Redis != null && !string.IsNullOrEmpty(cfg.Redis.Host) && !string.IsNullOrEmpty(cfg.Redis.Port)) { startInfo.EnvironmentVariables.Add("redis:host", cfg.Redis.Host); startInfo.EnvironmentVariables.Add("redis:port", cfg.Redis.Port); } if (CoreContext.Configuration.Standalone) { startInfo.EnvironmentVariables.Add("portal.internal.url", "http://localhost"); } LogDir = Logger.LogDirectory; startInfo.EnvironmentVariables.Add("logPath", Path.Combine(LogDir, "web.socketio.log")); StartNode(); } catch (Exception e) { Logger.Error(e); } } public void Stop() { StopPing(); StopNode(); } private static void StartNode() { StopNode(); proc = Process.Start(startInfo); var task = new Task(StartPing, cancellationTokenSource.Token, TaskCreationOptions.LongRunning); task.Start(TaskScheduler.Default); } private static void StopNode() { try { if (proc != null && !proc.HasExited) { proc.Kill(); if (!proc.WaitForExit(10000)) /* wait 10 seconds */ { Logger.Warn("The process does not wait for completion."); } proc.Close(); proc.Dispose(); proc = null; } } catch (Exception e) { Logger.Error("SocketIO failed stop", e); } } private static void StartPing() { Thread.Sleep(PingInterval); var pingCancellationTokenSource = new CancellationTokenSource(); var error = false; webSocket = new WebSocket(string.Format("ws://127.0.0.1:{0}/socket.io/?EIO=3&transport=websocket", startInfo.EnvironmentVariables["port"])); webSocket.SetCookie(new WebSocketSharp.Net.Cookie("authorization", SignalrServiceClient.CreateAuthToken())); webSocket.EmitOnPing = true; webSocket.Log.Level = LogLevel.Trace; webSocket.Log.Output = (logData, filePath) => { if (logData.Message.Contains("SocketException")) { error = true; } Logger.Debug(logData.Message); }; webSocket.OnOpen += (sender, e) => { pingCancellationTokenSource = new CancellationTokenSource(); Logger.Info("Open"); error = false; Thread.Sleep(PingInterval); var task = new Task(() => { while (webSocket.Ping()) { Logger.Debug("Ping " + webSocket.ReadyState); Thread.Sleep(PingInterval); } Logger.Debug("Reconnect" + webSocket.ReadyState); }, pingCancellationTokenSource.Token, TaskCreationOptions.LongRunning); task.Start(TaskScheduler.Default); }; webSocket.OnClose += (sender, e) => { Logger.Info("Close"); pingCancellationTokenSource.Cancel(); pingCancellationTokenSource.Dispose(); if (cancellationTokenSource.IsCancellationRequested) return; if (error) { Process.GetCurrentProcess().Kill(); } else { StartPing(); } }; webSocket.OnMessage += (sender, e) => { if (e.Data.Contains("error")) { Logger.Error("Auth error"); cancellationTokenSource.Cancel(); } }; webSocket.OnError += (sender, e) => { Logger.Error("Error", e.Exception); }; webSocket.Connect(); } private static void StopPing() { try { cancellationTokenSource.Cancel(); if (webSocket.IsAlive) { webSocket.Close(); webSocket = null; } } catch (Exception) { Logger.Error("Ping failed stop"); } } } }
//------------------------------------------------------------------------------ // <copyright file="basecomparevalidator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Web; using System.Web.UI.HtmlControls; using System.Text.RegularExpressions; using System.Text; using System.Web.Util; /// <devdoc> /// <para> Serves as the abstract base /// class for validators that do typed comparisons.</para> /// </devdoc> public abstract class BaseCompareValidator : BaseValidator { /// <devdoc> /// <para>Gets or sets the data type that specifies how the values /// being compared should be interpreted.</para> /// </devdoc> [ WebCategory("Behavior"), Themeable(false), DefaultValue(ValidationDataType.String), WebSysDescription(SR.RangeValidator_Type) ] public ValidationDataType Type { get { object o = ViewState["Type"]; return((o == null) ? ValidationDataType.String : (ValidationDataType)o); } set { if (value < ValidationDataType.String || value > ValidationDataType.Currency) { throw new ArgumentOutOfRangeException("value"); } ViewState["Type"] = value; } } /// <devdoc> /// Whether we should do culture invariant conversion against the /// string value properties on the control /// </devdoc> [ WebCategory("Behavior"), Themeable(false), DefaultValue(false), WebSysDescription(SR.BaseCompareValidator_CultureInvariantValues) ] public bool CultureInvariantValues { get { object o = ViewState["CultureInvariantValues"]; return((o == null) ? false : (bool)o); } set { ViewState["CultureInvariantValues"] = value; } } /// <internalonly/> /// <devdoc> /// AddAttributesToRender method /// </devdoc> protected override void AddAttributesToRender(HtmlTextWriter writer) { base.AddAttributesToRender(writer); if (RenderUplevel) { ValidationDataType type = Type; if (type != ValidationDataType.String) { string id = ClientID; HtmlTextWriter expandoAttributeWriter = (EnableLegacyRendering || IsUnobtrusive) ? writer : null; AddExpandoAttribute(expandoAttributeWriter, id, "type", PropertyConverter.EnumToString(typeof(ValidationDataType), type), false); NumberFormatInfo info = NumberFormatInfo.CurrentInfo; if (type == ValidationDataType.Double) { string decimalChar = info.NumberDecimalSeparator; AddExpandoAttribute(expandoAttributeWriter, id, "decimalchar", decimalChar); } else if (type == ValidationDataType.Currency) { string decimalChar = info.CurrencyDecimalSeparator; AddExpandoAttribute(expandoAttributeWriter, id, "decimalchar", decimalChar); string groupChar = info.CurrencyGroupSeparator; // Map non-break space onto regular space for parsing if (groupChar[0] == 160) groupChar = " "; AddExpandoAttribute(expandoAttributeWriter, id, "groupchar", groupChar); int digits = info.CurrencyDecimalDigits; AddExpandoAttribute(expandoAttributeWriter, id, "digits", digits.ToString(NumberFormatInfo.InvariantInfo), false); // VSWhidbey 83165 int groupSize = GetCurrencyGroupSize(info); if (groupSize > 0) { AddExpandoAttribute(expandoAttributeWriter, id, "groupsize", groupSize.ToString(NumberFormatInfo.InvariantInfo), false); } } else if (type == ValidationDataType.Date) { AddExpandoAttribute(expandoAttributeWriter, id, "dateorder", GetDateElementOrder(), false); AddExpandoAttribute(expandoAttributeWriter, id, "cutoffyear", CutoffYear.ToString(NumberFormatInfo.InvariantInfo), false); // VSWhidbey 504553: The changes of this bug make client-side script not // using the century attribute anymore, but still generating it for // backward compatibility with Everett pages. int currentYear = DateTime.Today.Year; int century = currentYear - (currentYear % 100); AddExpandoAttribute(expandoAttributeWriter, id, "century", century.ToString(NumberFormatInfo.InvariantInfo), false); } } } } /// <devdoc> /// Check if the text can be converted to the type /// </devdoc> public static bool CanConvert(string text, ValidationDataType type) { return CanConvert(text, type, false); } public static bool CanConvert(string text, ValidationDataType type, bool cultureInvariant) { object value = null; return Convert(text, type, cultureInvariant, out value); } /// <internalonly/> /// <devdoc> /// Return the order of date elements for the current culture /// </devdoc> protected static string GetDateElementOrder() { DateTimeFormatInfo info = DateTimeFormatInfo.CurrentInfo; string shortPattern = info.ShortDatePattern; if (shortPattern.IndexOf('y') < shortPattern.IndexOf('M')) { return "ymd"; } else if (shortPattern.IndexOf('M') < shortPattern.IndexOf('d')) { return "mdy"; } else { return "dmy"; } } // VSWhidbey 83165 private static int GetCurrencyGroupSize(NumberFormatInfo info) { int [] groupSizes = info.CurrencyGroupSizes; if (groupSizes != null && groupSizes.Length == 1) { return groupSizes[0]; } else { return -1; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected static int CutoffYear { get { return DateTimeFormatInfo.CurrentInfo.Calendar.TwoDigitYearMax; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected static int GetFullYear(int shortYear) { Debug.Assert(shortYear >= 0 && shortYear < 100); return DateTimeFormatInfo.CurrentInfo.Calendar.ToFourDigitYear(shortYear); } /// <devdoc> /// Try to convert the test into the validation data type /// </devdoc> protected static bool Convert(string text, ValidationDataType type, out object value) { return Convert(text, type, false, out value); } protected static bool Convert(string text, ValidationDataType type, bool cultureInvariant, out object value) { value = null; try { switch (type) { case ValidationDataType.String: value = text; break; case ValidationDataType.Integer: value = Int32.Parse(text, CultureInfo.InvariantCulture); break; case ValidationDataType.Double: { string cleanInput; if (cultureInvariant) { cleanInput = ConvertDouble(text, CultureInfo.InvariantCulture.NumberFormat); } else { cleanInput = ConvertDouble(text, NumberFormatInfo.CurrentInfo); } if (cleanInput != null) { value = Double.Parse(cleanInput, CultureInfo.InvariantCulture); } break; } case ValidationDataType.Date: { if (cultureInvariant) { value = ConvertDate(text, "ymd"); } else { // if the calendar is not gregorian, we should not enable client-side, so just parse it directly: if (!(DateTimeFormatInfo.CurrentInfo.Calendar.GetType() == typeof(GregorianCalendar))) { value = DateTime.Parse(text, CultureInfo.CurrentCulture); break; } string dateElementOrder = GetDateElementOrder(); value = ConvertDate(text, dateElementOrder); } break; } case ValidationDataType.Currency: { string cleanInput; if (cultureInvariant) { cleanInput = ConvertCurrency(text, CultureInfo.InvariantCulture.NumberFormat); } else { cleanInput = ConvertCurrency(text, NumberFormatInfo.CurrentInfo); } if (cleanInput != null) { value = Decimal.Parse(cleanInput, CultureInfo.InvariantCulture); } break; } } } catch { value = null; } return (value != null); } private static string ConvertCurrency(string text, NumberFormatInfo info) { string decimalChar = info.CurrencyDecimalSeparator; string groupChar = info.CurrencyGroupSeparator; // VSWhidbey 83165 string beginGroupSize, subsequentGroupSize; int groupSize = GetCurrencyGroupSize(info); if (groupSize > 0) { string groupSizeText = groupSize.ToString(NumberFormatInfo.InvariantInfo); beginGroupSize = "{1," + groupSizeText + "}"; subsequentGroupSize = "{" + groupSizeText + "}"; } else { beginGroupSize = subsequentGroupSize = "+"; } // Map non-break space onto regular space for parsing if (groupChar[0] == 160) groupChar = " "; int digits = info.CurrencyDecimalDigits; bool hasDigits = (digits > 0); string currencyExpression = "^\\s*([-\\+])?((\\d" + beginGroupSize + "(\\" + groupChar + "\\d" + subsequentGroupSize + ")+)|\\d*)" + (hasDigits ? "\\" + decimalChar + "?(\\d{0," + digits.ToString(NumberFormatInfo.InvariantInfo) + "})" : string.Empty) + "\\s*$"; Match m = Regex.Match(text, currencyExpression); if (!m.Success) { return null; } // Make sure there are some valid digits if (m.Groups[2].Length == 0 && hasDigits && m.Groups[5].Length == 0) { return null; } return m.Groups[1].Value + m.Groups[2].Value.Replace(groupChar, string.Empty) + ((hasDigits && m.Groups[5].Length > 0) ? "." + m.Groups[5].Value : string.Empty); } private static string ConvertDouble(string text, NumberFormatInfo info) { // VSWhidbey 83156: If text is empty, it would be default to 0 for // backward compatibility reason. if (text.Length == 0) { return "0"; } string decimalChar = info.NumberDecimalSeparator; string doubleExpression = "^\\s*([-\\+])?(\\d*)\\" + decimalChar + "?(\\d*)\\s*$"; Match m = Regex.Match(text, doubleExpression); if (!m.Success) { return null; } // Make sure there are some valid digits if (m.Groups[2].Length == 0 && m.Groups[3].Length == 0) { return null; } return m.Groups[1].Value + (m.Groups[2].Length > 0 ? m.Groups[2].Value : "0") + ((m.Groups[3].Length > 0) ? "." + m.Groups[3].Value: string.Empty); } // **************************************************************************************************************** // ** ** // ** NOTE: When updating the regular expressions in this method, you must also update the regular expressions ** // ** in WebUIValidation.js::ValidatorConvert(). The server and client regular expressions must match. ** // ** ** // **************************************************************************************************************** private static object ConvertDate(string text, string dateElementOrder) { // always allow the YMD format, if they specify 4 digits string dateYearFirstExpression = "^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\.?\\s*$"; Match m = Regex.Match(text, dateYearFirstExpression); int day, month, year; if (m.Success && (m.Groups[2].Success || dateElementOrder == "ymd")) { day = Int32.Parse(m.Groups[6].Value, CultureInfo.InvariantCulture); month = Int32.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture); if (m.Groups[2].Success) { year = Int32.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture); } else { year = GetFullYear(Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture)); } } else { if (dateElementOrder == "ymd") { return null; } // also check for the year last format string dateYearLastExpression = "^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})(?:\\s|\\2)((\\d{4})|(\\d{2}))(?:\\s\u0433\\.|\\.)?\\s*$"; m = Regex.Match(text, dateYearLastExpression); if (!m.Success) { return null; } if (dateElementOrder == "mdy") { day = Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture); month = Int32.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); } else { day = Int32.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); month = Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture); } if (m.Groups[5].Success) { year = Int32.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture); } else { year = GetFullYear(Int32.Parse(m.Groups[6].Value, CultureInfo.InvariantCulture)); } } return new DateTime(year, month, day); } /// <devdoc> /// Compare two strings using the type and operator /// </devdoc> protected static bool Compare(string leftText, string rightText, ValidationCompareOperator op, ValidationDataType type) { return Compare(leftText, false, rightText, false, op, type); } protected static bool Compare(string leftText, bool cultureInvariantLeftText, string rightText, bool cultureInvariantRightText, ValidationCompareOperator op, ValidationDataType type) { object leftObject; if (!Convert(leftText, type, cultureInvariantLeftText, out leftObject)) return false; if (op == ValidationCompareOperator.DataTypeCheck) return true; object rightObject; if (!Convert(rightText, type, cultureInvariantRightText, out rightObject)) return true; int compareResult; switch (type) { case ValidationDataType.String: compareResult = String.Compare((string)leftObject, (string) rightObject, false, CultureInfo.CurrentCulture); break; case ValidationDataType.Integer: compareResult = ((int)leftObject).CompareTo(rightObject); break; case ValidationDataType.Double: compareResult = ((double)leftObject).CompareTo(rightObject); break; case ValidationDataType.Date: compareResult = ((DateTime)leftObject).CompareTo(rightObject); break; case ValidationDataType.Currency: compareResult = ((Decimal)leftObject).CompareTo(rightObject); break; default: Debug.Fail("Unknown Type"); return true; } switch (op) { case ValidationCompareOperator.Equal: return compareResult == 0; case ValidationCompareOperator.NotEqual: return compareResult != 0; case ValidationCompareOperator.GreaterThan: return compareResult > 0 ; case ValidationCompareOperator.GreaterThanEqual: return compareResult >= 0 ; case ValidationCompareOperator.LessThan: return compareResult < 0 ; case ValidationCompareOperator.LessThanEqual: return compareResult <= 0 ; default: Debug.Fail("Unknown Operator"); return true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override bool DetermineRenderUplevel() { // We don't do client-side validation for dates with non gregorian calendars if (Type == ValidationDataType.Date && DateTimeFormatInfo.CurrentInfo.Calendar.GetType() != typeof(GregorianCalendar)) { return false; } return base.DetermineRenderUplevel(); } internal string ConvertToShortDateString(string text) { // VSWhidbey 83099, 85305, we should ignore error if it happens and // leave text as intact when parsing the date. We assume the caller // (validator) is able to handle invalid text itself. DateTime date; if (DateTime.TryParse(text, CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { text = date.ToShortDateString(); } return text; } internal bool IsInStandardDateFormat(string date) { // VSWhidbey 115454: We identify that date string with only numbers // and specific punctuation separators is in standard date format. const string standardDateExpression = "^\\s*(\\d+)([-/]|\\. ?)(\\d+)\\2(\\d+)\\s*$"; return Regex.Match(date, standardDateExpression).Success; } internal string ConvertCultureInvariantToCurrentCultureFormat(string valueInString, ValidationDataType type) { object value; Convert(valueInString, type, true, out value); if (value is DateTime) { // For Date type we explicitly want the date portion only return ((DateTime) value).ToShortDateString(); } else { return System.Convert.ToString(value, CultureInfo.CurrentCulture); } } } }
//--------------------------------------------------------------------- // <copyright file="EntitySqlQueryBuilder.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Objects.Internal { using System.Collections.Generic; using System.Data.Common; using System.Data.Common.Utils; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Text; /// <summary> /// Provides Entity-SQL query building services for <see cref="EntitySqlQueryState"/>. /// Knowledge of how to compose Entity-SQL fragments using query builder operators resides entirely in this class. /// </summary> internal static class EntitySqlQueryBuilder { /// <summary> /// Helper method to extract the Entity-SQL command text from an <see cref="ObjectQueryState"/> instance if that /// instance models an Entity-SQL-backed ObjectQuery, or to throw an exception indicating that query builder methods /// are not supported on this query. /// </summary> /// <param name="query">The instance from which the Entity-SQL command text should be retrieved</param> /// <returns>The Entity-SQL command text, if the specified query state instance is based on Entity-SQL</returns> /// <exception cref="NotSupportedException"> /// If the specified instance is not based on Entity-SQL command text, and so does not support Entity-SQL query builder methods /// </exception> private static string GetCommandText(ObjectQueryState query) { string commandText = null; if(!query.TryGetCommandText(out commandText)) { throw EntityUtil.NotSupported(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_NotSupportedLinqSource); } return commandText; } /// <summary> /// Merges <see cref="ObjectParameter"/>s from a source ObjectQuery with ObjectParameters specified as an argument to a builder method. /// A new <see cref="ObjectParameterCollection"/> is returned that contains copies of parameters from both <paramref name="sourceQueryParams"/> and <paramref name="builderMethodParams"/>. /// </summary> /// <param name="context">The <see cref="ObjectContext"/> to use when constructing the new parameter collection</param> /// <param name="sourceQueryParams">ObjectParameters from the ObjectQuery on which the query builder method was called</param> /// <param name="builderMethodParams">ObjectParameters that were specified as an argument to the builder method</param> /// <returns>A new ObjectParameterCollection containing copies of all parameters</returns> private static ObjectParameterCollection MergeParameters(ObjectContext context, ObjectParameterCollection sourceQueryParams, ObjectParameter[] builderMethodParams) { Debug.Assert(builderMethodParams != null, "params array argument should not be null"); if (sourceQueryParams == null && builderMethodParams.Length == 0) { return null; } ObjectParameterCollection mergedParams = ObjectParameterCollection.DeepCopy(sourceQueryParams); if (mergedParams == null) { mergedParams = new ObjectParameterCollection(context.Perspective); } foreach (ObjectParameter builderParam in builderMethodParams) { mergedParams.Add(builderParam); } return mergedParams; } /// <summary> /// Merges <see cref="ObjectParameter"/>s from two ObjectQuery arguments to SetOp builder methods (Except, Intersect, Union, UnionAll). /// A new <see cref="ObjectParameterCollection"/> is returned that contains copies of parameters from both <paramref name="query1Params"/> and <paramref name="query2Params"/>. /// </summary> /// <param name="query1Params">ObjectParameters from the first ObjectQuery argument (on which the query builder method was called)</param> /// <param name="query2Params">ObjectParameters from the second ObjectQuery argument (specified as an argument to the builder method)</param> /// <returns>A new ObjectParameterCollection containing copies of all parameters</returns> private static ObjectParameterCollection MergeParameters(ObjectParameterCollection query1Params, ObjectParameterCollection query2Params) { if (query1Params == null && query2Params == null) { return null; } ObjectParameterCollection mergedParams; ObjectParameterCollection sourceParams; if (query1Params != null) { mergedParams = ObjectParameterCollection.DeepCopy(query1Params); sourceParams = query2Params; } else { mergedParams = ObjectParameterCollection.DeepCopy(query2Params); sourceParams = query1Params; } if (sourceParams != null) { foreach (ObjectParameter sourceParam in sourceParams) { mergedParams.Add(sourceParam.ShallowCopy()); } } return mergedParams; } private static ObjectQueryState NewBuilderQuery(ObjectQueryState sourceQuery, Type elementType, StringBuilder queryText, Span newSpan, IEnumerable<ObjectParameter> enumerableParams) { return NewBuilderQuery(sourceQuery, elementType, queryText, false, newSpan, enumerableParams); } private static ObjectQueryState NewBuilderQuery(ObjectQueryState sourceQuery, Type elementType, StringBuilder queryText, bool allowsLimit, Span newSpan, IEnumerable<ObjectParameter> enumerableParams) { ObjectParameterCollection queryParams = enumerableParams as ObjectParameterCollection; if (queryParams == null && enumerableParams != null) { queryParams = new ObjectParameterCollection(sourceQuery.ObjectContext.Perspective); foreach (ObjectParameter objectParam in enumerableParams) { queryParams.Add(objectParam); } } EntitySqlQueryState newState = new EntitySqlQueryState(elementType, queryText.ToString(), allowsLimit, sourceQuery.ObjectContext, queryParams, newSpan); sourceQuery.ApplySettingsTo(newState); return newState; } // Note that all query builder string constants contain embedded newlines to prevent manipulation of the // query text by single line comments (--) that might appear in user-supplied portions of the string such // as a filter predicate, projection list, etc. #region SetOp Helpers private const string _setOpEpilog = @" )"; private const string _setOpProlog = @"( "; // SetOp helper - note that this doesn't merge Spans, since Except uses the original query's Span // while Intersect/Union/UnionAll use the merged Span. private static ObjectQueryState BuildSetOp(ObjectQueryState leftQuery, ObjectQueryState rightQuery, Span newSpan, string setOp) { // Assert that the arguments aren't null (should have been verified by ObjectQuery) Debug.Assert(leftQuery != null, "Left query is null?"); Debug.Assert(rightQuery != null, "Right query is null?"); Debug.Assert(leftQuery.ElementType.Equals(rightQuery.ElementType), "Incompatible element types in arguments to Except<T>/Intersect<T>/Union<T>/UnionAll<T>?"); // Retrieve the left and right arguments to the set operation - // this will throw if either input query is not an Entity-SQL query. string left = GetCommandText(leftQuery); string right = GetCommandText(rightQuery); // ObjectQuery arguments must be associated with the same ObjectContext instance as the implemented query if (!object.ReferenceEquals(leftQuery.ObjectContext, rightQuery.ObjectContext)) { throw EntityUtil.Argument(System.Data.Entity.Strings.ObjectQuery_QueryBuilder_InvalidQueryArgument, "query"); } // Create a string builder only large enough to contain the new query text int queryLength = _setOpProlog.Length + left.Length + setOp.Length + right.Length + _setOpEpilog.Length; StringBuilder builder = new StringBuilder(queryLength); // Build the new query builder.Append(_setOpProlog); builder.Append(left); builder.Append(setOp); builder.Append(right); builder.Append(_setOpEpilog); // Create a new query implementation and apply the state of this implementation to it. // The Span of the query argument will be merged into the new query's Span by the caller, iff the Set Op is NOT Except. // See the Except, Intersect, Union and UnionAll methods in this class for examples. return NewBuilderQuery(leftQuery, leftQuery.ElementType, builder, newSpan, MergeParameters(leftQuery.Parameters, rightQuery.Parameters)); } #endregion #region Select/SelectValue Helpers private const string _fromOp = @" FROM ( "; private const string _asOp = @" ) AS "; private static ObjectQueryState BuildSelectOrSelectValue(ObjectQueryState query, string alias, string projection, ObjectParameter[] parameters, string projectOp, Type elementType) { Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(alias), "Invalid alias"); Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(projection), "Invalid projection"); string queryText = GetCommandText(query); // Build the new query string - "<project op> <projection> FROM (<this query>) AS <alias>" int queryLength = projectOp.Length + projection.Length + _fromOp.Length + queryText.Length + _asOp.Length + alias.Length; StringBuilder builder = new StringBuilder(queryLength); builder.Append(projectOp); builder.Append(projection); builder.Append(_fromOp); builder.Append(queryText); builder.Append(_asOp); builder.Append(alias); // Create a new EntitySqlQueryImplementation that uses the new query as its command text. // Span should not be carried over from a Select or SelectValue operation. return NewBuilderQuery(query, elementType, builder, null, MergeParameters(query.ObjectContext, query.Parameters, parameters)); } #endregion #region OrderBy/Where Helper private static ObjectQueryState BuildOrderByOrWhere(ObjectQueryState query, string alias, string predicateOrKeys, ObjectParameter[] parameters, string op, string skipCount, bool allowsLimit) { Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(alias), "Invalid alias"); Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(predicateOrKeys), "Invalid predicate/keys"); Debug.Assert(null == skipCount || op == _orderByOp, "Skip clause used with WHERE operator?"); string queryText = GetCommandText(query); // Build the new query string: // Either: "SELECT VALUE <alias> FROM (<this query>) AS <alias> WHERE <predicate>" // (for Where) // Or: "SELECT VALUE <alias> FROM (<this query>) AS <alias> ORDER BY <keys> <optional: SKIP <skip>>" // Depending on the value of 'op' int queryLength = _selectValueOp.Length + alias.Length + _fromOp.Length + queryText.Length + _asOp.Length + alias.Length + op.Length + predicateOrKeys.Length; if (skipCount != null) { queryLength += (_skipOp.Length + skipCount.Length); } StringBuilder builder = new StringBuilder(queryLength); builder.Append(_selectValueOp); builder.Append(alias); builder.Append(_fromOp); builder.Append(queryText); builder.Append(_asOp); builder.Append(alias); builder.Append(op); builder.Append(predicateOrKeys); if (skipCount != null) { builder.Append(_skipOp); builder.Append(skipCount); } // Create a new EntitySqlQueryImplementation that uses the new query as its command text. // Span is carried over, no adjustment is needed. return NewBuilderQuery(query, query.ElementType, builder, allowsLimit, query.Span, MergeParameters(query.ObjectContext, query.Parameters, parameters)); } #endregion #region Distinct private const string _distinctProlog = @"SET( "; private const string _distinctEpilog = @" )"; internal static ObjectQueryState Distinct(ObjectQueryState query) { // Build the new query string - "SET(<this query>)" string queryText = GetCommandText(query); StringBuilder builder = new StringBuilder(_distinctProlog.Length + queryText.Length + _distinctEpilog.Length); builder.Append(_distinctProlog); builder.Append(queryText); builder.Append(_distinctEpilog); // Span is carried over, no adjustment is needed return NewBuilderQuery(query, query.ElementType, builder, query.Span, ObjectParameterCollection.DeepCopy(query.Parameters)); } #endregion #region Except private const string _exceptOp = @" ) EXCEPT ( "; internal static ObjectQueryState Except(ObjectQueryState leftQuery, ObjectQueryState rightQuery) { // Call the SetOp helper. // Span is taken from the leftmost query. return EntitySqlQueryBuilder.BuildSetOp(leftQuery, rightQuery, leftQuery.Span, _exceptOp); } #endregion #region GroupBy private const string _groupByOp = @" GROUP BY "; internal static ObjectQueryState GroupBy(ObjectQueryState query, string alias, string keys, string projection, ObjectParameter[] parameters) { Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(alias), "Invalid alias"); Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(alias), "Invalid keys"); Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(projection), "Invalid projection"); string queryText = GetCommandText(query); // Build the new query string: // "SELECT <projection> FROM (<this query>) AS <alias> GROUP BY <keys>" int queryLength = _selectOp.Length + projection.Length + _fromOp.Length + queryText.Length + _asOp.Length + alias.Length + _groupByOp.Length + keys.Length; StringBuilder builder = new StringBuilder(queryLength); builder.Append(_selectOp); builder.Append(projection); builder.Append(_fromOp); builder.Append(queryText); builder.Append(_asOp); builder.Append(alias); builder.Append(_groupByOp); builder.Append(keys); // Create a new EntitySqlQueryImplementation that uses the new query as its command text. // Span should not be carried over from a GroupBy operation. return NewBuilderQuery(query, typeof(DbDataRecord), builder, null, MergeParameters(query.ObjectContext, query.Parameters, parameters)); } #endregion #region Intersect private const string _intersectOp = @" ) INTERSECT ( "; internal static ObjectQueryState Intersect(ObjectQueryState leftQuery, ObjectQueryState rightQuery) { // Ensure the Spans of the query arguments are merged into the new query's Span. Span newSpan = Span.CopyUnion(leftQuery.Span, rightQuery.Span); // Call the SetOp helper. return BuildSetOp(leftQuery, rightQuery, newSpan, _intersectOp); } #endregion #region OfType private const string _ofTypeProlog = @"OFTYPE( ( "; private const string _ofTypeInfix = @" ), ["; private const string _ofTypeInfix2 = "].["; private const string _ofTypeEpilog = @"] )"; internal static ObjectQueryState OfType(ObjectQueryState query, EdmType newType, Type clrOfType) { Debug.Assert(newType != null, "OfType cannot be null"); Debug.Assert(Helper.IsEntityType(newType) || Helper.IsComplexType(newType), "OfType must be Entity or Complex type"); string queryText = GetCommandText(query); // Build the new query string - "OFTYPE((<query>), [<type namespace>].[<type name>])" int queryLength = _ofTypeProlog.Length + queryText.Length + _ofTypeInfix.Length + newType.NamespaceName.Length + (newType.NamespaceName != string.Empty ? _ofTypeInfix2.Length : 0) + newType.Name.Length + _ofTypeEpilog.Length; StringBuilder builder = new StringBuilder(queryLength); builder.Append(_ofTypeProlog); builder.Append(queryText); builder.Append(_ofTypeInfix); if (newType.NamespaceName != string.Empty) { builder.Append(newType.NamespaceName); builder.Append(_ofTypeInfix2); } builder.Append(newType.Name); builder.Append(_ofTypeEpilog); // Create a new EntitySqlQueryImplementation that uses the new query as its command text. // Span is carried over, no adjustment is needed return NewBuilderQuery(query, clrOfType, builder, query.Span, ObjectParameterCollection.DeepCopy(query.Parameters)); } #endregion #region OrderBy private const string _orderByOp = @" ORDER BY "; internal static ObjectQueryState OrderBy(ObjectQueryState query, string alias, string keys, ObjectParameter[] parameters) { return BuildOrderByOrWhere(query, alias, keys, parameters, _orderByOp, null, true); } #endregion #region Select private const string _selectOp = "SELECT "; internal static ObjectQueryState Select(ObjectQueryState query, string alias, string projection, ObjectParameter[] parameters) { return BuildSelectOrSelectValue(query, alias, projection, parameters, _selectOp, typeof(DbDataRecord)); } #endregion #region SelectValue private const string _selectValueOp = "SELECT VALUE "; internal static ObjectQueryState SelectValue(ObjectQueryState query, string alias, string projection, ObjectParameter[] parameters, Type projectedType) { return BuildSelectOrSelectValue(query, alias, projection, parameters, _selectValueOp, projectedType); } #endregion #region Skip private const string _skipOp = @" SKIP "; internal static ObjectQueryState Skip(ObjectQueryState query, string alias, string keys, string count, ObjectParameter[] parameters) { Debug.Assert(!StringUtil.IsNullOrEmptyOrWhiteSpace(count), "Invalid skip count"); return BuildOrderByOrWhere(query, alias, keys, parameters, _orderByOp, count, true); } #endregion #region Top private const string _limitOp = @" LIMIT "; private const string _topOp = @"SELECT VALUE TOP( "; private const string _topInfix = @" ) "; internal static ObjectQueryState Top(ObjectQueryState query, string alias, string count, ObjectParameter[] parameters) { int queryLength = count.Length; string queryText = GetCommandText(query); bool limitAllowed = ((EntitySqlQueryState)query).AllowsLimitSubclause; if (limitAllowed) { // Build the new query string: // <this query> LIMIT <count> queryLength += (queryText.Length + _limitOp.Length // + count.Length is added above ); } else { // Build the new query string: // "SELECT VALUE TOP(<count>) <alias> FROM (<this query>) AS <alias>" queryLength += (_topOp.Length + // count.Length + is added above _topInfix.Length + alias.Length + _fromOp.Length + queryText.Length + _asOp.Length + alias.Length); } StringBuilder builder = new StringBuilder(queryLength); if (limitAllowed) { builder.Append(queryText); builder.Append(_limitOp); builder.Append(count); } else { builder.Append(_topOp); builder.Append(count); builder.Append(_topInfix); builder.Append(alias); builder.Append(_fromOp); builder.Append(queryText); builder.Append(_asOp); builder.Append(alias); } // Create a new EntitySqlQueryImplementation that uses the new query as its command text. // Span is carried over, no adjustment is needed. return NewBuilderQuery(query, query.ElementType, builder, query.Span, MergeParameters(query.ObjectContext, query.Parameters, parameters)); } #endregion #region Union private const string _unionOp = @" ) UNION ( "; internal static ObjectQueryState Union(ObjectQueryState leftQuery, ObjectQueryState rightQuery) { // Ensure the Spans of the query arguments are merged into the new query's Span. Span newSpan = Span.CopyUnion(leftQuery.Span, rightQuery.Span); // Call the SetOp helper. return BuildSetOp(leftQuery, rightQuery, newSpan, _unionOp); } #endregion #region Union private const string _unionAllOp = @" ) UNION ALL ( "; internal static ObjectQueryState UnionAll(ObjectQueryState leftQuery, ObjectQueryState rightQuery) { // Ensure the Spans of the query arguments are merged into the new query's Span. Span newSpan = Span.CopyUnion(leftQuery.Span, rightQuery.Span); // Call the SetOp helper. return BuildSetOp(leftQuery, rightQuery, newSpan, _unionAllOp); } #endregion #region Where private const string _whereOp = @" WHERE "; internal static ObjectQueryState Where(ObjectQueryState query, string alias, string predicate, ObjectParameter[] parameters) { return BuildOrderByOrWhere(query, alias, predicate, parameters, _whereOp, null, false); } #endregion } }
using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * an implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first * * The slowest version uses no static tables at all and computes the values * in each round. * </p> * <p> * This file contains the slowest performance version with no static tables * for round precomputation, but it has the smallest foot print. * </p> */ public class AesLightEngine : IBlockCipher { // The S box private static readonly byte[] S = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, }; // The inverse S-box private static readonly byte[] Si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static readonly byte[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; private uint Shift( uint r, int shift) { return (r >> shift) | (r << (32 - shift)); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private const uint m1 = 0x80808080; private const uint m2 = 0x7f7f7f7f; private const uint m3 = 0x0000001b; private uint FFmulX( uint x) { return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private uint Mcol( uint x) { uint f2 = FFmulX(x); return f2 ^ Shift(x ^ f2, 8) ^ Shift(x, 16) ^ Shift(x, 24); } private uint Inv_Mcol( uint x) { uint f2 = FFmulX(x); uint f4 = FFmulX(f2); uint f8 = FFmulX(f4); uint f9 = x ^ f8; return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24); } private uint SubWord( uint x) { return (uint)S[x&255] | (((uint)S[(x>>8)&255]) << 8) | (((uint)S[(x>>16)&255]) << 16) | (((uint)S[(x>>24)&255]) << 24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private uint[,] GenerateWorkingKey( byte[] key, bool forEncryption) { int KC = key.Length / 4; // key length in words int t; if ((KC != 4) && (KC != 6) && (KC != 8)) throw new ArgumentException("Key length not 128/192/256 bits."); ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes uint[,] W = new uint[ROUNDS+1,4]; // 4 words in a block // // copy the key into the round key array // t = 0; for (int i = 0; i < key.Length; t++) { W[t >> 2, t & 3] = Pack.LE_To_UInt32(key, i); i+=4; } // // while not enough round key material calculated // calculate new values // int k = (ROUNDS + 1) << 2; for (int i = KC; (i < k); i++) { uint temp = W[(i-1)>>2,(i-1)&3]; if ((i % KC) == 0) { temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1]; } else if ((KC > 6) && ((i % KC) == 4)) { temp = SubWord(temp); } W[i>>2,i&3] = W[(i - KC)>>2,(i-KC)&3] ^ temp; } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { for (int i = 0; i < 4; i++) { W[j,i] = Inv_Mcol(W[j,i]); } } } return W; } private int ROUNDS; private uint[,] WorkingKey; private uint C0, C1, C2, C3; private bool forEncryption; private const int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AesLightEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().ToString()); WorkingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey(), forEncryption); this.forEncryption = forEncryption; } public string AlgorithmName { get { return "AES"; } } public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { return BLOCK_SIZE; } public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (WorkingKey == null) { throw new InvalidOperationException("AES engine not initialised"); } if ((inOff + (32 / 2)) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (32 / 2)) > output.Length) { throw new DataLengthException("output buffer too short"); } if (forEncryption) { UnPackBlock(input, inOff); EncryptBlock(WorkingKey); PackBlock(output, outOff); } else { UnPackBlock(input, inOff); DecryptBlock(WorkingKey); PackBlock(output, outOff); } return BLOCK_SIZE; } public void Reset() { } private void UnPackBlock( byte[] bytes, int off) { C0 = Pack.LE_To_UInt32(bytes, off); C1 = Pack.LE_To_UInt32(bytes, off + 4); C2 = Pack.LE_To_UInt32(bytes, off + 8); C3 = Pack.LE_To_UInt32(bytes, off + 12); } private void PackBlock( byte[] bytes, int off) { Pack.UInt32_To_LE(C0, bytes, off); Pack.UInt32_To_LE(C1, bytes, off + 4); Pack.UInt32_To_LE(C2, bytes, off + 8); Pack.UInt32_To_LE(C3, bytes, off + 12); } private void EncryptBlock( uint[,] KW) { int r; uint r0, r1, r2, r3; C0 ^= KW[0,0]; C1 ^= KW[0,1]; C2 ^= KW[0,2]; C3 ^= KW[0,3]; for (r = 1; r < ROUNDS - 1;) { r0 = Mcol((uint)S[C0&255] ^ (((uint)S[(C1>>8)&255])<<8) ^ (((uint)S[(C2>>16)&255])<<16) ^ (((uint)S[(C3>>24)&255])<<24)) ^ KW[r,0]; r1 = Mcol((uint)S[C1&255] ^ (((uint)S[(C2>>8)&255])<<8) ^ (((uint)S[(C3>>16)&255])<<16) ^ (((uint)S[(C0>>24)&255])<<24)) ^ KW[r,1]; r2 = Mcol((uint)S[C2&255] ^ (((uint)S[(C3>>8)&255])<<8) ^ (((uint)S[(C0>>16)&255])<<16) ^ (((uint)S[(C1>>24)&255])<<24)) ^ KW[r,2]; r3 = Mcol((uint)S[C3&255] ^ (((uint)S[(C0>>8)&255])<<8) ^ (((uint)S[(C1>>16)&255])<<16) ^ (((uint)S[(C2>>24)&255])<<24)) ^ KW[r++,3]; C0 = Mcol((uint)S[r0&255] ^ (((uint)S[(r1>>8)&255])<<8) ^ (((uint)S[(r2>>16)&255])<<16) ^ (((uint)S[(r3>>24)&255])<<24)) ^ KW[r,0]; C1 = Mcol((uint)S[r1&255] ^ (((uint)S[(r2>>8)&255])<<8) ^ (((uint)S[(r3>>16)&255])<<16) ^ (((uint)S[(r0>>24)&255])<<24)) ^ KW[r,1]; C2 = Mcol((uint)S[r2&255] ^ (((uint)S[(r3>>8)&255])<<8) ^ (((uint)S[(r0>>16)&255])<<16) ^ (((uint)S[(r1>>24)&255])<<24)) ^ KW[r,2]; C3 = Mcol((uint)S[r3&255] ^ (((uint)S[(r0>>8)&255])<<8) ^ (((uint)S[(r1>>16)&255])<<16) ^ (((uint)S[(r2>>24)&255])<<24)) ^ KW[r++,3]; } r0 = Mcol((uint)S[C0&255] ^ (((uint)S[(C1>>8)&255])<<8) ^ (((uint)S[(C2>>16)&255])<<16) ^ (((uint)S[(C3>>24)&255])<<24)) ^ KW[r,0]; r1 = Mcol((uint)S[C1&255] ^ (((uint)S[(C2>>8)&255])<<8) ^ (((uint)S[(C3>>16)&255])<<16) ^ (((uint)S[(C0>>24)&255])<<24)) ^ KW[r,1]; r2 = Mcol((uint)S[C2&255] ^ (((uint)S[(C3>>8)&255])<<8) ^ (((uint)S[(C0>>16)&255])<<16) ^ (((uint)S[(C1>>24)&255])<<24)) ^ KW[r,2]; r3 = Mcol((uint)S[C3&255] ^ (((uint)S[(C0>>8)&255])<<8) ^ (((uint)S[(C1>>16)&255])<<16) ^ (((uint)S[(C2>>24)&255])<<24)) ^ KW[r++,3]; // the final round is a simple function of S C0 = (uint)S[r0&255] ^ (((uint)S[(r1>>8)&255])<<8) ^ (((uint)S[(r2>>16)&255])<<16) ^ (((uint)S[(r3>>24)&255])<<24) ^ KW[r,0]; C1 = (uint)S[r1&255] ^ (((uint)S[(r2>>8)&255])<<8) ^ (((uint)S[(r3>>16)&255])<<16) ^ (((uint)S[(r0>>24)&255])<<24) ^ KW[r,1]; C2 = (uint)S[r2&255] ^ (((uint)S[(r3>>8)&255])<<8) ^ (((uint)S[(r0>>16)&255])<<16) ^ (((uint)S[(r1>>24)&255])<<24) ^ KW[r,2]; C3 = (uint)S[r3&255] ^ (((uint)S[(r0>>8)&255])<<8) ^ (((uint)S[(r1>>16)&255])<<16) ^ (((uint)S[(r2>>24)&255])<<24) ^ KW[r,3]; } private void DecryptBlock( uint[,] KW) { int r; uint r0, r1, r2, r3; C0 ^= KW[ROUNDS,0]; C1 ^= KW[ROUNDS,1]; C2 ^= KW[ROUNDS,2]; C3 ^= KW[ROUNDS,3]; for (r = ROUNDS-1; r>1;) { r0 = Inv_Mcol((uint)Si[C0&255] ^ (((uint)Si[(C3>>8)&255])<<8) ^ (((uint)Si[(C2>>16)&255])<<16) ^ ((uint)Si[(C1>>24)&255]<<24)) ^ KW[r,0]; r1 = Inv_Mcol((uint)Si[C1&255] ^ (((uint)Si[(C0>>8)&255])<<8) ^ (((uint)Si[(C3>>16)&255])<<16) ^ ((uint)Si[(C2>>24)&255]<<24)) ^ KW[r,1]; r2 = Inv_Mcol((uint)Si[C2&255] ^ (((uint)Si[(C1>>8)&255])<<8) ^ (((uint)Si[(C0>>16)&255])<<16) ^ ((uint)Si[(C3>>24)&255]<<24)) ^ KW[r,2]; r3 = Inv_Mcol((uint)Si[C3&255] ^ (((uint)Si[(C2>>8)&255])<<8) ^ (((uint)Si[(C1>>16)&255])<<16) ^ ((uint)Si[(C0>>24)&255]<<24)) ^ KW[r--,3]; C0 = Inv_Mcol((uint)Si[r0&255] ^ (((uint)Si[(r3>>8)&255])<<8) ^ (((uint)Si[(r2>>16)&255])<<16) ^ ((uint)Si[(r1>>24)&255]<<24)) ^ KW[r,0]; C1 = Inv_Mcol((uint)Si[r1&255] ^ (((uint)Si[(r0>>8)&255])<<8) ^ (((uint)Si[(r3>>16)&255])<<16) ^ ((uint)Si[(r2>>24)&255]<<24)) ^ KW[r,1]; C2 = Inv_Mcol((uint)Si[r2&255] ^ (((uint)Si[(r1>>8)&255])<<8) ^ (((uint)Si[(r0>>16)&255])<<16) ^ ((uint)Si[(r3>>24)&255]<<24)) ^ KW[r,2]; C3 = Inv_Mcol((uint)Si[r3&255] ^ (((uint)Si[(r2>>8)&255])<<8) ^ (((uint)Si[(r1>>16)&255])<<16) ^ ((uint)Si[(r0>>24)&255]<<24)) ^ KW[r--,3]; } r0 = Inv_Mcol((uint)Si[C0&255] ^ (((uint)Si[(C3>>8)&255])<<8) ^ (((uint)Si[(C2>>16)&255])<<16) ^ ((uint)Si[(C1>>24)&255]<<24)) ^ KW[r,0]; r1 = Inv_Mcol((uint)Si[C1&255] ^ (((uint)Si[(C0>>8)&255])<<8) ^ (((uint)Si[(C3>>16)&255])<<16) ^ ((uint)Si[(C2>>24)&255]<<24)) ^ KW[r,1]; r2 = Inv_Mcol((uint)Si[C2&255] ^ (((uint)Si[(C1>>8)&255])<<8) ^ (((uint)Si[(C0>>16)&255])<<16) ^ ((uint)Si[(C3>>24)&255]<<24)) ^ KW[r,2]; r3 = Inv_Mcol((uint)Si[C3&255] ^ (((uint)Si[(C2>>8)&255])<<8) ^ (((uint)Si[(C1>>16)&255])<<16) ^ ((uint)Si[(C0>>24)&255]<<24)) ^ KW[r,3]; // the final round's table is a simple function of Si C0 = (uint)Si[r0&255] ^ (((uint)Si[(r3>>8)&255])<<8) ^ (((uint)Si[(r2>>16)&255])<<16) ^ (((uint)Si[(r1>>24)&255])<<24) ^ KW[0,0]; C1 = (uint)Si[r1&255] ^ (((uint)Si[(r0>>8)&255])<<8) ^ (((uint)Si[(r3>>16)&255])<<16) ^ (((uint)Si[(r2>>24)&255])<<24) ^ KW[0,1]; C2 = (uint)Si[r2&255] ^ (((uint)Si[(r1>>8)&255])<<8) ^ (((uint)Si[(r0>>16)&255])<<16) ^ (((uint)Si[(r3>>24)&255])<<24) ^ KW[0,2]; C3 = (uint)Si[r3&255] ^ (((uint)Si[(r2>>8)&255])<<8) ^ (((uint)Si[(r1>>16)&255])<<16) ^ (((uint)Si[(r0>>24)&255])<<24) ^ KW[0,3]; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.DataPipeline; using Amazon.DataPipeline.Model; namespace Amazon.DataPipeline { /// <summary> /// Interface for accessing AmazonDataPipeline. /// /// <para> This is the <i>AWS Data Pipeline API Reference</i> . This guide provides descriptions and samples of the AWS Data Pipeline API. /// </para> <para> AWS Data Pipeline is a web service that configures and manages a data-driven workflow called a pipeline. AWS Data Pipeline /// handles the details of scheduling and ensuring that data dependencies are met so your application can focus on processing the data.</para> /// <para> The AWS Data Pipeline API implements two main sets of functionality. The first set of actions configure the pipeline in the web /// service. You call these actions to create a pipeline and define data sources, schedules, dependencies, and the transforms to be performed on /// the data. </para> <para> The second set of actions are used by a task runner application that calls the AWS Data Pipeline API to receive the /// next task ready for processing. The logic for performing the task, such as querying the data, running data analysis, or converting the data /// from one format to another, is contained within the task runner. The task runner performs the task assigned to it by the web service, /// reporting progress to the web service as it does so. When the task is done, the task runner reports the final success or failure of the task /// to the web service. </para> <para> AWS Data Pipeline provides an open-source implementation of a task runner called AWS Data Pipeline Task /// Runner. AWS Data Pipeline Task Runner provides logic for common data management scenarios, such as performing database queries and running /// data analysis using Amazon Elastic MapReduce (Amazon EMR). You can use AWS Data Pipeline Task Runner as your task runner, or you can write /// your own task runner to provide custom data management. </para> <para> The AWS Data Pipeline API uses the Signature Version 4 protocol for /// signing requests. For more information about how to sign a request with this protocol, see Signature Version 4 Signing Process. In the code /// examples in this reference, the Signature Version 4 Request parameters are represented as AuthParams. </para> /// </summary> public interface AmazonDataPipeline : IDisposable { #region ActivatePipeline /// <summary> /// <para> Validates a pipeline and initiates processing. If the pipeline does not pass validation, activation fails. </para> <para> Call this /// action to start processing pipeline tasks of a pipeline you've created using the CreatePipeline and PutPipelineDefinition actions. A /// pipeline cannot be modified after it has been successfully activated. </para> /// </summary> /// /// <param name="activatePipelineRequest">Container for the necessary parameters to execute the ActivatePipeline service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the ActivatePipeline service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> ActivatePipelineResponse ActivatePipeline(ActivatePipelineRequest activatePipelineRequest); /// <summary> /// Initiates the asynchronous execution of the ActivatePipeline operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ActivatePipeline"/> /// </summary> /// /// <param name="activatePipelineRequest">Container for the necessary parameters to execute the ActivatePipeline operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndActivatePipeline /// operation.</returns> IAsyncResult BeginActivatePipeline(ActivatePipelineRequest activatePipelineRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ActivatePipeline operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ActivatePipeline"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginActivatePipeline.</param> /// /// <returns>Returns a ActivatePipelineResult from AmazonDataPipeline.</returns> ActivatePipelineResponse EndActivatePipeline(IAsyncResult asyncResult); #endregion #region ListPipelines /// <summary> /// <para>Returns a list of pipeline identifiers for all active pipelines. Identifiers are returned only for pipelines you have permission to /// access. </para> /// </summary> /// /// <param name="listPipelinesRequest">Container for the necessary parameters to execute the ListPipelines service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the ListPipelines service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> ListPipelinesResponse ListPipelines(ListPipelinesRequest listPipelinesRequest); /// <summary> /// Initiates the asynchronous execution of the ListPipelines operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ListPipelines"/> /// </summary> /// /// <param name="listPipelinesRequest">Container for the necessary parameters to execute the ListPipelines operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListPipelines /// operation.</returns> IAsyncResult BeginListPipelines(ListPipelinesRequest listPipelinesRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListPipelines operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ListPipelines"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListPipelines.</param> /// /// <returns>Returns a ListPipelinesResult from AmazonDataPipeline.</returns> ListPipelinesResponse EndListPipelines(IAsyncResult asyncResult); /// <summary> /// <para>Returns a list of pipeline identifiers for all active pipelines. Identifiers are returned only for pipelines you have permission to /// access. </para> /// </summary> /// /// <returns>The response from the ListPipelines service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> ListPipelinesResponse ListPipelines(); #endregion #region ReportTaskProgress /// <summary> /// <para> Updates the AWS Data Pipeline service on the progress of the calling task runner. When the task runner is assigned a task, it should /// call ReportTaskProgress to acknowledge that it has the task within 2 minutes. If the web service does not recieve this acknowledgement /// within the 2 minute window, it will assign the task in a subsequent PollForTask call. After this initial acknowledgement, the task runner /// only needs to report progress every 15 minutes to maintain its ownership of the task. You can change this reporting time from 15 minutes by /// specifying a <c>reportProgressTimeout</c> field in your pipeline. If a task runner does not report its status after 5 minutes, AWS Data /// Pipeline will assume that the task runner is unable to process the task and will reassign the task in a subsequent response to PollForTask. /// task runners should call ReportTaskProgress every 60 seconds. </para> /// </summary> /// /// <param name="reportTaskProgressRequest">Container for the necessary parameters to execute the ReportTaskProgress service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the ReportTaskProgress service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="TaskNotFoundException"/> /// <exception cref="PipelineDeletedException"/> ReportTaskProgressResponse ReportTaskProgress(ReportTaskProgressRequest reportTaskProgressRequest); /// <summary> /// Initiates the asynchronous execution of the ReportTaskProgress operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ReportTaskProgress"/> /// </summary> /// /// <param name="reportTaskProgressRequest">Container for the necessary parameters to execute the ReportTaskProgress operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndReportTaskProgress operation.</returns> IAsyncResult BeginReportTaskProgress(ReportTaskProgressRequest reportTaskProgressRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ReportTaskProgress operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ReportTaskProgress"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginReportTaskProgress.</param> /// /// <returns>Returns a ReportTaskProgressResult from AmazonDataPipeline.</returns> ReportTaskProgressResponse EndReportTaskProgress(IAsyncResult asyncResult); #endregion #region ValidatePipelineDefinition /// <summary> /// <para>Tests the pipeline definition with a set of validation checks to ensure that it is well formed and can run without error. </para> /// </summary> /// /// <param name="validatePipelineDefinitionRequest">Container for the necessary parameters to execute the ValidatePipelineDefinition service /// method on AmazonDataPipeline.</param> /// /// <returns>The response from the ValidatePipelineDefinition service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> ValidatePipelineDefinitionResponse ValidatePipelineDefinition(ValidatePipelineDefinitionRequest validatePipelineDefinitionRequest); /// <summary> /// Initiates the asynchronous execution of the ValidatePipelineDefinition operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ValidatePipelineDefinition"/> /// </summary> /// /// <param name="validatePipelineDefinitionRequest">Container for the necessary parameters to execute the ValidatePipelineDefinition operation /// on AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndValidatePipelineDefinition operation.</returns> IAsyncResult BeginValidatePipelineDefinition(ValidatePipelineDefinitionRequest validatePipelineDefinitionRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ValidatePipelineDefinition operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ValidatePipelineDefinition"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginValidatePipelineDefinition.</param> /// /// <returns>Returns a ValidatePipelineDefinitionResult from AmazonDataPipeline.</returns> ValidatePipelineDefinitionResponse EndValidatePipelineDefinition(IAsyncResult asyncResult); #endregion #region PollForTask /// <summary> /// <para> Task runners call this action to receive a task to perform from AWS Data Pipeline. The task runner specifies which tasks it can /// perform by setting a value for the workerGroup parameter of the PollForTask call. The task returned by PollForTask may come from any of the /// pipelines that match the workerGroup value passed in by the task runner and that was launched using the IAM user credentials specified by /// the task runner. </para> <para> If tasks are ready in the work queue, PollForTask returns a response immediately. If no tasks are available /// in the queue, PollForTask uses long-polling and holds on to a poll connection for up to a 90 seconds during which time the first newly /// scheduled task is handed to the task runner. To accomodate this, set the socket timeout in your task runner to 90 seconds. The task runner /// should not call PollForTask again on the same <c>workerGroup</c> until it receives a response, and this may take up to 90 seconds. </para> /// </summary> /// /// <param name="pollForTaskRequest">Container for the necessary parameters to execute the PollForTask service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the PollForTask service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="TaskNotFoundException"/> PollForTaskResponse PollForTask(PollForTaskRequest pollForTaskRequest); /// <summary> /// Initiates the asynchronous execution of the PollForTask operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.PollForTask"/> /// </summary> /// /// <param name="pollForTaskRequest">Container for the necessary parameters to execute the PollForTask operation on AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPollForTask /// operation.</returns> IAsyncResult BeginPollForTask(PollForTaskRequest pollForTaskRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the PollForTask operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.PollForTask"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPollForTask.</param> /// /// <returns>Returns a PollForTaskResult from AmazonDataPipeline.</returns> PollForTaskResponse EndPollForTask(IAsyncResult asyncResult); #endregion #region QueryObjects /// <summary> /// <para>Queries a pipeline for the names of objects that match a specified set of conditions.</para> <para>The objects returned by /// QueryObjects are paginated and then filtered by the value you set for query. This means the action may return an empty result set with a /// value set for marker. If <c>HasMoreResults</c> is set to <c>True</c> , you should continue to call QueryObjects, passing in the returned /// value for marker, until <c>HasMoreResults</c> returns <c>False</c> .</para> /// </summary> /// /// <param name="queryObjectsRequest">Container for the necessary parameters to execute the QueryObjects service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the QueryObjects service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> QueryObjectsResponse QueryObjects(QueryObjectsRequest queryObjectsRequest); /// <summary> /// Initiates the asynchronous execution of the QueryObjects operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.QueryObjects"/> /// </summary> /// /// <param name="queryObjectsRequest">Container for the necessary parameters to execute the QueryObjects operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndQueryObjects /// operation.</returns> IAsyncResult BeginQueryObjects(QueryObjectsRequest queryObjectsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the QueryObjects operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.QueryObjects"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginQueryObjects.</param> /// /// <returns>Returns a QueryObjectsResult from AmazonDataPipeline.</returns> QueryObjectsResponse EndQueryObjects(IAsyncResult asyncResult); #endregion #region SetStatus /// <summary> /// <para>Requests that the status of an array of physical or logical pipeline objects be updated in the pipeline. This update may not occur /// immediately, but is eventually consistent. The status that can be set depends on the type of object.</para> /// </summary> /// /// <param name="setStatusRequest">Container for the necessary parameters to execute the SetStatus service method on AmazonDataPipeline.</param> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> SetStatusResponse SetStatus(SetStatusRequest setStatusRequest); /// <summary> /// Initiates the asynchronous execution of the SetStatus operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.SetStatus"/> /// </summary> /// /// <param name="setStatusRequest">Container for the necessary parameters to execute the SetStatus operation on AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginSetStatus(SetStatusRequest setStatusRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the SetStatus operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.SetStatus"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetStatus.</param> SetStatusResponse EndSetStatus(IAsyncResult asyncResult); #endregion #region DeletePipeline /// <summary> /// <para> Permanently deletes a pipeline, its pipeline definition and its run history. You cannot query or restore a deleted pipeline. AWS Data /// Pipeline will attempt to cancel instances associated with the pipeline that are currently being processed by task runners. Deleting a /// pipeline cannot be undone. </para> <para> To temporarily pause a pipeline instead of deleting it, call SetStatus with the status set to /// Pause on individual components. Components that are paused by SetStatus can be resumed. </para> /// </summary> /// /// <param name="deletePipelineRequest">Container for the necessary parameters to execute the DeletePipeline service method on /// AmazonDataPipeline.</param> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> DeletePipelineResponse DeletePipeline(DeletePipelineRequest deletePipelineRequest); /// <summary> /// Initiates the asynchronous execution of the DeletePipeline operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.DeletePipeline"/> /// </summary> /// /// <param name="deletePipelineRequest">Container for the necessary parameters to execute the DeletePipeline operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginDeletePipeline(DeletePipelineRequest deletePipelineRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeletePipeline operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.DeletePipeline"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeletePipeline.</param> DeletePipelineResponse EndDeletePipeline(IAsyncResult asyncResult); #endregion #region GetPipelineDefinition /// <summary> /// <para>Returns the definition of the specified pipeline. You can call GetPipelineDefinition to retrieve the pipeline definition you provided /// using PutPipelineDefinition.</para> /// </summary> /// /// <param name="getPipelineDefinitionRequest">Container for the necessary parameters to execute the GetPipelineDefinition service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the GetPipelineDefinition service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> GetPipelineDefinitionResponse GetPipelineDefinition(GetPipelineDefinitionRequest getPipelineDefinitionRequest); /// <summary> /// Initiates the asynchronous execution of the GetPipelineDefinition operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.GetPipelineDefinition"/> /// </summary> /// /// <param name="getPipelineDefinitionRequest">Container for the necessary parameters to execute the GetPipelineDefinition operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndGetPipelineDefinition operation.</returns> IAsyncResult BeginGetPipelineDefinition(GetPipelineDefinitionRequest getPipelineDefinitionRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetPipelineDefinition operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.GetPipelineDefinition"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetPipelineDefinition.</param> /// /// <returns>Returns a GetPipelineDefinitionResult from AmazonDataPipeline.</returns> GetPipelineDefinitionResponse EndGetPipelineDefinition(IAsyncResult asyncResult); #endregion #region SetTaskStatus /// <summary> /// <para> Notifies AWS Data Pipeline that a task is completed and provides information about the final status. The task runner calls this /// action regardless of whether the task was sucessful. The task runner does not need to call SetTaskStatus for tasks that are canceled by the /// web service during a call to ReportTaskProgress. </para> /// </summary> /// /// <param name="setTaskStatusRequest">Container for the necessary parameters to execute the SetTaskStatus service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the SetTaskStatus service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="TaskNotFoundException"/> /// <exception cref="PipelineDeletedException"/> SetTaskStatusResponse SetTaskStatus(SetTaskStatusRequest setTaskStatusRequest); /// <summary> /// Initiates the asynchronous execution of the SetTaskStatus operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.SetTaskStatus"/> /// </summary> /// /// <param name="setTaskStatusRequest">Container for the necessary parameters to execute the SetTaskStatus operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSetTaskStatus /// operation.</returns> IAsyncResult BeginSetTaskStatus(SetTaskStatusRequest setTaskStatusRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the SetTaskStatus operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.SetTaskStatus"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetTaskStatus.</param> /// /// <returns>Returns a SetTaskStatusResult from AmazonDataPipeline.</returns> SetTaskStatusResponse EndSetTaskStatus(IAsyncResult asyncResult); #endregion #region EvaluateExpression /// <summary> /// <para>Evaluates a string in the context of a specified object. A task runner can use this action to evaluate SQL queries stored in Amazon /// S3. </para> /// </summary> /// /// <param name="evaluateExpressionRequest">Container for the necessary parameters to execute the EvaluateExpression service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the EvaluateExpression service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="TaskNotFoundException"/> /// <exception cref="PipelineDeletedException"/> EvaluateExpressionResponse EvaluateExpression(EvaluateExpressionRequest evaluateExpressionRequest); /// <summary> /// Initiates the asynchronous execution of the EvaluateExpression operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.EvaluateExpression"/> /// </summary> /// /// <param name="evaluateExpressionRequest">Container for the necessary parameters to execute the EvaluateExpression operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndEvaluateExpression operation.</returns> IAsyncResult BeginEvaluateExpression(EvaluateExpressionRequest evaluateExpressionRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the EvaluateExpression operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.EvaluateExpression"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginEvaluateExpression.</param> /// /// <returns>Returns a EvaluateExpressionResult from AmazonDataPipeline.</returns> EvaluateExpressionResponse EndEvaluateExpression(IAsyncResult asyncResult); #endregion #region DescribePipelines /// <summary> /// <para> Retrieve metadata about one or more pipelines. The information retrieved includes the name of the pipeline, the pipeline identifier, /// its current state, and the user account that owns the pipeline. Using account credentials, you can retrieve metadata about pipelines that /// you or your IAM users have created. If you are using an IAM user account, you can retrieve metadata about only those pipelines you have read /// permission for. </para> <para> To retrieve the full pipeline definition instead of metadata about the pipeline, call the /// GetPipelineDefinition action. </para> /// </summary> /// /// <param name="describePipelinesRequest">Container for the necessary parameters to execute the DescribePipelines service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the DescribePipelines service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> DescribePipelinesResponse DescribePipelines(DescribePipelinesRequest describePipelinesRequest); /// <summary> /// Initiates the asynchronous execution of the DescribePipelines operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.DescribePipelines"/> /// </summary> /// /// <param name="describePipelinesRequest">Container for the necessary parameters to execute the DescribePipelines operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribePipelines /// operation.</returns> IAsyncResult BeginDescribePipelines(DescribePipelinesRequest describePipelinesRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribePipelines operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.DescribePipelines"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribePipelines.</param> /// /// <returns>Returns a DescribePipelinesResult from AmazonDataPipeline.</returns> DescribePipelinesResponse EndDescribePipelines(IAsyncResult asyncResult); #endregion #region CreatePipeline /// <summary> /// <para>Creates a new empty pipeline. When this action succeeds, you can then use the PutPipelineDefinition action to populate the /// pipeline.</para> /// </summary> /// /// <param name="createPipelineRequest">Container for the necessary parameters to execute the CreatePipeline service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the CreatePipeline service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> CreatePipelineResponse CreatePipeline(CreatePipelineRequest createPipelineRequest); /// <summary> /// Initiates the asynchronous execution of the CreatePipeline operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.CreatePipeline"/> /// </summary> /// /// <param name="createPipelineRequest">Container for the necessary parameters to execute the CreatePipeline operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreatePipeline /// operation.</returns> IAsyncResult BeginCreatePipeline(CreatePipelineRequest createPipelineRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreatePipeline operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.CreatePipeline"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreatePipeline.</param> /// /// <returns>Returns a CreatePipelineResult from AmazonDataPipeline.</returns> CreatePipelineResponse EndCreatePipeline(IAsyncResult asyncResult); #endregion #region DescribeObjects /// <summary> /// <para> Returns the object definitions for a set of objects associated with the pipeline. Object definitions are composed of a set of fields /// that define the properties of the object. </para> /// </summary> /// /// <param name="describeObjectsRequest">Container for the necessary parameters to execute the DescribeObjects service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the DescribeObjects service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> DescribeObjectsResponse DescribeObjects(DescribeObjectsRequest describeObjectsRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeObjects operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.DescribeObjects"/> /// </summary> /// /// <param name="describeObjectsRequest">Container for the necessary parameters to execute the DescribeObjects operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeObjects /// operation.</returns> IAsyncResult BeginDescribeObjects(DescribeObjectsRequest describeObjectsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeObjects operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.DescribeObjects"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeObjects.</param> /// /// <returns>Returns a DescribeObjectsResult from AmazonDataPipeline.</returns> DescribeObjectsResponse EndDescribeObjects(IAsyncResult asyncResult); #endregion #region ReportTaskRunnerHeartbeat /// <summary> /// <para>Task runners call ReportTaskRunnerHeartbeat every 15 minutes to indicate that they are operational. In the case of AWS Data Pipeline /// Task Runner launched on a resource managed by AWS Data Pipeline, the web service can use this call to detect when the task runner /// application has failed and restart a new instance.</para> /// </summary> /// /// <param name="reportTaskRunnerHeartbeatRequest">Container for the necessary parameters to execute the ReportTaskRunnerHeartbeat service /// method on AmazonDataPipeline.</param> /// /// <returns>The response from the ReportTaskRunnerHeartbeat service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> ReportTaskRunnerHeartbeatResponse ReportTaskRunnerHeartbeat(ReportTaskRunnerHeartbeatRequest reportTaskRunnerHeartbeatRequest); /// <summary> /// Initiates the asynchronous execution of the ReportTaskRunnerHeartbeat operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ReportTaskRunnerHeartbeat"/> /// </summary> /// /// <param name="reportTaskRunnerHeartbeatRequest">Container for the necessary parameters to execute the ReportTaskRunnerHeartbeat operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndReportTaskRunnerHeartbeat operation.</returns> IAsyncResult BeginReportTaskRunnerHeartbeat(ReportTaskRunnerHeartbeatRequest reportTaskRunnerHeartbeatRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ReportTaskRunnerHeartbeat operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.ReportTaskRunnerHeartbeat"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginReportTaskRunnerHeartbeat.</param> /// /// <returns>Returns a ReportTaskRunnerHeartbeatResult from AmazonDataPipeline.</returns> ReportTaskRunnerHeartbeatResponse EndReportTaskRunnerHeartbeat(IAsyncResult asyncResult); #endregion #region PutPipelineDefinition /// <summary> /// <para>Adds tasks, schedules, and preconditions that control the behavior of the pipeline. You can use PutPipelineDefinition to populate a /// new pipeline or to update an existing pipeline that has not yet been activated. </para> <para> PutPipelineDefinition also validates the /// configuration as it adds it to the pipeline. Changes to the pipeline are saved unless one of the following three validation errors exists in /// the pipeline. <ol> <li>An object is missing a name or identifier field.</li> /// <li>A string or reference field is empty.</li> /// <li>The number of objects in the pipeline exceeds the maximum allowed objects.</li> /// </ol> </para> <para> Pipeline object definitions are passed to the PutPipelineDefinition action and returned by the GetPipelineDefinition /// action. </para> /// </summary> /// /// <param name="putPipelineDefinitionRequest">Container for the necessary parameters to execute the PutPipelineDefinition service method on /// AmazonDataPipeline.</param> /// /// <returns>The response from the PutPipelineDefinition service method, as returned by AmazonDataPipeline.</returns> /// /// <exception cref="PipelineNotFoundException"/> /// <exception cref="InternalServiceErrorException"/> /// <exception cref="InvalidRequestException"/> /// <exception cref="PipelineDeletedException"/> PutPipelineDefinitionResponse PutPipelineDefinition(PutPipelineDefinitionRequest putPipelineDefinitionRequest); /// <summary> /// Initiates the asynchronous execution of the PutPipelineDefinition operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.PutPipelineDefinition"/> /// </summary> /// /// <param name="putPipelineDefinitionRequest">Container for the necessary parameters to execute the PutPipelineDefinition operation on /// AmazonDataPipeline.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndPutPipelineDefinition operation.</returns> IAsyncResult BeginPutPipelineDefinition(PutPipelineDefinitionRequest putPipelineDefinitionRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the PutPipelineDefinition operation. /// <seealso cref="Amazon.DataPipeline.AmazonDataPipeline.PutPipelineDefinition"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutPipelineDefinition.</param> /// /// <returns>Returns a PutPipelineDefinitionResult from AmazonDataPipeline.</returns> PutPipelineDefinitionResponse EndPutPipelineDefinition(IAsyncResult asyncResult); #endregion } }
namespace Petstore { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// The Storage Management Client. /// </summary> public partial class StorageManagementClient : Microsoft.Rest.ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IStorageAccountsOperations. /// </summary> public virtual IStorageAccountsOperations StorageAccounts { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.StorageAccounts = new StorageAccountsOperations(this); this.Usage = new UsageOperations(this); this.BaseUri = new System.Uri("https://management.azure.com"); this.ApiVersion = "2015-06-15"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
// * // * Copyright (C) 2008 Roger Alsing : http://www.RogerAlsing.com // * // * This library is free software; you can redistribute it and/or modify it // * under the terms of the GNU Lesser General Public License 2.1 or later, as // * published by the Free Software Foundation. See the included license.txt // * or http://www.gnu.org/copyleft/lesser.html for details. // * // * using System; using System.Diagnostics; using Alsing.SourceCode; namespace Alsing.Windows.Forms.SyntaxBox { /// <summary> /// Caret class used by the SyntaxBoxControl /// </summary> public sealed class Caret { /// <summary> /// Gets or Sets the position of the caret. /// </summary> public TextPoint Position { get { return _Position; } set { _Position = value; _Position.Change += PositionChange; OnChange(); } } /// <summary> /// Event fired when the carets position has changed. /// </summary> public event EventHandler Change = null; private void PositionChange(object s, EventArgs e) { OnChange(); } private void OnChange() { if (Change != null) Change(this, null); } #region General Declarations // X Position of the caret (in logical units (eg. 1 tab = 5 chars) private readonly EditViewControl Control; /// <summary> /// The Position of the caret in Chars (Column and Row index) /// </summary> private TextPoint _Position; /// <summary> /// Used by the painter to determine if the caret should be rendered or not /// </summary> public bool Blink; private int OldLogicalXPos; // to what control does the caret belong?? #endregion #region Constructor(s) /// <summary> /// Caret constructor /// </summary> /// <param name="control">The control that will use the caret</param> public Caret(EditViewControl control) { Position = new TextPoint(0, 0); Control = control; } #endregion #region Helpers private void RememberXPos() { OldLogicalXPos = LogicalPosition.X; } /// <summary> /// Confines the caret to a valid position within the active document /// </summary> public void CropPosition() { if (Position.X < 0) Position.X = 0; if (Position.Y >= Control.Document.Count) Position.Y = Control.Document.Count - 1; if (Position.Y < 0) Position.Y = 0; Row xtr = CurrentRow; if (Position.X > xtr.Text.Length && !Control.VirtualWhitespace) Position.X = xtr.Text.Length; } #endregion #region Movement Methods /// <summary> /// Moves the caret right one step. /// if the caret is placed at the last column of a row the caret will move down one row and be placed at the first column of that row. /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveRight(bool Select) { CropPosition(); Position.X++; if (CurrentRow.IsCollapsed) { if (Position.X > CurrentRow.Expansion_EndChar) { Position.Y = CurrentRow.Expansion_EndRow.Index; Position.X = CurrentRow.Expansion_EndRow.Expansion_StartChar; CropPosition(); } RememberXPos(); CaretMoved(Select); } else { Row xtr = CurrentRow; if (Position.X > xtr.Text.Length && !Control.VirtualWhitespace) { if (Position.Y < Control.Document.Count - 1) { MoveDown(Select); Position.X = 0; //this.Position.Y ++; CropPosition(); } else CropPosition(); } RememberXPos(); CaretMoved(Select); } } /// <summary> /// Moves the caret up one row. /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveUp(bool Select) { CropPosition(); int x = OldLogicalXPos; //error here try { if (CurrentRow != null && CurrentRow.PrevVisibleRow != null) { Position.Y = CurrentRow.PrevVisibleRow.Index; if (CurrentRow.IsCollapsed) { x = 0; } } } catch { } finally { CropPosition(); LogicalPosition = new TextPoint(x, Position.Y); CropPosition(); CaretMoved(Select); } } /// <summary> /// Moves the caret up x rows /// </summary> /// <param name="rows">Number of rows the caret should be moved up</param> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveUp(int rows, bool Select) { CropPosition(); int x = OldLogicalXPos; try { int pos = CurrentRow.VisibleIndex; pos -= rows; if (pos < 0) pos = 0; Row r = Control.Document.VisibleRows[pos]; pos = r.Index; Position.Y = pos; // for (int i=0;i<rows;i++) // { // this.Position.Y = this.CurrentRow.PrevVisibleRow.Index; // } if (CurrentRow.IsCollapsed) { x = 0; } } catch {} CropPosition(); LogicalPosition = new TextPoint(x, Position.Y); CropPosition(); CaretMoved(Select); } /// <summary> /// Moves the caret down x rows. /// </summary> /// <param name="rows">The number of rows the caret should be moved down</param> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveDown(int rows, bool Select) { int x = OldLogicalXPos; CropPosition(); //this.Position.Y +=rows; try { int pos = CurrentRow.VisibleIndex; pos += rows; if (pos > Control.Document.VisibleRows.Count - 1) pos = Control.Document.VisibleRows.Count - 1; Row r = Control.Document.VisibleRows[pos]; pos = r.Index; Position.Y = pos; // for (int i=0;i<rows;i++) // { // this.Position.Y = this.CurrentRow.NextVisibleRow.Index; // // } if (CurrentRow.IsCollapsed) { x = 0; } } catch {} finally { CropPosition(); LogicalPosition = new TextPoint(x, Position.Y); CropPosition(); CaretMoved(Select); } } /// <summary> /// Moves the caret down one row. /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveDown(bool Select) { CropPosition(); int x = OldLogicalXPos; //error here try { Row r = CurrentRow; Row r2 = r.NextVisibleRow; if (r2 == null) return; Position.Y = r2.Index; if (CurrentRow.IsCollapsed) { x = 0; } } catch {} finally { CropPosition(); LogicalPosition = new TextPoint(x, Position.Y); CropPosition(); CaretMoved(Select); } } /// <summary> /// Moves the caret left one step. /// if the caret is placed at the first column the caret will be moved up one line and placed at the last column of the row. /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveLeft(bool Select) { CropPosition(); Position.X--; if (CurrentRow.IsCollapsedEndPart) { if (Position.X < CurrentRow.Expansion_StartChar) { if (CurrentRow.Expansion_StartRow.Index == - 1) Debugger.Break(); Position.Y = CurrentRow.Expansion_StartRow.Index; Position.X = CurrentRow.Expansion_StartRow.Expansion_EndChar; CropPosition(); } RememberXPos(); CaretMoved(Select); } else { if (Position.X < 0) { if (Position.Y > 0) { MoveUp(Select); CropPosition(); Row xtr = CurrentRow; Position.X = xtr.Text.Length; if (CurrentRow.IsCollapsed) { Position.Y = CurrentRow.Expansion_EndRow.Index; Position.X = CurrentRow.Text.Length; } } else CropPosition(); } RememberXPos(); CaretMoved(Select); } } /// <summary> /// Moves the caret to the first non whitespace column at the active row /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveHome(bool Select) { CropPosition(); if (CurrentRow.IsCollapsedEndPart) { Position.Y = CurrentRow.Expansion_StartRow.Index; MoveHome(Select); } else { int i = CurrentRow.GetLeadingWhitespace().Length; Position.X = Position.X == i ? 0 : i; RememberXPos(); CaretMoved(Select); } } /// <summary> /// Moves the caret to the end of a row ignoring any whitespace characters at the end of the row /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveEnd(bool Select) { if (CurrentRow.IsCollapsed) { Position.Y = CurrentRow.Expansion_EndRow.Index; MoveEnd(Select); } else { CropPosition(); Row xtr = CurrentRow; Position.X = xtr.Text.Length; RememberXPos(); CaretMoved(Select); } } public void CaretMoved(bool Select) { Control.ScrollIntoView(); if (!Select) Control.Selection.ClearSelection(); else Control.Selection.MakeSelection(); } /// <summary> /// Moves the caret to the first column of the active row /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveAbsoluteHome(bool Select) { Position.X = 0; Position.Y = 0; RememberXPos(); CaretMoved(Select); } /// <summary> /// Moves the caret to the absolute end of the active row /// </summary> /// <param name="Select">True if a selection should be created from the current caret pos to the new pos</param> public void MoveAbsoluteEnd(bool Select) { Position.X = Control.Document[Control.Document.Count - 1].Text.Length; Position.Y = Control.Document.Count - 1; RememberXPos(); CaretMoved(Select); } #endregion #region Get Related info from Caret Position /// <summary> /// Gets the word that the caret is placed on. /// This only applies if the active row is fully parsed. /// </summary> /// <returns>a Word object from the active row</returns> public Word CurrentWord { get { return Control.Document.GetWordFromPos(Position); } } public Word PreviousWord { get { if (Position.X > 1) { TextPoint point = new TextPoint(Position.X - 2, Position.Y); return Control.Document.GetWordFromPos(point); } else { return null; } } } public Word GetWord(int countBefore) { Word word = CurrentWord; Row row = Control.Caret.CurrentRow; int index = row.words.IndexOf(word); if (index >= countBefore) { return row.words[index - countBefore]; } else { return null; } return CurrentWord; } public string GetWordText(int countBefore) { Word foundWord = GetWord(countBefore); if (foundWord == null) { return null; } else { return foundWord.Text; } } /// <summary> /// Returns the row that the caret is placed on /// </summary> /// <returns>a Row object from the active document</returns> public Row CurrentRow { get { return Control.Document[Position.Y]; } } /// <summary> /// Gets the word that the caret is placed on. /// This only applies if the active row is fully parsed. /// </summary> /// <returns>a Word object from the active row</returns> public Span CurrentSegment() { return Control.Document.GetSegmentFromPos(Position); } #endregion #region Set Position Methods/Props /// <summary> /// Gets or Sets the Logical position of the caret. /// </summary> public TextPoint LogicalPosition { get { if (Position.X < 0) return new TextPoint(0, Position.Y); Row xtr = CurrentRow; int x = 0; if (xtr == null) return new TextPoint(0, 0); int Padd = Math.Max(Position.X - xtr.Text.Length, 0); var PaddStr = new String(' ', Padd); string TotStr = xtr.Text + PaddStr; char[] buffer = TotStr.ToCharArray(0, Position.X); foreach (char c in buffer) { if (c == '\t') { x += Control.TabSize - (x%Control.TabSize); } else { x++; } } return new TextPoint(x, Position.Y); } set { Row xtr = CurrentRow; int x = 0; int xx = 0; if (value.X > 0) { char[] chars = xtr.Text.ToCharArray(); int i = 0; while (x < value.X) { char c = i < chars.Length ? chars[i] : ' '; xx++; if (c == '\t') { x += Control.TabSize - (x%Control.TabSize); } else { x++; } i++; } } Position.Y = value.Y; Position.X = xx; } } /// <summary> /// Sets the position of the caret /// </summary> /// <param name="pos">Point containing the new x and y positions</param> public void SetPos(TextPoint pos) { Position = pos; RememberXPos(); } #endregion } }
// Created by Paul Gonzalez Becerra using System; namespace Saserdote.DataSystems { public class FDictionary<T,K>:IFDictionary { #region --- Field Variables --- // Variables protected T[] pKeys; protected K[] pObjs; protected int lstIndex; #endregion // Field Variables #region --- Constructors --- public FDictionary() { pKeys= new T[0]; pObjs= new K[0]; lstIndex= -1; } #endregion // Constructors #region --- Properties --- // Gets and sets the object of the given index public K this[T index] { get { return pObjs[getIndex(index)]; } set { pObjs[getIndex(index)]= value; } } // Gets the keys of the dictionary public T[] keys { get { return pKeys; } } #endregion // Properties #region --- Inherited Properties --- // Gets the size of the list public int size { get { return pObjs.Length; } } #endregion // Inherited Properties #region --- Methods --- // Adds the two given values into the dictionary public bool add(T key, K value) { if(contains(key)) return false; // Variables T[] keyTemp= new T[size+1]; K[] objTemp= new K[size+1]; for(int i= 0; i< size; i++) { keyTemp[i]= pKeys[i]; objTemp[i]= pObjs[i]; } keyTemp[size]= key; objTemp[size]= value; pKeys= keyTemp; pObjs= objTemp; return true; } // Adds in an array of the two values into the dictionary public bool addRange(T[] pmKeys, K[] values) { if(pmKeys.Length!= values.Length) { Console.WriteLine("Lengths are not equal"); return false; } if(pmKeys.Length== 1) return add(pmKeys[0], values[0]); // Variables bool flag= false; for(int i= 0; i< pmKeys.Length; i++) { if(add(pmKeys[i], values[i])) flag= true; } return flag; } // Finds if the given key is inside the dictionary public bool contains(T key) { if(lstIndex!= -1) { if(key.Equals(keys[lstIndex])) return true; } for(int i= 0; i< size; i++) { if(pKeys[i].Equals(key)) return true; } return false; } // Gets the index of the given key public int getIndex(T key, int startIndex) { if(lstIndex!= -1) { if(key.Equals(keys[lstIndex])) return lstIndex; } for(int i= startIndex; i< size; i++) { if(pKeys[i].Equals(key)) return i; } return -1; } public int getIndex(T key) { return getIndex(key, 0); } // Inserts the two values into the dictionary public bool insert(T key, K value, int index) { if(index>= size) return add(key, value); if(index< 0) index= 0; if(contains(key)) return false; // Variables T[] keyTemp= new T[size+1]; K[] objTemp= new K[size+1]; int k= index; for(int i= 0; i< index; i++) { keyTemp[i]= pKeys[i]; objTemp[i]= pObjs[i]; } keyTemp[index]= key; objTemp[index]= value; for(int h= index+1; h< keyTemp.Length; h++) { keyTemp[h]= pKeys[k]; objTemp[h]= pObjs[k++]; } pKeys= keyTemp; pObjs= objTemp; return true; } // Finds if the two properties are equal public bool equals(FDictionary<T, K> props) { if(size!= props.size) return false; // Variables int trues= 0; for(int h= 0; h< size; h++) { for(int k= 0; k< props.size; k++) { if(pKeys[h].Equals(props.pKeys[k]) && pObjs[h].Equals(props.pObjs[k])) trues++; } } return (trues== size); } // Gets the key by the index public T getKeyByIndex(int index) { if(index< 0 || index>= size) return default(T); return pKeys[index]; } // Sets the key by the given index and key public void setKeyByIndex(int index, T key) { if(index< 0 || index>= size) return; pKeys[index]= key; } // Gets the key by the index via reference public bool getKeyByIndex(int index, out T key) { key= default(T); if(index< 0 || index>= size) return false; key= pKeys[index]; return true; } // Gets the value by the index public K getValueByIndex(int index) { if(index< 0 || index>= size) return default(K); return pObjs[index]; } // Sets the value by the given index and value public void setValueByIndex(int index, K value) { if(index< 0 || index>= size) return; pObjs[index]= value; } // Gets the value by the index via reference public bool getValueByIndex(int index, out K value) { value= default(K); if(index< 0 || index>= size) return false; value= pObjs[index]; return true; } #endregion // Methods #region --- Inherited Methods --- // Clears all the keys and values public void clear() { pKeys= new T[0]; pObjs= new K[0]; lstIndex= -1; } // Adds in a key and value public bool add(object key, object value) { if(key is T && value is K) return add((T)key, (K)value); return false; } // Adds in a range of keys and values public bool addRange(object[] pmKeys, object[] values) { if(pmKeys.Length!= values.Length) return false; if(pmKeys.GetType()== typeof(T) && values.GetType()== typeof(K)) { // Variables T[] keyTemp= new T[pmKeys.Length]; K[] objTemp= new K[values.Length]; for(int i= 0; i< pmKeys.Length; i++) { keyTemp[i]= (T)pmKeys[i]; objTemp[i]= (K)values[i]; } return addRange(keyTemp, objTemp); } return false; } // Finds if the given key exists public bool contains(object key) { if(key is T) return contains((T)key); return false; } // Gets the index of the given key public int getIndex(object key, int startIndex) { if(key is T) return getIndex((T)key, startIndex); return -1; } public int getIndex(object key) { return getIndex(key, 0); } // Inserts the key and value into the given index public bool insert(object key, object value, int index) { if(key is T && value is K) return insert((T)key, (K)value, index); return false; } // Removes the item via key public bool remove(object key) { return removeAt(getIndex(key)); } // Removes the item via index public bool removeAt(int index) { if(index< 0 || index>= size) return false; if(lstIndex== index) lstIndex= -1; // Variables T[] keyTemp= new T[size-1]; K[] objTemp= new K[size-1]; int k= index+1; for(int i= 0; i< index; i++) { keyTemp[i]= pKeys[i]; objTemp[i]= pObjs[i]; } if(k>= size) k= size-1; for(int h= index; h< keyTemp.Length; h++) { keyTemp[h]= pKeys[k]; objTemp[h]= pObjs[k++]; } pKeys= keyTemp; pObjs= objTemp; return true; } // Reverses the order of the keys and values public void reverseOrder() { if(size< 2) return; // Variables T[] keyTemp= new T[size]; K[] objTemp= new K[size]; int k= size-1; for(int h= 0; h< size; h++) { if(lstIndex== k) lstIndex= h; keyTemp[h]= pKeys[k]; objTemp[h]= pObjs[k--]; } pKeys= keyTemp; pObjs= objTemp; } // Switches the two given indices around public bool swap(int fIndex, int sIndex) { if(fIndex== sIndex) return true; if(fIndex< 0 || fIndex>= size) return false; if(sIndex< 0 || sIndex>= size) return false; if(lstIndex== fIndex) lstIndex= sIndex; else if(lstIndex== sIndex) lstIndex= fIndex; // Variables T keyTemp= pKeys[fIndex]; K objTemp= pObjs[fIndex]; pKeys[fIndex]= pKeys[sIndex]; pKeys[sIndex]= keyTemp; pObjs[fIndex]= pObjs[sIndex]; pObjs[sIndex]= objTemp; return true; } // Finds if the given object is equal to the list public override bool Equals(object obj) { if(obj== null) return false; if(obj is FDictionary<T, K>) return equals((FDictionary<T, K>)obj); return false; } // Gets the hash code public override int GetHashCode() { // Variables int hashcode= 0; for(int i= 0; i< size; i++) hashcode+= pKeys[i].GetHashCode()+pObjs[i].GetHashCode(); return hashcode; } // Prints out all the contents of the list public override string ToString() { // Variables string str= "Dictionary of "+typeof(T)+" : "+typeof(K)+"\n"; str+= "{\n"; for(int i= 0; i< size; i++) { if(i!= size-1) str+= "\tKey:"+pKeys[i].ToString()+",Value:"+pObjs[i].ToString()+",\n"; else str+= "\tKey:"+pKeys[i].ToString()+",Value:"+pObjs[i].ToString()+"\n"; } str+= "}"; return str; } #endregion // Inherited Methods } } // End of File
using System; using System.Collections.Generic; using System.Diagnostics; using dk.nita.saml20.Schema.Core; using dk.nita.saml20.Utils; using dk.nita.saml20.Validation; using Trace=dk.nita.saml20.Utils.Trace; namespace dk.nita.saml20.Validation { public class Saml20AssertionValidator : ISaml20AssertionValidator { private readonly List<string> _allowedAudienceUris; protected bool _quirksMode; public Saml20AssertionValidator(List<string> allowedAudienceUris, bool quirksMode) { _allowedAudienceUris = allowedAudienceUris; _quirksMode = quirksMode; } #region Properties private ISaml20NameIDValidator _nameIDValidator; private ISaml20NameIDValidator NameIDValidator { get { if (_nameIDValidator == null) _nameIDValidator = new Saml20NameIDValidator(); return _nameIDValidator; } } private ISaml20SubjectValidator _subjectValidator; private ISaml20SubjectValidator SubjectValidator { get { if (_subjectValidator == null) _subjectValidator = new Saml20SubjectValidator(); return _subjectValidator; } } private ISaml20StatementValidator StatementValidator { get { if (_statementValidator == null) _statementValidator = new Saml20StatementValidator(); return _statementValidator; } } private ISaml20StatementValidator _statementValidator; #endregion #region ISaml20AssertionValidator interface public virtual void ValidateAssertion(Assertion assertion) { if (assertion == null) throw new ArgumentNullException("assertion"); ValidateAssertionAttributes(assertion); ValidateSubject(assertion); ValidateConditions(assertion); ValidateStatements(assertion); } #region ISaml20AssertionValidator Members /// <summary> /// Null fields are considered to be valid /// </summary> private static bool ValidateNotBefore(DateTime? notBefore, DateTime now, TimeSpan allowedClockSkew) { if (notBefore == null) return true; return TimeRestrictionValidation.NotBeforeValid(notBefore.Value, now, allowedClockSkew); } /// <summary> /// Handle allowed clock skew by increasing notOnOrAfter with allowedClockSkew /// </summary> private static bool ValidateNotOnOrAfter(DateTime? notOnOrAfter, DateTime now, TimeSpan allowedClockSkew) { if (notOnOrAfter == null) return true; return TimeRestrictionValidation.NotOnOrAfterValid(notOnOrAfter.Value, now, allowedClockSkew); } public void ValidateTimeRestrictions(Assertion assertion, TimeSpan allowedClockSkew) { // Conditions are not required if (assertion.Conditions == null) return; Conditions conditions = assertion.Conditions; DateTime now = DateTime.UtcNow; // Negative allowed clock skew does not make sense - we are trying to relax the restriction interval, not restrict it any further if (allowedClockSkew < TimeSpan.Zero) allowedClockSkew = allowedClockSkew.Negate(); // NotBefore must not be in the future if (!ValidateNotBefore(conditions.NotBefore, now, allowedClockSkew)) throw new Saml20FormatException("Conditions.NotBefore must not be in the future"); // NotOnOrAfter must not be in the past if (!ValidateNotOnOrAfter(conditions.NotOnOrAfter, now, allowedClockSkew)) throw new Saml20FormatException("Conditions.NotOnOrAfter must not be in the past"); foreach (AuthnStatement statement in assertion.GetAuthnStatements()) { if (statement.SessionNotOnOrAfter != null && statement.SessionNotOnOrAfter <= now) throw new Saml20FormatException("AuthnStatement attribute SessionNotOnOrAfter MUST be in the future"); // TODO: Consider validating that authnStatement.AuthnInstant is in the past } if (assertion.Subject != null) { foreach (object o in assertion.Subject.Items) { if (!(o is SubjectConfirmation)) continue; SubjectConfirmation subjectConfirmation = (SubjectConfirmation) o; if (subjectConfirmation.SubjectConfirmationData == null) continue; if (!ValidateNotBefore(subjectConfirmation.SubjectConfirmationData.NotBefore, now, allowedClockSkew)) throw new Saml20FormatException("SubjectConfirmationData.NotBefore must not be in the future"); if (!ValidateNotOnOrAfter(subjectConfirmation.SubjectConfirmationData.NotOnOrAfter, now, allowedClockSkew)) throw new Saml20FormatException("SubjectConfirmationData.NotOnOrAfter must not be in the past"); } } } #endregion /// <summary> /// Validates that all the required attributes are present on the assertion. /// Furthermore it validates validity of the Issuer element. /// </summary> /// <param name="assertion"></param> private void ValidateAssertionAttributes(Assertion assertion) { //There must be a Version if (!Saml20Utils.ValidateRequiredString(assertion.Version)) throw new Saml20FormatException("Assertion element must have the Version attribute set."); //Version must be 2.0 if (assertion.Version != Saml20Constants.Version) throw new Saml20FormatException("Wrong value of version attribute on Assertion element"); //Assertion must have an ID if (!Saml20Utils.ValidateRequiredString(assertion.ID)) throw new Saml20FormatException("Assertion element must have the ID attribute set."); // Make sure that the ID elements is at least 128 bits in length (SAML2.0 std section 1.3.4) if (!Saml20Utils.ValidateIDString(assertion.ID)) throw new Saml20FormatException("Assertion element must have an ID attribute with at least 16 characters (the equivalent of 128 bits)"); //IssueInstant must be set. if (!assertion.IssueInstant.HasValue) throw new Saml20FormatException("Assertion element must have the IssueInstant attribute set."); //There must be an Issuer if (assertion.Issuer == null) throw new Saml20FormatException("Assertion element must have an issuer element."); //The Issuer element must be valid NameIDValidator.ValidateNameID(assertion.Issuer); } /// <summary> /// Validates the subject of an Asssertion /// </summary> /// <param name="assertion"></param> private void ValidateSubject(Assertion assertion) { if (assertion.Subject == null) { //If there is no statements there must be a subject // as specified in [SAML2.0std] section 2.3.3 if (assertion.Items == null || assertion.Items.Length == 0) throw new Saml20FormatException("Assertion with no Statements must have a subject."); foreach (StatementAbstract o in assertion.Items) { //If any of the below types are present there must be a subject. if (o is AuthnStatement || o is AuthzDecisionStatement || o is AttributeStatement) throw new Saml20FormatException("AuthnStatement, AuthzDecisionStatement and AttributeStatement require a subject."); } } else { //If a subject is present, validate it SubjectValidator.ValidateSubject(assertion.Subject); } } /// <summary> /// Validates the Assertion's conditions /// Audience restrictions processing rules are: /// - Within a single audience restriction condition in the assertion, the service must be configured /// with an audience-list that contains at least one of the restrictions in the assertion ("OR" filter) /// - When multiple audience restrictions are present within the same assertion, all individual audience /// restriction conditions must be met ("AND" filter) /// </summary> private void ValidateConditions(Assertion assertion) { // Conditions are not required if (assertion.Conditions == null) return; bool oneTimeUseSeen = false; bool proxyRestrictionsSeen = false; ValidateConditionsInterval(assertion.Conditions); foreach (ConditionAbstract cat in assertion.Conditions.Items) { if (cat is OneTimeUse) { if (oneTimeUseSeen) { throw new Saml20FormatException("Assertion contained more than one condition of type OneTimeUse"); } oneTimeUseSeen = true; continue; } if (cat is ProxyRestriction) { if (proxyRestrictionsSeen) { throw new Saml20FormatException("Assertion contained more than one condition of type ProxyRestriction"); } proxyRestrictionsSeen = true; ProxyRestriction proxyRestriction = (ProxyRestriction) cat; if (!String.IsNullOrEmpty(proxyRestriction.Count)) { uint res; if (!UInt32.TryParse(proxyRestriction.Count, out res)) throw new Saml20FormatException("Count attribute of ProxyRestriction MUST BE a non-negative integer"); } if (proxyRestriction.Audience != null) { foreach(string audience in proxyRestriction.Audience) { if (!Uri.IsWellFormedUriString(audience, UriKind.Absolute)) throw new Saml20FormatException("ProxyRestriction Audience MUST BE a wellformed uri"); } } } // AudienceRestriction processing goes here (section 2.5.1.4 of [SAML2.0std]) if (cat is AudienceRestriction) { // No audience restrictions? No problems... AudienceRestriction audienceRestriction = (AudienceRestriction)cat; if (audienceRestriction.Audience == null || audienceRestriction.Audience.Count == 0) continue; // If there are no allowed audience uris configured for the service, the assertion is not // valid for this service if (_allowedAudienceUris == null || _allowedAudienceUris.Count < 1) throw new Saml20FormatException("The service is not configured to meet any audience restrictions"); string match = null; foreach (string audience in audienceRestriction.Audience) { //In QuirksMode this validation is omitted if (!_quirksMode) { // The given audience value MUST BE a valid URI if (!Uri.IsWellFormedUriString(audience, UriKind.Absolute)) throw new Saml20FormatException("Audience element has value which is not a wellformed absolute uri"); } match = _allowedAudienceUris.Find( delegate(string allowedUri) { return allowedUri.Equals(audience); }); if (match != null) break; } // if (Trace.ShouldTrace(TraceEventType.Verbose)) // { // string intended = "Intended uris: " + Environment.NewLine + String.Join(Environment.NewLine, audienceRestriction.Audience.ToArray()); // string allowed = "Allowed uris: " + Environment.NewLine + String.Join(Environment.NewLine, _allowedAudienceUris.ToArray()); // Trace.TraceData(TraceEventType.Verbose, Trace.CreateTraceString(GetType(), "ValidateConditions"), intended, allowed); // } if (match == null) throw new Saml20FormatException("The service is not configured to meet the given audience restrictions"); } } } /// <summary> /// If both conditions.NotBefore and conditions.NotOnOrAfter are specified, NotBefore /// MUST BE less than NotOnOrAfter /// </summary> /// <exception cref="Saml20FormatException">If <param name="conditions"/>.NotBefore is not less than <paramref name="conditions"/>.NotOnOrAfter</exception> private static void ValidateConditionsInterval(Conditions conditions) { // No settings? No restrictions if (conditions.NotBefore == null && conditions.NotOnOrAfter == null) return; if (conditions.NotBefore != null && conditions.NotOnOrAfter != null && conditions.NotBefore.Value >= conditions.NotOnOrAfter.Value) throw new Saml20FormatException(String.Format("NotBefore {0} MUST BE less than NotOnOrAfter {1} on Conditions", Saml20Utils.ToUTCString(conditions.NotBefore.Value), Saml20Utils.ToUTCString(conditions.NotOnOrAfter.Value))); } /// <summary> /// Validates the details of the Statements present in the assertion ([SAML2.0std] section 2.7) /// NOTE: the rules relating to the enforcement of a Subject element are handled during Subject validation /// </summary> private void ValidateStatements(Assertion assertion) { // Statements are not required if (assertion.Items == null) return; foreach (StatementAbstract o in assertion.Items) { StatementValidator.ValidateStatement(o); } } #endregion } }
using System; using System.IO; using System.Web.Http; using Aspose.CAD.Live.Demos.UI.Models; using System.Threading.Tasks; using Aspose.CAD.Live.Demos.UI.Config; using System.IO.Compression; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Drawing.Imaging; using System.Drawing; using System.Net; using System.Linq; using Aspose.CAD.Live.Demos.UI.Helpers; namespace Aspose.CAD.Live.Demos.UI.Controllers { ///<Summary> /// AsposeViewerController class to get document page ///</Summary> public class AsposeViewerController : ApiController { ///<Summary> /// GetDocumentPage method to get document page ///</Summary> [HttpGet] public HttpResponseMessage GetDocumentPage( string file, string folderName, int currentPage) { string outfileName = Path.GetFileNameWithoutExtension(file) + "_{0}"; string outPath = Config.Configuration.OutputDirectory + folderName + "/" + outfileName; currentPage = currentPage - 1; string imagePath = string.Format(outPath, currentPage) + ".jpeg"; Directory.CreateDirectory(Config.Configuration.OutputDirectory + folderName); if (System.IO.File.Exists(imagePath)) { return GetImageFromPath(imagePath); } return null; } ///<Summary> /// DocumentPages method to get document pages ///</Summary> [HttpGet] public List<string> DocumentPages( string file, string folderName, int currentPage) { List<string> output; try { output = GetDocumentPages( file, folderName, currentPage); } catch (Exception ex) { throw ex; } return output; } private List<string> GetDocumentPages(string file, string folderName, int currentPage) { List<string> lstOutput = new List<string>(); string outfileName = "page_{0}"; string outPath = Config.Configuration.OutputDirectory + folderName + "/" + outfileName; currentPage = currentPage - 1; Directory.CreateDirectory(Config.Configuration.OutputDirectory + folderName); string imagePath = string.Format(outPath, currentPage) + ".jpeg"; if (System.IO.File.Exists(imagePath) && currentPage > 0) { lstOutput.Add(imagePath); return lstOutput; } int i = currentPage; var filename = System.IO.File.Exists(Config.Configuration.WorkingDirectory + folderName + "/" + file) ? Config.Configuration.WorkingDirectory + folderName + "/" + file : Config.Configuration.OutputDirectory + folderName + "/" + file; using (FilePathLock.Use(filename)) { try { Aspose.CAD.Live.Demos.UI.Models.License.SetAsposeCADLicense(); // Load an existing CAD document Aspose.CAD.FileFormats.Cad.CadImage image = (Aspose.CAD.FileFormats.Cad.CadImage)Aspose.CAD.Image.Load(filename); // Create an instance of CadRasterizationOptions Aspose.CAD.ImageOptions.CadRasterizationOptions rasterizationOptions = new Aspose.CAD.ImageOptions.CadRasterizationOptions(); // Set image width & height rasterizationOptions.PageWidth = 1024; rasterizationOptions.PageHeight = 1024; // Set the drawing to render at the center of image //rasterizationOptions.CenterDrawing = true; //rasterizationOptions.TypeOfEntities = Aspose.CAD.ImageOptions.TypeOfEntities.Entities3D; rasterizationOptions.AutomaticLayoutsScaling = true; rasterizationOptions.NoScaling = false; rasterizationOptions.ContentAsBitmap = true; // Set Graphics options rasterizationOptions.GraphicsOptions.SmoothingMode = Aspose.CAD.SmoothingMode.HighQuality; rasterizationOptions.GraphicsOptions.TextRenderingHint = Aspose.CAD.TextRenderingHint.AntiAliasGridFit; rasterizationOptions.GraphicsOptions.InterpolationMode = Aspose.CAD.InterpolationMode.HighQualityBicubic; // Get the layers in an instance of CadLayersDictionary var layersList = image.Layers; lstOutput.Add(layersList.Count.ToString()); i = 0; // Iterate over the layers foreach (var layerName in layersList.GetLayersNames()) { if (i == currentPage) { // Add the layer name to the CadRasterizationOptions's layer list rasterizationOptions.Layers[i] = layerName; // Create an instance of PngOptions for the resultant image Aspose.CAD.ImageOptions.JpegOptions options = new Aspose.CAD.ImageOptions.JpegOptions(); // Set rasterization options options.VectorRasterizationOptions = rasterizationOptions; image.Save(imagePath, options); lstOutput.Add(imagePath); image.Dispose(); break; } i++; } if (!image.Disposed) image.Dispose(); } catch (Exception ex) { throw ex; } return lstOutput; } } ///<Summary> /// DownloadDocument method to download document ///</Summary> [HttpGet] public HttpResponseMessage DownloadDocument(string file, string folderName, bool isImage) { string outfileName = Path.GetFileNameWithoutExtension(file) + "_Out.zip"; string outPath; if (!isImage) { if (System.IO.File.Exists(Config.Configuration.WorkingDirectory + folderName + "/" + file)) outPath = Config.Configuration.WorkingDirectory + folderName + "/" + file; else outPath = Config.Configuration.OutputDirectory + folderName + "/" + file; } else { outPath = Config.Configuration.OutputDirectory + outfileName; } using (FilePathLock.Use(outPath)) { if (isImage) { if (System.IO.File.Exists(outPath)) System.IO.File.Delete(outPath); List<string> lst = GetDocumentPages(file, folderName, 1); if (lst.Count > 1) { int tmpPageCount = int.Parse(lst[0]); for (int i = 2; i <= tmpPageCount; i++) { GetDocumentPages( file, folderName, i); } } ZipFile.CreateFromDirectory(Config.Configuration.OutputDirectory + folderName + "/", outPath); } if ((!System.IO.File.Exists(outPath)) || !Path.GetFullPath(outPath).StartsWith(Path.GetFullPath( System.Web.HttpContext.Current.Server.MapPath("~/Assets/")))) { var exception = new HttpResponseException(HttpStatusCode.NotFound); throw exception; } try { using (var fileStream = new FileStream(outPath, FileMode.Open, FileAccess.Read)) { using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.ToArray()) }; result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = (isImage ? outfileName : file) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; } } } catch (Exception x) { Console.WriteLine(x.Message); } } return null; } ///<Summary> /// PageImage method to get page image ///</Summary> [HttpGet] public HttpResponseMessage PageImage(string imagePath) { return GetImageFromPath(imagePath); } private HttpResponseMessage GetImageFromPath(string imagePath) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read); System.Drawing.Image image = System.Drawing.Image.FromStream(fileStream); MemoryStream memoryStream = new MemoryStream(); image.Save(memoryStream, ImageFormat.Jpeg); result.Content = new ByteArrayContent(memoryStream.ToArray()); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); fileStream.Close(); return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace System.Threading { public sealed partial class Semaphore : WaitHandle { // creates a nameless semaphore object // Win32 only takes maximum count of Int32.MaxValue [SecuritySafeCritical] public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { } [SecurityCritical] public Semaphore(int initialCount, int maximumCount, string name) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } if (maximumCount < 1) { throw new ArgumentOutOfRangeException("maximumCount", SR.ArgumentOutOfRange_NeedPosNum); } if (initialCount > maximumCount) { throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); } ValidateNewName(name); SafeWaitHandle myHandle = CreateSemaphone(initialCount, maximumCount, name); if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); WinIOError(); } this.SafeWaitHandle = myHandle; } [SecurityCritical] public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } if (maximumCount < 1) { throw new ArgumentOutOfRangeException("maximumCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } if (initialCount > maximumCount) { throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); } ValidateNewName(name); SafeWaitHandle myHandle; myHandle = CreateSemaphone(initialCount, maximumCount, name); int errorCode = Marshal.GetLastWin32Error(); if (myHandle.IsInvalid) { if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); WinIOError(); } createdNew = errorCode != Interop.mincore.Errors.ERROR_ALREADY_EXISTS; this.SafeWaitHandle = myHandle; } [SecurityCritical] private Semaphore(SafeWaitHandle handle) { this.SafeWaitHandle = handle; } [SecurityCritical] public static Semaphore OpenExisting(string name) { Semaphore result; switch (OpenExistingWorker(name, out result)) { case OpenExistingResult.NameNotFound: throw new WaitHandleCannotBeOpenedException(); case OpenExistingResult.NameInvalid: throw new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); case OpenExistingResult.PathNotFound: throw new IOException(GetMessage(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)); default: return result; } } [SecurityCritical] public static bool TryOpenExisting(string name, out Semaphore result) { return OpenExistingWorker(name, out result) == OpenExistingResult.Success; } // This exists in WaitHandle, but is oddly ifdefed for some reason... private enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } [SecurityCritical] private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) { ValidateExistingName(name); result = null; SafeWaitHandle myHandle = OpenSemaphore(name); if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (Interop.mincore.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.mincore.Errors.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Interop.mincore.Errors.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; //this is for passed through NativeMethods Errors WinIOError(); } result = new Semaphore(myHandle); return OpenExistingResult.Success; } public int Release() { return Release(1); } // increase the count on a semaphore, returns previous count [SecuritySafeCritical] public int Release(int releaseCount) { if (releaseCount < 1) { throw new ArgumentOutOfRangeException("releaseCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } int previousCount; //If ReleaseSempahore returns false when the specified value would cause // the semaphore's count to exceed the maximum count set when Semaphore was created //Non-Zero return if (!ReleaseSemaphore(SafeWaitHandle, releaseCount, out previousCount)) { throw new SemaphoreFullException(); } return previousCount; } internal static void WinIOError() { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, String.Empty); } internal static void WinIOError(string str) { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, str); } // After calling GetLastWin32Error(), it clears the last error field, // so you must save the HResult and pass it to this method. This method // will determine the appropriate exception to throw dependent on your // error, and depending on the error, insert a string into the message // gotten from the ResourceManager. internal static void WinIOError(int errorCode, String str) { throw new IOException(GetMessage(errorCode), MakeHRFromErrorCode(errorCode)); } // Use this to translate error codes like the above into HRESULTs like // 0x80070006 for ERROR_INVALID_HANDLE internal static int MakeHRFromErrorCode(int errorCode) { return unchecked(((int)0x80070000) | errorCode); } } }
/* * TraceListener.cs - Implementation of the * "System.Diagnostics.TraceListener" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Diagnostics { #if !ECMA_COMPAT public abstract class TraceListener : MarshalByRefObject, IDisposable { // Internal state. private int indentLevel; private int indentSize; private String name; private bool needIndent; // Constructors. protected TraceListener() { this.indentLevel = 0; this.indentSize = 4; this.name = String.Empty; this.needIndent = false; } protected TraceListener(String name) { this.indentLevel = 0; this.indentSize = 4; this.name = name; this.needIndent = false; } // Listener properties. public int IndentLevel { get { return indentLevel; } set { if(value < 0) { value = 0; } indentLevel = value; } } public int IndentSize { get { return indentSize; } set { if(value < 0) { throw new ArgumentOutOfRangeException ("value", S._("ArgRange_NonNegative")); } indentSize = value; } } public virtual String Name { get { return name; } set { name = value; } } protected bool NeedIndent { get { return needIndent; } set { needIndent = value; } } // Close this trace listener. public virtual void Close() { // Nothing to do here. } // Dispose this trace listener. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Nothing to do here. } // Log a failure message to this trace listener. public virtual void Fail(String message) { // Nothing to do here. } public virtual void Fail(String message, String detailMessage) { // Nothing to do here. } // Flush this trace listener's output stream. public virtual void Flush() { // Nothing to do here. } // Write data to this trace listener's output stream. public virtual void Write(Object o) { if(o != null) { Write(o.ToString()); } } public abstract void Write(String message); public virtual void Write(Object o, String category) { if(category == null) { if(o != null) { Write(o.ToString()); } } else if(o != null) { Write(o.ToString(), category); } else { Write(String.Empty, category); } } public virtual void Write(String message, String category) { if(category == null) { Write(message); } else if(message != null) { Write(category + ": " + message); } else { Write(category + ": "); } } // Write indent data to this trace listener. protected virtual void WriteIndent() { NeedIndent = false; int level = indentLevel; String indent; if(indentSize == 4) { // Short-cut to improve common-case performance. indent = " "; } else { indent = new String(' ', indentSize); } while(level > 0) { Write(indent); --level; } } // Write data to this trace listener's output stream followed by newline. public virtual void WriteLine(Object o) { if(o != null) { WriteLine(o.ToString()); } else { WriteLine(String.Empty); } } public abstract void WriteLine(String message); public virtual void WriteLine(Object o, String category) { if(category == null) { if(o != null) { WriteLine(o.ToString()); } } else if(o != null) { WriteLine(o.ToString(), category); } else { WriteLine(String.Empty, category); } } public virtual void WriteLine(String message, String category) { if(category == null) { WriteLine(message); } else if(message != null) { WriteLine(category + ": " + message); } else { WriteLine(category + ": "); } } }; // class TraceListener #endif // !ECMA_COMPAT }; // namespace System.Diagnostics
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Threading.Channels.Tests { public abstract class UnboundedChannelTests : ChannelTestBase { protected override Channel<T> CreateChannel<T>() => Channel.CreateUnbounded<T>( new UnboundedChannelOptions { SingleReader = RequiresSingleReader, AllowSynchronousContinuations = AllowSynchronousContinuations }); protected override Channel<T> CreateFullChannel<T>() => null; [Fact] public async Task Complete_BeforeEmpty_NoWaiters_TriggersCompletion() { Channel<int> c = CreateChannel(); Assert.True(c.Writer.TryWrite(42)); c.Writer.Complete(); Assert.False(c.Reader.Completion.IsCompleted); Assert.Equal(42, await c.Reader.ReadAsync()); await c.Reader.Completion; } [Fact] public void TryWrite_TryRead_Many() { Channel<int> c = CreateChannel(); const int NumItems = 100000; for (int i = 0; i < NumItems; i++) { Assert.True(c.Writer.TryWrite(i)); } for (int i = 0; i < NumItems; i++) { Assert.True(c.Reader.TryRead(out int result)); Assert.Equal(i, result); } } [Fact] public void TryWrite_TryRead_OneAtATime() { Channel<int> c = CreateChannel(); for (int i = 0; i < 10; i++) { Assert.True(c.Writer.TryWrite(i)); Assert.True(c.Reader.TryRead(out int result)); Assert.Equal(i, result); } } [Fact] public void WaitForReadAsync_DataAvailable_CompletesSynchronously() { Channel<int> c = CreateChannel(); Assert.True(c.Writer.TryWrite(42)); AssertSynchronousTrue(c.Reader.WaitToReadAsync()); } [Theory] [InlineData(0)] [InlineData(1)] public async Task WriteMany_ThenComplete_SuccessfullyReadAll(int readMode) { Channel<int> c = CreateChannel(); for (int i = 0; i < 10; i++) { Assert.True(c.Writer.TryWrite(i)); } c.Writer.Complete(); Assert.False(c.Reader.Completion.IsCompleted); for (int i = 0; i < 10; i++) { Assert.False(c.Reader.Completion.IsCompleted); switch (readMode) { case 0: int result; Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); break; case 1: Assert.Equal(i, await c.Reader.ReadAsync()); break; } } await c.Reader.Completion; } [Fact] public void AllowSynchronousContinuations_WaitToReadAsync_ContinuationsInvokedAccordingToSetting() { Channel<int> c = CreateChannel(); int expectedId = Environment.CurrentManagedThreadId; Task r = c.Reader.WaitToReadAsync().AsTask().ContinueWith(_ => { Assert.Equal(AllowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(c.Writer.WriteAsync(42).IsCompletedSuccessfully); ((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation r.GetAwaiter().GetResult(); } [Fact] public void AllowSynchronousContinuations_CompletionTask_ContinuationsInvokedAccordingToSetting() { Channel<int> c = CreateChannel(); int expectedId = Environment.CurrentManagedThreadId; Task r = c.Reader.Completion.ContinueWith(_ => { Assert.Equal(AllowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(c.Writer.TryComplete()); ((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation r.GetAwaiter().GetResult(); } } public abstract class SingleReaderUnboundedChannelTests : UnboundedChannelTests { protected override bool RequiresSingleReader => true; [Fact] public void ValidateInternalDebuggerAttributes() { Channel<int> c = CreateChannel(); Assert.True(c.Writer.TryWrite(1)); Assert.True(c.Writer.TryWrite(2)); object queue = DebuggerAttributes.GetFieldValue(c, "_items"); DebuggerAttributes.ValidateDebuggerDisplayReferences(queue); DebuggerAttributes.InvokeDebuggerTypeProxyProperties(queue); } [Fact] public async Task MultipleWaiters_CancelsPreviousWaiter() { Channel<int> c = CreateChannel(); ValueTask<bool> t1 = c.Reader.WaitToReadAsync(); ValueTask<bool> t2 = c.Reader.WaitToReadAsync(); await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await t1); Assert.True(c.Writer.TryWrite(42)); Assert.True(await t2); } [Fact] public async Task MultipleReaders_CancelsPreviousReader() { Channel<int> c = CreateChannel(); ValueTask<int> t1 = c.Reader.ReadAsync(); ValueTask<int> t2 = c.Reader.ReadAsync(); await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await t1); Assert.True(c.Writer.TryWrite(42)); Assert.Equal(42, await t2); } [Fact] public void Stress_TryWrite_TryRead() { const int NumItems = 3000000; Channel<int> c = CreateChannel(); Task.WaitAll( Task.Run(async () => { int received = 0; while (await c.Reader.WaitToReadAsync()) { while (c.Reader.TryRead(out int i)) { Assert.Equal(received, i); received++; } } }), Task.Run(() => { for (int i = 0; i < NumItems; i++) { Assert.True(c.Writer.TryWrite(i)); } c.Writer.Complete(); })); } } public sealed class SyncMultiReaderUnboundedChannelTests : UnboundedChannelTests { protected override bool AllowSynchronousContinuations => true; } public sealed class AsyncMultiReaderUnboundedChannelTests : UnboundedChannelTests { protected override bool AllowSynchronousContinuations => false; } public sealed class SyncSingleReaderUnboundedChannelTests : SingleReaderUnboundedChannelTests { protected override bool AllowSynchronousContinuations => true; } public sealed class AsyncSingleReaderUnboundedChannelTests : SingleReaderUnboundedChannelTests { protected override bool AllowSynchronousContinuations => false; } }
/* * * Tiger Tree Hash Threaded - by Gil Schmidt. * * - this code was writtin based on: * "Tree Hash EXchange format (THEX)" * http://www.open-content.net/specs/draft-jchapweske-thex-02.html * * - the tiger hash class was converted from visual basic code called TigerNet: * http://www.hotpixel.net/software.html * * - Base32 class was taken from: * http://msdn.microsoft.com/msdnmag/issues/04/07/CustomPreferences/default.aspx * didn't want to waste my time on writing a Base32 class. * * - along with the request for a version the return the full TTH tree and the need * for a faster version i rewrote a thread base version of the ThexCS. * i must say that the outcome wasn't as good as i thought it would be. * after writing ThexOptimized i noticed that the major "speed barrier" * was reading the data from the file so i decide to split it into threads * that each one will read the data and will make the computing process shorter. * in testing i found out that small files (about 50 mb) are being processed * faster but in big files (700 mb) it was slower, also the CPU is working better * with more threads. * * - the update for the ThexThreaded is now including a Dispose() function to free * some memory which is mostly taken by the TTH array, also i changed the way the * data is pulled out of the file so it would read data block instead of data leaf * every time (reduced the i/o reads dramaticly and go easy on the hd) i used 1 MB * blocks for each thread you can set it at DataBlockSize (put something like: * LeafSize * N). the method for copying bytes is change to Buffer.BlockCopy it's * faster but you won't notice it too much. * * (a lot of threads = slower but the cpu is working less, i recommend 3-5 threads) * * - fixed code for 0 byte file (thanks Flow84). * * * if you use this code please add my name and email to the references! * [ contact me at Gil_Smdt@hotmali.com ] */ using System; using System.Threading; using System.IO; namespace TTH { public class ThexThreaded { const byte LeafHash = 0x00; const byte InternalHash = 0x01; const int LeafSize = 1024; const int DataBlockSize = LeafSize * 1024; // 1 MB const int ThreadCount = 4; const int ZERO_BYTE_FILE = 0; public byte[][][] TTH; public int LevelCount; string Filename; int LeafCount; FileStream FilePtr; FileBlock[] FileParts = new FileBlock[ThreadCount]; Thread[] ThreadsList = new Thread[ThreadCount]; public byte[] GetTTH_Value(string Filename) { GetTTH(Filename); return TTH[LevelCount-1][0]; } public byte[][][] GetTTH_Tree(string Filename) { GetTTH(Filename); return TTH; } private void GetTTH(string Filename) { this.Filename = Filename; try { OpenFile(); if (Initialize()) { SplitFile(); Console.WriteLine("starting to get TTH: " + DateTime.Now.ToString()); StartThreads(); Console.WriteLine("finished to get TTH: " + DateTime.Now.ToString()); GC.Collect(); CompressTree(); } } catch (Exception e) { Console.WriteLine("error while trying to get TTH: " + e.Message); StopThreads(); } if (FilePtr != null) FilePtr.Close(); } void Dispose() { TTH = null; ThreadsList = null; FileParts = null; GC.Collect(); } void OpenFile() { if (!File.Exists(Filename)) throw new Exception("file doesn't exists!"); FilePtr = new FileStream(Filename,FileMode.Open,FileAccess.Read,FileShare.Read); //,DataBlockSize); } bool Initialize() { if (FilePtr.Length == ZERO_BYTE_FILE) { Tiger TG = new Tiger(); LevelCount = 1; TTH = new byte[1][][]; TTH[0] = new byte[1][]; TTH[0][0] = TG.ComputeHash(new byte[1] { 0 }); return false; } else { int i = 1; LevelCount = 1; LeafCount = (int)(FilePtr.Length / LeafSize); if ((FilePtr.Length % LeafSize) > 0) LeafCount++; while (i < LeafCount) { i *= 2; LevelCount++; } TTH = new byte[LevelCount][][]; TTH[0] = new byte[LeafCount][]; } return true; } void SplitFile() { long LeafsInPart = LeafCount / ThreadCount; // check if file is bigger then 1 MB or don't use threads if (FilePtr.Length > 1024 * 1024) for (int i = 0; i < ThreadCount; i++) FileParts[i] = new FileBlock(LeafsInPart * LeafSize * i, LeafsInPart * LeafSize * (i + 1)); FileParts[ThreadCount - 1].End = FilePtr.Length; } void StartThreads() { for (int i = 0; i < ThreadCount; i++) { ThreadsList[i] = new Thread(new ThreadStart(ProcessLeafs)); ThreadsList[i].IsBackground = true; ThreadsList[i].Name = i.ToString(); ThreadsList[i].Start(); } bool ThreadsAreWorking = false; do { Thread.Sleep(1000); ThreadsAreWorking = false; for (int i = 0; i < ThreadCount; i++) if (ThreadsList[i].IsAlive) ThreadsAreWorking = true; } while (ThreadsAreWorking); } void StopThreads() { for (int i = 0; i < ThreadCount; i++) if (ThreadsList[i] != null && ThreadsList[i].IsAlive) ThreadsList[i].Abort(); } void ProcessLeafs() { FileStream ThreadFilePtr = new FileStream(Filename,FileMode.Open,FileAccess.Read); FileBlock ThreadFileBlock = FileParts[Convert.ToInt16(Thread.CurrentThread.Name)]; Tiger TG = new Tiger(); byte[] DataBlock; byte[] Data = new byte[LeafSize + 1]; long LeafIndex; int BlockLeafs; int i; ThreadFilePtr.Position = ThreadFileBlock.Start; while (ThreadFilePtr.Position < ThreadFileBlock.End) { LeafIndex = ThreadFilePtr.Position / 1024; if (ThreadFileBlock.End - ThreadFilePtr.Position < DataBlockSize) DataBlock = new byte[ThreadFileBlock.End - ThreadFilePtr.Position]; else DataBlock = new byte[DataBlockSize]; ThreadFilePtr.Read(DataBlock,0,DataBlock.Length); //read block BlockLeafs = DataBlock.Length / 1024; for (i = 0; i < BlockLeafs; i++) { Buffer.BlockCopy(DataBlock,i * LeafSize,Data,1,LeafSize); TG.Initialize(); TTH[0][LeafIndex++] = TG.ComputeHash(Data); } if (i * LeafSize < DataBlock.Length) { Data = new byte[DataBlock.Length - BlockLeafs * LeafSize + 1]; Data[0] = LeafHash; Buffer.BlockCopy(DataBlock,BlockLeafs * LeafSize,Data,1,(Data.Length - 1)); TG.Initialize(); TTH[0][LeafIndex++] = TG.ComputeHash(Data); Data = new byte[LeafSize + 1]; Data[0] = LeafHash; } } DataBlock = null; Data = null; } void CompressTree() { int InternalLeafCount; int Level = 0,i,LeafIndex; while (Level + 1 < LevelCount) { LeafIndex = 0; InternalLeafCount = (LeafCount / 2) + (LeafCount % 2); TTH[Level + 1] = new byte[InternalLeafCount][]; for (i = 1; i < LeafCount; i += 2) ProcessInternalLeaf(Level + 1,LeafIndex++,TTH[Level][i - 1],TTH[Level][i]); if (LeafIndex < InternalLeafCount) TTH[Level + 1][LeafIndex] = TTH[Level][LeafCount - 1]; Level++; LeafCount = InternalLeafCount; } } void ProcessInternalLeaf(int Level,int Index,byte[] LeafA,byte[] LeafB) { Tiger TG = new Tiger(); byte[] Data = new byte[LeafA.Length + LeafB.Length + 1]; Data[0] = InternalHash; Buffer.BlockCopy(LeafA,0,Data,1,LeafA.Length); Buffer.BlockCopy(LeafB,0,Data,LeafA.Length + 1,LeafA.Length); TG.Initialize(); TTH[Level][Index] = TG.ComputeHash(Data); } } struct FileBlock { public long Start,End; public FileBlock(long Start,long End) { this.Start = Start; this.End = End; } } }
// /* // * Copyright (c) 2016, Alachisoft. 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. // */ #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 Alachisoft.NosDB.Common.Protobuf { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class GetChunkResponse { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_GetChunkResponse__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse, global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_GetChunkResponse__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static GetChunkResponse() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZHZXRDaHVua1Jlc3BvbnNlLnByb3RvEiBBbGFjaGlzb2Z0Lk5vc0RCLkNv", "bW1vbi5Qcm90b2J1ZhoPRGF0YUNodW5rLnByb3RvIlIKEEdldENodW5rUmVz", "cG9uc2USPgoJZGF0YUNodW5rGAEgASgLMisuQWxhY2hpc29mdC5Ob3NEQi5D", "b21tb24uUHJvdG9idWYuRGF0YUNodW5rQkAKJGNvbS5hbGFjaGlzb2Z0Lm5v", "c2RiLmNvbW1vbi5wcm90b2J1ZkIYR2V0Q2h1bmtSZXNwb25zZVByb3RvY29s")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NosDB_Common_Protobuf_GetChunkResponse__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NosDB_Common_Protobuf_GetChunkResponse__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse, global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_GetChunkResponse__Descriptor, new string[] { "DataChunk", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Alachisoft.NosDB.Common.Protobuf.Proto.DataChunk.Descriptor, }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class GetChunkResponse : pb::GeneratedMessage<GetChunkResponse, GetChunkResponse.Builder> { private GetChunkResponse() { } private static readonly GetChunkResponse defaultInstance = new GetChunkResponse().MakeReadOnly(); private static readonly string[] _getChunkResponseFieldNames = new string[] { "dataChunk" }; private static readonly uint[] _getChunkResponseFieldTags = new uint[] { 10 }; public static GetChunkResponse DefaultInstance { get { return defaultInstance; } } public override GetChunkResponse DefaultInstanceForType { get { return DefaultInstance; } } protected override GetChunkResponse ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.GetChunkResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_GetChunkResponse__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<GetChunkResponse, GetChunkResponse.Builder> InternalFieldAccessors { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.GetChunkResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_GetChunkResponse__FieldAccessorTable; } } public const int DataChunkFieldNumber = 1; private bool hasDataChunk; private global::Alachisoft.NosDB.Common.Protobuf.DataChunk dataChunk_; public bool HasDataChunk { get { return hasDataChunk; } } public global::Alachisoft.NosDB.Common.Protobuf.DataChunk DataChunk { get { return dataChunk_ ?? global::Alachisoft.NosDB.Common.Protobuf.DataChunk.DefaultInstance; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _getChunkResponseFieldNames; if (hasDataChunk) { output.WriteMessage(1, field_names[0], DataChunk); } 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 (hasDataChunk) { size += pb::CodedOutputStream.ComputeMessageSize(1, DataChunk); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static GetChunkResponse ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static GetChunkResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static GetChunkResponse ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static GetChunkResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static GetChunkResponse ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static GetChunkResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static GetChunkResponse ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static GetChunkResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static GetChunkResponse ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static GetChunkResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private GetChunkResponse 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(GetChunkResponse prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<GetChunkResponse, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(GetChunkResponse cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private GetChunkResponse result; private GetChunkResponse PrepareBuilder() { if (resultIsReadOnly) { GetChunkResponse original = result; result = new GetChunkResponse(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override GetChunkResponse 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::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.Descriptor; } } public override GetChunkResponse DefaultInstanceForType { get { return global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.DefaultInstance; } } public override GetChunkResponse BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is GetChunkResponse) { return MergeFrom((GetChunkResponse) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(GetChunkResponse other) { if (other == global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.DefaultInstance) return this; PrepareBuilder(); if (other.HasDataChunk) { MergeDataChunk(other.DataChunk); } 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(_getChunkResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _getChunkResponseFieldTags[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: { global::Alachisoft.NosDB.Common.Protobuf.DataChunk.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.DataChunk.CreateBuilder(); if (result.hasDataChunk) { subBuilder.MergeFrom(DataChunk); } input.ReadMessage(subBuilder, extensionRegistry); DataChunk = subBuilder.BuildPartial(); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasDataChunk { get { return result.hasDataChunk; } } public global::Alachisoft.NosDB.Common.Protobuf.DataChunk DataChunk { get { return result.DataChunk; } set { SetDataChunk(value); } } public Builder SetDataChunk(global::Alachisoft.NosDB.Common.Protobuf.DataChunk value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasDataChunk = true; result.dataChunk_ = value; return this; } public Builder SetDataChunk(global::Alachisoft.NosDB.Common.Protobuf.DataChunk.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasDataChunk = true; result.dataChunk_ = builderForValue.Build(); return this; } public Builder MergeDataChunk(global::Alachisoft.NosDB.Common.Protobuf.DataChunk value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasDataChunk && result.dataChunk_ != global::Alachisoft.NosDB.Common.Protobuf.DataChunk.DefaultInstance) { result.dataChunk_ = global::Alachisoft.NosDB.Common.Protobuf.DataChunk.CreateBuilder(result.dataChunk_).MergeFrom(value).BuildPartial(); } else { result.dataChunk_ = value; } result.hasDataChunk = true; return this; } public Builder ClearDataChunk() { PrepareBuilder(); result.hasDataChunk = false; result.dataChunk_ = null; return this; } } static GetChunkResponse() { object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.GetChunkResponse.Descriptor, null); } } #endregion } #endregion Designer generated code
namespace T5Suite2 { partial class SRAMCompareResults { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SRAMCompareResults)); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.showDifferenceMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn6 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn7 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn8 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn9 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn10 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn11 = new DevExpress.XtraGrid.Columns.GridColumn(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); this.contextMenuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); this.SuspendLayout(); // // gridControl1 // this.gridControl1.AccessibleDescription = null; this.gridControl1.AccessibleName = null; resources.ApplyResources(this.gridControl1, "gridControl1"); this.gridControl1.BackgroundImage = null; this.gridControl1.ContextMenuStrip = this.contextMenuStrip1; this.gridControl1.EmbeddedNavigator.AccessibleDescription = null; this.gridControl1.EmbeddedNavigator.AccessibleName = null; this.gridControl1.EmbeddedNavigator.AllowHtmlTextInToolTip = ((DevExpress.Utils.DefaultBoolean)(resources.GetObject("gridControl1.EmbeddedNavigator.AllowHtmlTextInToolTip"))); this.gridControl1.EmbeddedNavigator.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("gridControl1.EmbeddedNavigator.Anchor"))); this.gridControl1.EmbeddedNavigator.BackgroundImage = null; this.gridControl1.EmbeddedNavigator.BackgroundImageLayout = ((System.Windows.Forms.ImageLayout)(resources.GetObject("gridControl1.EmbeddedNavigator.BackgroundImageLayout"))); this.gridControl1.EmbeddedNavigator.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("gridControl1.EmbeddedNavigator.ImeMode"))); this.gridControl1.EmbeddedNavigator.TextLocation = ((DevExpress.XtraEditors.NavigatorButtonsTextLocation)(resources.GetObject("gridControl1.EmbeddedNavigator.TextLocation"))); this.gridControl1.EmbeddedNavigator.ToolTip = resources.GetString("gridControl1.EmbeddedNavigator.ToolTip"); this.gridControl1.EmbeddedNavigator.ToolTipIconType = ((DevExpress.Utils.ToolTipIconType)(resources.GetObject("gridControl1.EmbeddedNavigator.ToolTipIconType"))); this.gridControl1.EmbeddedNavigator.ToolTipTitle = resources.GetString("gridControl1.EmbeddedNavigator.ToolTipTitle"); this.gridControl1.Font = null; this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); // // contextMenuStrip1 // this.contextMenuStrip1.AccessibleDescription = null; this.contextMenuStrip1.AccessibleName = null; resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1"); this.contextMenuStrip1.BackgroundImage = null; this.contextMenuStrip1.Font = null; this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.showDifferenceMapToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; // // showDifferenceMapToolStripMenuItem // this.showDifferenceMapToolStripMenuItem.AccessibleDescription = null; this.showDifferenceMapToolStripMenuItem.AccessibleName = null; resources.ApplyResources(this.showDifferenceMapToolStripMenuItem, "showDifferenceMapToolStripMenuItem"); this.showDifferenceMapToolStripMenuItem.BackgroundImage = null; this.showDifferenceMapToolStripMenuItem.Name = "showDifferenceMapToolStripMenuItem"; this.showDifferenceMapToolStripMenuItem.ShortcutKeyDisplayString = null; this.showDifferenceMapToolStripMenuItem.Click += new System.EventHandler(this.showDifferenceMapToolStripMenuItem_Click); // // gridView1 // resources.ApplyResources(this.gridView1, "gridView1"); this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.gridColumn1, this.gridColumn2, this.gridColumn3, this.gridColumn4, this.gridColumn5, this.gridColumn6, this.gridColumn7, this.gridColumn8, this.gridColumn9, this.gridColumn10, this.gridColumn11}); this.gridView1.GridControl = this.gridControl1; this.gridView1.GroupCount = 2; this.gridView1.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, "CATEGORYNAME", null, " ({0})")}); this.gridView1.Name = "gridView1"; this.gridView1.OptionsBehavior.AllowIncrementalSearch = true; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsView.GroupDrawMode = DevExpress.XtraGrid.Views.Grid.GroupDrawMode.Standard; this.gridView1.OptionsView.ShowAutoFilterRow = true; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.OptionsView.ShowIndicator = false; this.gridView1.SortInfo.AddRange(new DevExpress.XtraGrid.Columns.GridColumnSortInfo[] { new DevExpress.XtraGrid.Columns.GridColumnSortInfo(this.gridColumn10, DevExpress.Data.ColumnSortOrder.Ascending), new DevExpress.XtraGrid.Columns.GridColumnSortInfo(this.gridColumn11, DevExpress.Data.ColumnSortOrder.Descending)}); this.gridView1.DoubleClick += new System.EventHandler(this.gridView1_DoubleClick); this.gridView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.gridView1_KeyDown); this.gridView1.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(this.gridView1_CustomDrawCell); // // gridColumn1 // resources.ApplyResources(this.gridColumn1, "gridColumn1"); this.gridColumn1.FieldName = "SYMBOLNAME"; this.gridColumn1.Name = "gridColumn1"; // // gridColumn2 // resources.ApplyResources(this.gridColumn2, "gridColumn2"); this.gridColumn2.DisplayFormat.FormatString = "{0:X4}"; this.gridColumn2.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.gridColumn2.FieldName = "SRAMADDRESS"; this.gridColumn2.Name = "gridColumn2"; // // gridColumn3 // resources.ApplyResources(this.gridColumn3, "gridColumn3"); this.gridColumn3.DisplayFormat.FormatString = "{0:X4}"; this.gridColumn3.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.gridColumn3.FieldName = "FLASHADDRESS"; this.gridColumn3.Name = "gridColumn3"; // // gridColumn4 // resources.ApplyResources(this.gridColumn4, "gridColumn4"); this.gridColumn4.DisplayFormat.FormatString = "{0:X4}"; this.gridColumn4.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.gridColumn4.FieldName = "LENGTHBYTES"; this.gridColumn4.Name = "gridColumn4"; // // gridColumn5 // resources.ApplyResources(this.gridColumn5, "gridColumn5"); this.gridColumn5.DisplayFormat.FormatString = "{0:X4}"; this.gridColumn5.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; this.gridColumn5.FieldName = "LENGTHVALUES"; this.gridColumn5.Name = "gridColumn5"; // // gridColumn6 // resources.ApplyResources(this.gridColumn6, "gridColumn6"); this.gridColumn6.FieldName = "DESCRIPTION"; this.gridColumn6.Name = "gridColumn6"; // // gridColumn7 // resources.ApplyResources(this.gridColumn7, "gridColumn7"); this.gridColumn7.DisplayFormat.FormatString = "{0:F1}"; this.gridColumn7.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom; this.gridColumn7.FieldName = "DIFFPERCENTAGE"; this.gridColumn7.Name = "gridColumn7"; // // gridColumn8 // resources.ApplyResources(this.gridColumn8, "gridColumn8"); this.gridColumn8.FieldName = "DIFFABSOLUTE"; this.gridColumn8.Name = "gridColumn8"; // // gridColumn9 // resources.ApplyResources(this.gridColumn9, "gridColumn9"); this.gridColumn9.DisplayFormat.FormatString = "{0:F1}"; this.gridColumn9.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom; this.gridColumn9.FieldName = "DIFFAVERAGE"; this.gridColumn9.Name = "gridColumn9"; // // gridColumn10 // resources.ApplyResources(this.gridColumn10, "gridColumn10"); this.gridColumn10.FieldName = "CATEGORYNAME"; this.gridColumn10.GroupFormat.FormatString = "{0}: [#image]{1} {2}"; this.gridColumn10.Name = "gridColumn10"; // // gridColumn11 // resources.ApplyResources(this.gridColumn11, "gridColumn11"); this.gridColumn11.FieldName = "SUBCATEGORYNAME"; this.gridColumn11.GroupFormat.FormatString = "{0}: [#image]{1} {2}"; this.gridColumn11.Name = "gridColumn11"; // // SRAMCompareResults // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = null; this.Controls.Add(this.gridControl1); this.Name = "SRAMCompareResults"; ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); this.contextMenuStrip1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraGrid.Views.Grid.GridView gridView1; public DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn2; private DevExpress.XtraGrid.Columns.GridColumn gridColumn3; private DevExpress.XtraGrid.Columns.GridColumn gridColumn4; private DevExpress.XtraGrid.Columns.GridColumn gridColumn5; private DevExpress.XtraGrid.Columns.GridColumn gridColumn6; private DevExpress.XtraGrid.Columns.GridColumn gridColumn7; private DevExpress.XtraGrid.Columns.GridColumn gridColumn8; private DevExpress.XtraGrid.Columns.GridColumn gridColumn9; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem showDifferenceMapToolStripMenuItem; private DevExpress.XtraGrid.Columns.GridColumn gridColumn10; private DevExpress.XtraGrid.Columns.GridColumn gridColumn11; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Runtime.CompilerServices; using System.Text; namespace Microsoft.AspNetCore.Http.Extensions { /// <summary> /// A helper class for constructing encoded Uris for use in headers and other Uris. /// </summary> public static class UriHelper { private const char ForwardSlash = '/'; private const char Hash = '#'; private const char QuestionMark = '?'; private static readonly string SchemeDelimiter = Uri.SchemeDelimiter; private static readonly SpanAction<char, (string scheme, string host, string pathBase, string path, string query, string fragment)> InitializeAbsoluteUriStringSpanAction = new(InitializeAbsoluteUriString); /// <summary> /// Combines the given URI components into a string that is properly encoded for use in HTTP headers. /// </summary> /// <param name="pathBase">The first portion of the request path associated with application root.</param> /// <param name="path">The portion of the request path that identifies the requested resource.</param> /// <param name="query">The query, if any.</param> /// <param name="fragment">The fragment, if any.</param> /// <returns>The combined URI components, properly encoded for use in HTTP headers.</returns> public static string BuildRelative( PathString pathBase = new PathString(), PathString path = new PathString(), QueryString query = new QueryString(), FragmentString fragment = new FragmentString()) { string combinePath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/"; return combinePath + query.ToString() + fragment.ToString(); } /// <summary> /// Combines the given URI components into a string that is properly encoded for use in HTTP headers. /// Note that unicode in the HostString will be encoded as punycode. /// </summary> /// <param name="scheme">http, https, etc.</param> /// <param name="host">The host portion of the uri normally included in the Host header. This may include the port.</param> /// <param name="pathBase">The first portion of the request path associated with application root.</param> /// <param name="path">The portion of the request path that identifies the requested resource.</param> /// <param name="query">The query, if any.</param> /// <param name="fragment">The fragment, if any.</param> /// <returns>The combined URI components, properly encoded for use in HTTP headers.</returns> public static string BuildAbsolute( string scheme, HostString host, PathString pathBase = new PathString(), PathString path = new PathString(), QueryString query = new QueryString(), FragmentString fragment = new FragmentString()) { if (scheme == null) { throw new ArgumentNullException(nameof(scheme)); } var hostText = host.ToUriComponent(); var pathBaseText = pathBase.ToUriComponent(); var pathText = path.ToUriComponent(); var queryText = query.ToUriComponent(); var fragmentText = fragment.ToUriComponent(); // PERF: Calculate string length to allocate correct buffer size for string.Create. var length = scheme.Length + Uri.SchemeDelimiter.Length + hostText.Length + pathBaseText.Length + pathText.Length + queryText.Length + fragmentText.Length; if (string.IsNullOrEmpty(pathText)) { if (string.IsNullOrEmpty(pathBaseText)) { pathText = "/"; length++; } } else if (pathBaseText.EndsWith('/')) { // If the path string has a trailing slash and the other string has a leading slash, we need // to trim one of them. // Just decrement the total length, for now. length--; } return string.Create(length, (scheme, hostText, pathBaseText, pathText, queryText, fragmentText), InitializeAbsoluteUriStringSpanAction); } /// <summary> /// Separates the given absolute URI string into components. Assumes no PathBase. /// </summary> /// <param name="uri">A string representation of the uri.</param> /// <param name="scheme">http, https, etc.</param> /// <param name="host">The host portion of the uri normally included in the Host header. This may include the port.</param> /// <param name="path">The portion of the request path that identifies the requested resource.</param> /// <param name="query">The query, if any.</param> /// <param name="fragment">The fragment, if any.</param> public static void FromAbsolute( string uri, out string scheme, out HostString host, out PathString path, out QueryString query, out FragmentString fragment) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } path = new PathString(); query = new QueryString(); fragment = new FragmentString(); var startIndex = uri.IndexOf(SchemeDelimiter, StringComparison.Ordinal); if (startIndex < 0) { throw new FormatException("No scheme delimiter in uri."); } scheme = uri.Substring(0, startIndex); // PERF: Calculate the end of the scheme for next IndexOf startIndex += SchemeDelimiter.Length; int searchIndex; var limit = uri.Length; if ((searchIndex = uri.IndexOf(Hash, startIndex)) >= 0 && searchIndex < limit) { fragment = FragmentString.FromUriComponent(uri.Substring(searchIndex)); limit = searchIndex; } if ((searchIndex = uri.IndexOf(QuestionMark, startIndex)) >= 0 && searchIndex < limit) { query = QueryString.FromUriComponent(uri.Substring(searchIndex, limit - searchIndex)); limit = searchIndex; } if ((searchIndex = uri.IndexOf(ForwardSlash, startIndex)) >= 0 && searchIndex < limit) { path = PathString.FromUriComponent(uri.Substring(searchIndex, limit - searchIndex)); limit = searchIndex; } host = HostString.FromUriComponent(uri.Substring(startIndex, limit - startIndex)); } /// <summary> /// Generates a string from the given absolute or relative Uri that is appropriately encoded for use in /// HTTP headers. Note that a unicode host name will be encoded as punycode. /// </summary> /// <param name="uri">The Uri to encode.</param> /// <returns>The encoded string version of <paramref name="uri"/>.</returns> public static string Encode(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (uri.IsAbsoluteUri) { return BuildAbsolute( scheme: uri.Scheme, host: HostString.FromUriComponent(uri), pathBase: PathString.FromUriComponent(uri), query: QueryString.FromUriComponent(uri), fragment: FragmentString.FromUriComponent(uri)); } else { return uri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped); } } /// <summary> /// Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers /// and other HTTP operations. /// </summary> /// <param name="request">The request to assemble the uri pieces from.</param> /// <returns>The encoded string version of the URL from <paramref name="request"/>.</returns> public static string GetEncodedUrl(this HttpRequest request) { return BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path, request.QueryString); } /// <summary> /// Returns the relative URI. /// </summary> /// <param name="request">The request to assemble the uri pieces from.</param> /// <returns>The path and query off of <paramref name="request"/>.</returns> public static string GetEncodedPathAndQuery(this HttpRequest request) { return BuildRelative(request.PathBase, request.Path, request.QueryString); } /// <summary> /// Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) /// suitable only for display. This format should not be used in HTTP headers or other HTTP operations. /// </summary> /// <param name="request">The request to assemble the uri pieces from.</param> /// <returns>The combined components of the request URL in a fully un-escaped form (except for the QueryString) /// suitable only for display.</returns> public static string GetDisplayUrl(this HttpRequest request) { var scheme = request.Scheme ?? string.Empty; var host = request.Host.Value ?? string.Empty; var pathBase = request.PathBase.Value ?? string.Empty; var path = request.Path.Value ?? string.Empty; var queryString = request.QueryString.Value ?? string.Empty; // PERF: Calculate string length to allocate correct buffer size for StringBuilder. var length = scheme.Length + SchemeDelimiter.Length + host.Length + pathBase.Length + path.Length + queryString.Length; return new StringBuilder(length) .Append(scheme) .Append(SchemeDelimiter) .Append(host) .Append(pathBase) .Append(path) .Append(queryString) .ToString(); } /// <summary> /// Copies the specified <paramref name="text"/> to the specified <paramref name="buffer"/> starting at the specified <paramref name="index"/>. /// </summary> /// <param name="buffer">The buffer to copy text to.</param> /// <param name="index">The buffer start index.</param> /// <param name="text">The text to copy.</param> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CopyTextToBuffer(Span<char> buffer, int index, ReadOnlySpan<char> text) { text.CopyTo(buffer.Slice(index, text.Length)); return index + text.Length; } /// <summary> /// Initializes the URI <see cref="string"/> for <see cref="BuildAbsolute(string, HostString, PathString, PathString, QueryString, FragmentString)"/>. /// </summary> /// <param name="buffer">The URI <see cref="string"/>'s <see cref="char"/> buffer.</param> /// <param name="uriParts">The URI parts.</param> private static void InitializeAbsoluteUriString(Span<char> buffer, (string scheme, string host, string pathBase, string path, string query, string fragment) uriParts) { var index = 0; var pathBaseSpan = uriParts.pathBase.AsSpan(); if (uriParts.path.Length > 0 && pathBaseSpan.Length > 0 && pathBaseSpan[^1] == '/') { // If the path string has a trailing slash and the other string has a leading slash, we need // to trim one of them. // Trim the last slahs from pathBase. The total length was decremented before the call to string.Create. pathBaseSpan = pathBaseSpan[..^1]; } index = CopyTextToBuffer(buffer, index, uriParts.scheme.AsSpan()); index = CopyTextToBuffer(buffer, index, Uri.SchemeDelimiter.AsSpan()); index = CopyTextToBuffer(buffer, index, uriParts.host.AsSpan()); index = CopyTextToBuffer(buffer, index, pathBaseSpan); index = CopyTextToBuffer(buffer, index, uriParts.path.AsSpan()); index = CopyTextToBuffer(buffer, index, uriParts.query.AsSpan()); _ = CopyTextToBuffer(buffer, index, uriParts.fragment.AsSpan()); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:35:25 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.ProjectedCategories { /// <summary> /// GaussKrugerBeijing1954 /// </summary> public class GaussKrugerBeijing1954 : CoordinateSystemCategory { #region Fields public readonly ProjectionInfo Beijing19543DegreeGKCM102E; public readonly ProjectionInfo Beijing19543DegreeGKCM105E; public readonly ProjectionInfo Beijing19543DegreeGKCM108E; public readonly ProjectionInfo Beijing19543DegreeGKCM111E; public readonly ProjectionInfo Beijing19543DegreeGKCM114E; public readonly ProjectionInfo Beijing19543DegreeGKCM117E; public readonly ProjectionInfo Beijing19543DegreeGKCM120E; public readonly ProjectionInfo Beijing19543DegreeGKCM123E; public readonly ProjectionInfo Beijing19543DegreeGKCM126E; public readonly ProjectionInfo Beijing19543DegreeGKCM129E; public readonly ProjectionInfo Beijing19543DegreeGKCM132E; public readonly ProjectionInfo Beijing19543DegreeGKCM135E; public readonly ProjectionInfo Beijing19543DegreeGKCM75E; public readonly ProjectionInfo Beijing19543DegreeGKCM78E; public readonly ProjectionInfo Beijing19543DegreeGKCM81E; public readonly ProjectionInfo Beijing19543DegreeGKCM84E; public readonly ProjectionInfo Beijing19543DegreeGKCM87E; public readonly ProjectionInfo Beijing19543DegreeGKCM90E; public readonly ProjectionInfo Beijing19543DegreeGKCM93E; public readonly ProjectionInfo Beijing19543DegreeGKCM96E; public readonly ProjectionInfo Beijing19543DegreeGKCM99E; public readonly ProjectionInfo Beijing19543DegreeGKZone25; public readonly ProjectionInfo Beijing19543DegreeGKZone26; public readonly ProjectionInfo Beijing19543DegreeGKZone27; public readonly ProjectionInfo Beijing19543DegreeGKZone28; public readonly ProjectionInfo Beijing19543DegreeGKZone29; public readonly ProjectionInfo Beijing19543DegreeGKZone30; public readonly ProjectionInfo Beijing19543DegreeGKZone31; public readonly ProjectionInfo Beijing19543DegreeGKZone32; public readonly ProjectionInfo Beijing19543DegreeGKZone33; public readonly ProjectionInfo Beijing19543DegreeGKZone34; public readonly ProjectionInfo Beijing19543DegreeGKZone35; public readonly ProjectionInfo Beijing19543DegreeGKZone36; public readonly ProjectionInfo Beijing19543DegreeGKZone37; public readonly ProjectionInfo Beijing19543DegreeGKZone38; public readonly ProjectionInfo Beijing19543DegreeGKZone39; public readonly ProjectionInfo Beijing19543DegreeGKZone40; public readonly ProjectionInfo Beijing19543DegreeGKZone41; public readonly ProjectionInfo Beijing19543DegreeGKZone42; public readonly ProjectionInfo Beijing19543DegreeGKZone43; public readonly ProjectionInfo Beijing19543DegreeGKZone44; public readonly ProjectionInfo Beijing19543DegreeGKZone45; public readonly ProjectionInfo Beijing1954GKZone13; public readonly ProjectionInfo Beijing1954GKZone13N; public readonly ProjectionInfo Beijing1954GKZone14; public readonly ProjectionInfo Beijing1954GKZone14N; public readonly ProjectionInfo Beijing1954GKZone15; public readonly ProjectionInfo Beijing1954GKZone15N; public readonly ProjectionInfo Beijing1954GKZone16; public readonly ProjectionInfo Beijing1954GKZone16N; public readonly ProjectionInfo Beijing1954GKZone17; public readonly ProjectionInfo Beijing1954GKZone17N; public readonly ProjectionInfo Beijing1954GKZone18; public readonly ProjectionInfo Beijing1954GKZone18N; public readonly ProjectionInfo Beijing1954GKZone19; public readonly ProjectionInfo Beijing1954GKZone19N; public readonly ProjectionInfo Beijing1954GKZone20; public readonly ProjectionInfo Beijing1954GKZone20N; public readonly ProjectionInfo Beijing1954GKZone21; public readonly ProjectionInfo Beijing1954GKZone21N; public readonly ProjectionInfo Beijing1954GKZone22; public readonly ProjectionInfo Beijing1954GKZone22N; public readonly ProjectionInfo Beijing1954GKZone23; public readonly ProjectionInfo Beijing1954GKZone23N; #endregion #region Constructors /// <summary> /// Creates a new instance of GaussKrugerBeijing1954 /// </summary> public GaussKrugerBeijing1954() { Beijing19543DegreeGKCM102E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM105E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM108E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM111E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM114E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM117E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM120E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM123E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM126E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM129E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM132E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM135E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM75E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM78E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM81E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM84E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM87E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM90E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM93E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM96E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM99E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone25 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=25500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone26 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=26500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone27 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=27500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone28 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=28500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone29 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=29500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone30 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=30500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone31 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=31500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone32 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=32500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone33 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=33500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone34 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=34500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone35 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=35500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone36 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=36500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone37 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=37500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone38 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=38500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone39 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=39500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone40 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=40500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone41 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=41500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone42 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=42500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone43 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=43500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone44 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=44500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone45 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=45500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone13 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=13500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone13N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone14 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=14500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone14N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone15 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=15500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone15N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone16 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=16500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone16N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone17 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=17500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone17N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone18 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=18500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone18N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone19 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=19500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone19N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone20 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=20500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone20N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone21 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=21500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone21N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone22 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=22500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone22N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone23 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=23500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone23N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM102E.Name = "Beijing_1954_3_Degree_GK_CM_102E"; Beijing19543DegreeGKCM105E.Name = "Beijing_1954_3_Degree_GK_CM_105E"; Beijing19543DegreeGKCM108E.Name = "Beijing_1954_3_Degree_GK_CM_108E"; Beijing19543DegreeGKCM111E.Name = "Beijing_1954_3_Degree_GK_CM_111E"; Beijing19543DegreeGKCM114E.Name = "Beijing_1954_3_Degree_GK_CM_114E"; Beijing19543DegreeGKCM117E.Name = "Beijing_1954_3_Degree_GK_CM_117E"; Beijing19543DegreeGKCM120E.Name = "Beijing_1954_3_Degree_GK_CM_120E"; Beijing19543DegreeGKCM123E.Name = "Beijing_1954_3_Degree_GK_CM_123E"; Beijing19543DegreeGKCM126E.Name = "Beijing_1954_3_Degree_GK_CM_126E"; Beijing19543DegreeGKCM129E.Name = "Beijing_1954_3_Degree_GK_CM_129E"; Beijing19543DegreeGKCM132E.Name = "Beijing_1954_3_Degree_GK_CM_132E"; Beijing19543DegreeGKCM135E.Name = "Beijing_1954_3_Degree_GK_CM_135E"; Beijing19543DegreeGKCM75E.Name = "Beijing_1954_3_Degree_GK_CM_75E"; Beijing19543DegreeGKCM78E.Name = "Beijing_1954_3_Degree_GK_CM_78E"; Beijing19543DegreeGKCM81E.Name = "Beijing_1954_3_Degree_GK_CM_81E"; Beijing19543DegreeGKCM84E.Name = "Beijing_1954_3_Degree_GK_CM_84E"; Beijing19543DegreeGKCM87E.Name = "Beijing_1954_3_Degree_GK_CM_87E"; Beijing19543DegreeGKCM90E.Name = "Beijing_1954_3_Degree_GK_CM_90E"; Beijing19543DegreeGKCM93E.Name = "Beijing_1954_3_Degree_GK_CM_93E"; Beijing19543DegreeGKCM96E.Name = "Beijing_1954_3_Degree_GK_CM_96E"; Beijing19543DegreeGKCM99E.Name = "Beijing_1954_3_Degree_GK_CM_99E"; Beijing19543DegreeGKZone25.Name = "Beijing_1954_3_Degree_GK_Zone_25"; Beijing19543DegreeGKZone26.Name = "Beijing_1954_3_Degree_GK_Zone_26"; Beijing19543DegreeGKZone27.Name = "Beijing_1954_3_Degree_GK_Zone_27"; Beijing19543DegreeGKZone28.Name = "Beijing_1954_3_Degree_GK_Zone_28"; Beijing19543DegreeGKZone29.Name = "Beijing_1954_3_Degree_GK_Zone_29"; Beijing19543DegreeGKZone30.Name = "Beijing_1954_3_Degree_GK_Zone_30"; Beijing19543DegreeGKZone31.Name = "Beijing_1954_3_Degree_GK_Zone_31"; Beijing19543DegreeGKZone32.Name = "Beijing_1954_3_Degree_GK_Zone_32"; Beijing19543DegreeGKZone33.Name = "Beijing_1954_3_Degree_GK_Zone_33"; Beijing19543DegreeGKZone34.Name = "Beijing_1954_3_Degree_GK_Zone_34"; Beijing19543DegreeGKZone35.Name = "Beijing_1954_3_Degree_GK_Zone_35"; Beijing19543DegreeGKZone36.Name = "Beijing_1954_3_Degree_GK_Zone_36"; Beijing19543DegreeGKZone37.Name = "Beijing_1954_3_Degree_GK_Zone_37"; Beijing19543DegreeGKZone38.Name = "Beijing_1954_3_Degree_GK_Zone_38"; Beijing19543DegreeGKZone39.Name = "Beijing_1954_3_Degree_GK_Zone_39"; Beijing19543DegreeGKZone40.Name = "Beijing_1954_3_Degree_GK_Zone_40"; Beijing19543DegreeGKZone41.Name = "Beijing_1954_3_Degree_GK_Zone_41"; Beijing19543DegreeGKZone42.Name = "Beijing_1954_3_Degree_GK_Zone_42"; Beijing19543DegreeGKZone43.Name = "Beijing_1954_3_Degree_GK_Zone_43"; Beijing19543DegreeGKZone44.Name = "Beijing_1954_3_Degree_GK_Zone_44"; Beijing19543DegreeGKZone45.Name = "Beijing_1954_3_Degree_GK_Zone_45"; Beijing1954GKZone13.Name = "Beijing_1954_GK_Zone_13"; Beijing1954GKZone13N.Name = "Beijing_1954_GK_Zone_13N"; Beijing1954GKZone14.Name = "Beijing_1954_GK_Zone_14"; Beijing1954GKZone14N.Name = "Beijing_1954_GK_Zone_14N"; Beijing1954GKZone15.Name = "Beijing_1954_GK_Zone_15"; Beijing1954GKZone15N.Name = "Beijing_1954_GK_Zone_15N"; Beijing1954GKZone16.Name = "Beijing_1954_GK_Zone_16"; Beijing1954GKZone16N.Name = "Beijing_1954_GK_Zone_16N"; Beijing1954GKZone17.Name = "Beijing_1954_GK_Zone_17"; Beijing1954GKZone17N.Name = "Beijing_1954_GK_Zone_17N"; Beijing1954GKZone18.Name = "Beijing_1954_GK_Zone_18"; Beijing1954GKZone18N.Name = "Beijing_1954_GK_Zone_18N"; Beijing1954GKZone19.Name = "Beijing_1954_GK_Zone_19"; Beijing1954GKZone19N.Name = "Beijing_1954_GK_Zone_19N"; Beijing1954GKZone20.Name = "Beijing_1954_GK_Zone_20"; Beijing1954GKZone20N.Name = "Beijing_1954_GK_Zone_20N"; Beijing1954GKZone21.Name = "Beijing_1954_GK_Zone_21"; Beijing1954GKZone21N.Name = "Beijing_1954_GK_Zone_21N"; Beijing1954GKZone22.Name = "Beijing_1954_GK_Zone_22"; Beijing1954GKZone22N.Name = "Beijing_1954_GK_Zone_22N"; Beijing1954GKZone23.Name = "Beijing_1954_GK_Zone_23"; Beijing1954GKZone23N.Name = "Beijing_1954_GK_Zone_23N"; Beijing19543DegreeGKZone28.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone29.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone30.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone31.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone32.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone33.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone34.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone35.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone36.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone37.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone38.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone39.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone40.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone41.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone42.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone43.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone44.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone45.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone13.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone13N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone14.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone14N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone15.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone15N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone16.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone16N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone17.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone17N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone18.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone18N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone19.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone19N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone20.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone20N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone21.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone21N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone22.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone22N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone23.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone23N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone28.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone29.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone30.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone31.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone32.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone33.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone34.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone35.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone36.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone37.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone38.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone39.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone40.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone41.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone42.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone43.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone44.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone45.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone13.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone13N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone14.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone14N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone15.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone15N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone16.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone16N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone17.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone17N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone18.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone18N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone19.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone19N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone20.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone20N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone21.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone21N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone22.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone22N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone23.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone23N.GeographicInfo.Datum.Name = "D_Beijing_1954"; } #endregion } } #pragma warning restore 1591
//--------------------------------------------------------------------- // <copyright file="EdmCoreModel.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Microsoft.OData.Edm.Annotations; using Microsoft.OData.Edm.Library.Annotations; namespace Microsoft.OData.Edm.Library { /// <summary> /// This is a marker interface for core model elements that do not require validation. /// </summary> internal interface IEdmValidCoreModelElement { } /// <summary> /// Provides predefined declarations relevant to EDM semantics. /// </summary> public class EdmCoreModel : EdmElement, IEdmModel, IEdmValidCoreModelElement { /// <summary> /// The default core EDM model. /// </summary> public static readonly EdmCoreModel Instance = new EdmCoreModel(); private readonly EdmValidCoreModelPrimitiveType[] primitiveTypes; private const string EdmNamespace = "Edm"; private readonly Dictionary<string, EdmPrimitiveTypeKind> primitiveTypeKinds = new Dictionary<string, EdmPrimitiveTypeKind>(); private readonly Dictionary<EdmPrimitiveTypeKind, EdmValidCoreModelPrimitiveType> primitiveTypesByKind = new Dictionary<EdmPrimitiveTypeKind, EdmValidCoreModelPrimitiveType>(); private readonly Dictionary<string, EdmValidCoreModelPrimitiveType> primitiveTypeByName = new Dictionary<string, EdmValidCoreModelPrimitiveType>(); private readonly IEdmDirectValueAnnotationsManager annotationsManager = new EdmDirectValueAnnotationsManager(); private EdmCoreModel() { var primitiveDouble = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Double", EdmPrimitiveTypeKind.Double); var primitiveSingle = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Single", EdmPrimitiveTypeKind.Single); var primitiveInt64 = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Int64", EdmPrimitiveTypeKind.Int64); var primitiveInt32 = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Int32", EdmPrimitiveTypeKind.Int32); var primitiveInt16 = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Int16", EdmPrimitiveTypeKind.Int16); var primitiveSByte = new EdmValidCoreModelPrimitiveType(EdmNamespace, "SByte", EdmPrimitiveTypeKind.SByte); var primitiveByte = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Byte", EdmPrimitiveTypeKind.Byte); var primitiveBoolean = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Boolean", EdmPrimitiveTypeKind.Boolean); var primitiveGuid = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Guid", EdmPrimitiveTypeKind.Guid); var primitiveTime = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Duration", EdmPrimitiveTypeKind.Duration); var primitiveTimeOfDay = new EdmValidCoreModelPrimitiveType(EdmNamespace, "TimeOfDay", EdmPrimitiveTypeKind.TimeOfDay); var primitiveDateTimeOffset = new EdmValidCoreModelPrimitiveType(EdmNamespace, "DateTimeOffset", EdmPrimitiveTypeKind.DateTimeOffset); var primitiveDate = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Date", EdmPrimitiveTypeKind.Date); var primitiveDecimal = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Decimal", EdmPrimitiveTypeKind.Decimal); var primitiveBinary = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Binary", EdmPrimitiveTypeKind.Binary); var primitiveString = new EdmValidCoreModelPrimitiveType(EdmNamespace, "String", EdmPrimitiveTypeKind.String); var primitiveStream = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Stream", EdmPrimitiveTypeKind.Stream); var primitiveGeography = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Geography", EdmPrimitiveTypeKind.Geography); var primitiveGeographyPoint = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeographyPoint", EdmPrimitiveTypeKind.GeographyPoint); var primitiveGeographyLineString = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeographyLineString", EdmPrimitiveTypeKind.GeographyLineString); var primitiveGeographyPolygon = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeographyPolygon", EdmPrimitiveTypeKind.GeographyPolygon); var primitiveGeographyCollection = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeographyCollection", EdmPrimitiveTypeKind.GeographyCollection); var primitiveGeographyMultiPolygon = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeographyMultiPolygon", EdmPrimitiveTypeKind.GeographyMultiPolygon); var primitiveGeographyMultiLineString = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeographyMultiLineString", EdmPrimitiveTypeKind.GeographyMultiLineString); var primitiveGeographyMultiPoint = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeographyMultiPoint", EdmPrimitiveTypeKind.GeographyMultiPoint); var primitiveGeometry = new EdmValidCoreModelPrimitiveType(EdmNamespace, "Geometry", EdmPrimitiveTypeKind.Geometry); var primitiveGeometryPoint = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeometryPoint", EdmPrimitiveTypeKind.GeometryPoint); var primitiveGeometryLineString = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeometryLineString", EdmPrimitiveTypeKind.GeometryLineString); var primitiveGeometryPolygon = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeometryPolygon", EdmPrimitiveTypeKind.GeometryPolygon); var primitiveGeometryCollection = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeometryCollection", EdmPrimitiveTypeKind.GeometryCollection); var primitiveGeometryMultiPolygon = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeometryMultiPolygon", EdmPrimitiveTypeKind.GeometryMultiPolygon); var primitiveGeometryMultiLineString = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeometryMultiLineString", EdmPrimitiveTypeKind.GeometryMultiLineString); var primitiveGeometryMultiPoint = new EdmValidCoreModelPrimitiveType(EdmNamespace, "GeometryMultiPoint", EdmPrimitiveTypeKind.GeometryMultiPoint); this.primitiveTypes = new EdmValidCoreModelPrimitiveType[] { primitiveBinary, primitiveBoolean, primitiveByte, primitiveDate, primitiveDateTimeOffset, primitiveDecimal, primitiveDouble, primitiveGuid, primitiveInt16, primitiveInt32, primitiveInt64, primitiveSByte, primitiveSingle, primitiveStream, primitiveString, primitiveTime, primitiveTimeOfDay, primitiveGeography, primitiveGeographyPoint, primitiveGeographyLineString, primitiveGeographyPolygon, primitiveGeographyCollection, primitiveGeographyMultiPolygon, primitiveGeographyMultiLineString, primitiveGeographyMultiPoint, primitiveGeometry, primitiveGeometryPoint, primitiveGeometryLineString, primitiveGeometryPolygon, primitiveGeometryCollection, primitiveGeometryMultiPolygon, primitiveGeometryMultiLineString, primitiveGeometryMultiPoint }; foreach (var primitive in this.primitiveTypes) { this.primitiveTypeKinds[primitive.Name] = primitive.PrimitiveKind; this.primitiveTypeKinds[primitive.Namespace + '.' + primitive.Name] = primitive.PrimitiveKind; this.primitiveTypesByKind[primitive.PrimitiveKind] = primitive; this.primitiveTypeByName[primitive.Namespace + '.' + primitive.Name] = primitive; this.primitiveTypeByName[primitive.Name] = primitive; } } /// <summary> /// Gets the namespace of this core model. /// </summary> public static string Namespace { get { return "Edm"; } } /// <summary> /// Gets the types defined in this core model. /// </summary> public IEnumerable<IEdmSchemaElement> SchemaElements { get { return this.primitiveTypes; } } /// <summary> /// Gets the collection of namespaces that schema elements use contained in this model. /// </summary> public IEnumerable<string> DeclaredNamespaces { get { return Enumerable.Empty<string>(); } } /// <summary> /// Gets the vocabulary annotations defined in this model. /// </summary> public IEnumerable<IEdmVocabularyAnnotation> VocabularyAnnotations { get { return Enumerable.Empty<IEdmVocabularyAnnotation>(); } } /// <summary> /// Gets the collection of models referred to by this model. /// </summary> public IEnumerable<IEdmModel> ReferencedModels { get { return Enumerable.Empty<IEdmModel>(); } } /// <summary> /// Gets the model's annotations manager. /// </summary> public IEdmDirectValueAnnotationsManager DirectValueAnnotationsManager { get { return this.annotationsManager; } } /// <summary> /// Gets the only one entity container of the model. /// </summary> public IEdmEntityContainer EntityContainer { get { return null; } } /// <summary> /// Gets a reference to a non-atomic collection type definition. /// </summary> /// <param name="elementType">Type of elements in the collection.</param> /// <returns>A new non-atomic collection type reference.</returns> public static IEdmCollectionTypeReference GetCollection(IEdmTypeReference elementType) { return new EdmCollectionTypeReference(new EdmCollectionType(elementType)); } /// <summary> /// Searches for a type with the given name in this model only and returns null if no such type exists. /// </summary> /// <param name="qualifiedName">The qualified name of the type being found.</param> /// <returns>The requested type, or null if no such type exists.</returns> public IEdmSchemaType FindDeclaredType(string qualifiedName) { EdmValidCoreModelPrimitiveType element; return this.primitiveTypeByName.TryGetValue(qualifiedName, out element) ? element : null; } /// <summary> /// Searches for bound operations based on the binding type, returns an empty enumerable if no operation exists. /// </summary> /// <param name="bindingType">Type of the binding.</param> /// <returns>A set of operations that share the binding type or empty enumerable if no such operation exists.</returns> public IEnumerable<IEdmOperation> FindDeclaredBoundOperations(IEdmType bindingType) { return Enumerable.Empty<IEdmOperation>(); } /// <summary> /// Searches for bound operations based on the qualified name and binding type, returns an empty enumerable if no operation exists. /// </summary> /// <param name="qualifiedName">The qualified name of the operation.</param> /// <param name="bindingType">Type of the binding.</param> /// <returns> /// A set of operations that share the qualified name and binding type or empty enumerable if no such operation exists. /// </returns> public IEnumerable<IEdmOperation> FindDeclaredBoundOperations(string qualifiedName, IEdmType bindingType) { return Enumerable.Empty<IEdmOperation>(); } /// <summary> /// Searches for a value term with the given name in this model and returns null if no such value term exists. /// </summary> /// <param name="qualifiedName">The qualified name of the value term being found.</param> /// <returns>The requested value term, or null if no such value term exists.</returns> public IEdmValueTerm FindDeclaredValueTerm(string qualifiedName) { return null; } /// <summary> /// Searches for operations with the given name in this model and returns an empty enumerable if no such operation exists. /// </summary> /// <param name="qualifiedName">The qualified name of the operation being found.</param> /// <returns>A set operations sharing the specified qualified name, or an empty enumerable if no such operation exists.</returns> public IEnumerable<IEdmOperation> FindDeclaredOperations(string qualifiedName) { return Enumerable.Empty<IEdmOperation>(); } /// <summary> /// Searches for any functionImport or actionImport by name and parameter names. /// </summary> /// <param name="operationImportName">The name of the operation imports to find. May be qualified with the namespace.</param> /// <param name="parameterNames">The parameter names of the parameters.</param> /// <returns>The operation imports that matches the search criteria or empty there was no match.</returns> public IEnumerable<IEdmOperationImport> FindOperationImportsByNameNonBindingParameterType(string operationImportName, IEnumerable<string> parameterNames) { return Enumerable.Empty<IEdmOperationImport>(); } /// <summary> /// Gets primitive type by kind. /// </summary> /// <param name="kind">Kind of the primitive type.</param> /// <returns>Primitive type definition.</returns> public IEdmPrimitiveType GetPrimitiveType(EdmPrimitiveTypeKind kind) { return this.GetCoreModelPrimitiveType(kind); } /// <summary> /// Gets the EdmPrimitiveTypeKind by the type name. /// </summary> /// <param name="typeName">Name of the type to look up.</param> /// <returns>EdmPrimitiveTypeKind of the type.</returns> public EdmPrimitiveTypeKind GetPrimitiveTypeKind(string typeName) { EdmPrimitiveTypeKind kind; return this.primitiveTypeKinds.TryGetValue(typeName, out kind) ? kind : EdmPrimitiveTypeKind.None; } /// <summary> /// Gets a reference to a primitive type of the specified kind. /// </summary> /// <param name="kind">Primitive kind of the type reference being created.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetPrimitive(EdmPrimitiveTypeKind kind, bool isNullable) { IEdmPrimitiveType primitiveDefinition = this.GetCoreModelPrimitiveType(kind); if (primitiveDefinition != null) { return primitiveDefinition.GetPrimitiveTypeReference(isNullable); } else { throw new InvalidOperationException(Edm.Strings.EdmPrimitive_UnexpectedKind); } } /// <summary> /// Gets a reference to the Int16 primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetInt16(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Int16), isNullable); } /// <summary> /// Gets a reference to the Int32 primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetInt32(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Int32), isNullable); } /// <summary> /// Gets a reference to the Int64 primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetInt64(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Int64), isNullable); } /// <summary> /// Gets a reference to the Boolean primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetBoolean(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Boolean), isNullable); } /// <summary> /// Gets a reference to the Byte primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetByte(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Byte), isNullable); } /// <summary> /// Gets a reference to the SByte primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetSByte(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.SByte), isNullable); } /// <summary> /// Gets a reference to the Guid primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference.</returns> public IEdmPrimitiveTypeReference GetGuid(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Guid), isNullable); } /// <summary> /// Get a reference to the Date primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new primitive type reference</returns> public IEdmPrimitiveTypeReference GetDate(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Date), isNullable); } /// <summary> /// Gets a reference to a datetime with offset primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new datetime with offset type reference.</returns> public IEdmTemporalTypeReference GetDateTimeOffset(bool isNullable) { return new EdmTemporalTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.DateTimeOffset), isNullable); } /// <summary> /// Gets a reference to a duration primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new duration type reference.</returns> public IEdmTemporalTypeReference GetDuration(bool isNullable) { return new EdmTemporalTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Duration), isNullable); } /// <summary> /// Gets a reference to a TimeOfDay primitive type definition /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new TimeOfDay type reference.</returns> public IEdmTemporalTypeReference GetTimeOfDay(bool isNullable) { return new EdmTemporalTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.TimeOfDay), isNullable); } /// <summary> /// Gets a reference to a decimal primitive type definition. /// </summary> /// <param name="precision">Precision of values of this type.</param> /// <param name="scale">Scale of values of this type.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new decimal type reference.</returns> public IEdmDecimalTypeReference GetDecimal(int? precision, int? scale, bool isNullable) { if (precision.HasValue || scale.HasValue) { // Facet values may render this reference as semantically invalid, so can't return an IEdmValidCoreModelElement. return new EdmDecimalTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Decimal), isNullable, precision, scale); } else { return new EdmDecimalTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Decimal), isNullable); } } /// <summary> /// Gets a reference to a decimal primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new decimal type reference.</returns> public IEdmDecimalTypeReference GetDecimal(bool isNullable) { return new EdmDecimalTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Decimal), isNullable); } /// <summary> /// Gets a reference to a single primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new decimal type reference.</returns> public IEdmPrimitiveTypeReference GetSingle(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Single), isNullable); } /// <summary> /// Gets a reference to a double primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new decimal type reference.</returns> public IEdmPrimitiveTypeReference GetDouble(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Double), isNullable); } /// <summary> /// Gets a reference to a stream primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new stream type reference.</returns> public IEdmPrimitiveTypeReference GetStream(bool isNullable) { return new EdmPrimitiveTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Stream), isNullable); } /// <summary> /// Gets a reference to a temporal primitive type definition. /// </summary> /// <param name="kind">Primitive kind of the type reference being created.</param> /// <param name="precision">Precision of values of this type.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new temporal type reference.</returns> public IEdmTemporalTypeReference GetTemporal(EdmPrimitiveTypeKind kind, int? precision, bool isNullable) { switch (kind) { case EdmPrimitiveTypeKind.DateTimeOffset: case EdmPrimitiveTypeKind.Duration: case EdmPrimitiveTypeKind.TimeOfDay: return new EdmTemporalTypeReference(this.GetCoreModelPrimitiveType(kind), isNullable, precision); default: throw new InvalidOperationException(Edm.Strings.EdmPrimitive_UnexpectedKind); } } /// <summary> /// Gets a reference to a temporal primitive type definition. /// </summary> /// <param name="kind">Primitive kind of the type reference being created.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new temporal type reference.</returns> public IEdmTemporalTypeReference GetTemporal(EdmPrimitiveTypeKind kind, bool isNullable) { switch (kind) { case EdmPrimitiveTypeKind.DateTimeOffset: case EdmPrimitiveTypeKind.Duration: case EdmPrimitiveTypeKind.TimeOfDay: return new EdmTemporalTypeReference(this.GetCoreModelPrimitiveType(kind), isNullable); default: throw new InvalidOperationException(Edm.Strings.EdmPrimitive_UnexpectedKind); } } /// <summary> /// Gets a reference to a binary primitive type definition. /// </summary> /// <param name="isUnbounded">Flag specifying if max length is unbounded.</param> /// <param name="maxLength">Maximum length of the type.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new binary type reference.</returns> public IEdmBinaryTypeReference GetBinary(bool isUnbounded, int? maxLength, bool isNullable) { return new EdmBinaryTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Binary), isNullable, isUnbounded, maxLength); } /// <summary> /// Gets a reference to a binary primitive type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new binary type reference.</returns> public IEdmBinaryTypeReference GetBinary(bool isNullable) { return new EdmBinaryTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.Binary), isNullable); } /// <summary> /// Gets a reference to a spatial primitive type definition. /// </summary> /// <param name="kind">Primitive kind of the type reference being created.</param> /// <param name="spatialReferenceIdentifier">Spatial Reference Identifier for the spatial type being created.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new spatial type reference.</returns> public IEdmSpatialTypeReference GetSpatial(EdmPrimitiveTypeKind kind, int? spatialReferenceIdentifier, bool isNullable) { switch (kind) { case EdmPrimitiveTypeKind.Geography: case EdmPrimitiveTypeKind.GeographyPoint: case EdmPrimitiveTypeKind.GeographyLineString: case EdmPrimitiveTypeKind.GeographyPolygon: case EdmPrimitiveTypeKind.GeographyCollection: case EdmPrimitiveTypeKind.GeographyMultiPolygon: case EdmPrimitiveTypeKind.GeographyMultiLineString: case EdmPrimitiveTypeKind.GeographyMultiPoint: case EdmPrimitiveTypeKind.Geometry: case EdmPrimitiveTypeKind.GeometryPoint: case EdmPrimitiveTypeKind.GeometryLineString: case EdmPrimitiveTypeKind.GeometryPolygon: case EdmPrimitiveTypeKind.GeometryCollection: case EdmPrimitiveTypeKind.GeometryMultiPolygon: case EdmPrimitiveTypeKind.GeometryMultiLineString: case EdmPrimitiveTypeKind.GeometryMultiPoint: return new EdmSpatialTypeReference(this.GetCoreModelPrimitiveType(kind), isNullable, spatialReferenceIdentifier); default: throw new InvalidOperationException(Edm.Strings.EdmPrimitive_UnexpectedKind); } } /// <summary> /// Gets a reference to a spatial primitive type definition. /// </summary> /// <param name="kind">Primitive kind of the type reference being created.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new spatial type reference.</returns> public IEdmSpatialTypeReference GetSpatial(EdmPrimitiveTypeKind kind, bool isNullable) { switch (kind) { case EdmPrimitiveTypeKind.Geography: case EdmPrimitiveTypeKind.GeographyPoint: case EdmPrimitiveTypeKind.GeographyLineString: case EdmPrimitiveTypeKind.GeographyPolygon: case EdmPrimitiveTypeKind.GeographyCollection: case EdmPrimitiveTypeKind.GeographyMultiPolygon: case EdmPrimitiveTypeKind.GeographyMultiLineString: case EdmPrimitiveTypeKind.GeographyMultiPoint: case EdmPrimitiveTypeKind.Geometry: case EdmPrimitiveTypeKind.GeometryPoint: case EdmPrimitiveTypeKind.GeometryLineString: case EdmPrimitiveTypeKind.GeometryPolygon: case EdmPrimitiveTypeKind.GeometryCollection: case EdmPrimitiveTypeKind.GeometryMultiPolygon: case EdmPrimitiveTypeKind.GeometryMultiLineString: case EdmPrimitiveTypeKind.GeometryMultiPoint: return new EdmSpatialTypeReference(this.GetCoreModelPrimitiveType(kind), isNullable); default: throw new InvalidOperationException(Edm.Strings.EdmPrimitive_UnexpectedKind); } } /// <summary> /// Gets a reference to a string primitive type definition. /// </summary> /// <param name="isUnbounded">Flag specifying if max length is the maximum allowable value.</param> /// <param name="maxLength">Maximum length of the type.</param> /// <param name="isUnicode">Flag specifying if the type should support unicode encoding.</param> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new string type reference.</returns> public IEdmStringTypeReference GetString(bool isUnbounded, int? maxLength, bool? isUnicode, bool isNullable) { return new EdmStringTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.String), isNullable, isUnbounded, maxLength, isUnicode); } /// <summary> /// Gets a reference to a binary string type definition. /// </summary> /// <param name="isNullable">Flag specifying if the referenced type should be nullable.</param> /// <returns>A new string type reference.</returns> public IEdmStringTypeReference GetString(bool isNullable) { return new EdmStringTypeReference(this.GetCoreModelPrimitiveType(EdmPrimitiveTypeKind.String), isNullable); } /// <summary> /// Searches for vocabulary annotations specified by this model or a referenced model for a given element. /// </summary> /// <param name="element">The annotated element.</param> /// <returns>The vocabulary annotations for the element.</returns> public IEnumerable<IEdmVocabularyAnnotation> FindDeclaredVocabularyAnnotations(IEdmVocabularyAnnotatable element) { return Enumerable.Empty<IEdmVocabularyAnnotation>(); } /// <summary> /// Finds a list of types that derive from the supplied type. /// </summary> /// <param name="baseType">The base type that derived types are being searched for.</param> /// <returns>A list of types that derive from the type.</returns> public IEnumerable<IEdmStructuredType> FindDirectlyDerivedTypes(IEdmStructuredType baseType) { return Enumerable.Empty<IEdmStructuredType>(); } private EdmValidCoreModelPrimitiveType GetCoreModelPrimitiveType(EdmPrimitiveTypeKind kind) { EdmValidCoreModelPrimitiveType definition; return this.primitiveTypesByKind.TryGetValue(kind, out definition) ? definition : null; } #region Core model types and type references private sealed class EdmValidCoreModelPrimitiveType : EdmType, IEdmPrimitiveType, IEdmValidCoreModelElement { private readonly string namespaceName; private readonly string name; private readonly EdmPrimitiveTypeKind primitiveKind; public EdmValidCoreModelPrimitiveType(string namespaceName, string name, EdmPrimitiveTypeKind primitiveKind) { this.namespaceName = namespaceName ?? string.Empty; this.name = name ?? string.Empty; this.primitiveKind = primitiveKind; } public string Name { get { return this.name; } } public string Namespace { get { return this.namespaceName; } } /// <summary> /// Gets the kind of this type. /// </summary> public override EdmTypeKind TypeKind { get { return EdmTypeKind.Primitive; } } public EdmPrimitiveTypeKind PrimitiveKind { get { return this.primitiveKind; } } public EdmSchemaElementKind SchemaElementKind { get { return EdmSchemaElementKind.TypeDefinition; } } } #endregion } }
namespace iTin.Export.Model { using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml.Serialization; using ComponentModel.Writer; using Helpers; /// <inheritdoc /> /// <summary> /// A Specialization of <see cref="T:iTin.Export.Model.BaseBehaviorModel" /> class.<br /> /// Which represents a transform file behavior. If the writer that we are using generates a Xml transform file, /// this element allows us to define their behavior. Allows indicate if you want save it, where and if Xml code generated will indented. /// </summary> /// <remarks> /// <para>Belongs to: <strong><c>Behaviors</c></strong>. For more information, please see <see cref="T:iTin.Export.Model.BehaviorsModel" />.<br /> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;TransformFile .../&gt; /// </code> /// </para> /// <para><strong>Attributes</strong></para> /// <table> /// <thead> /// <tr> /// <th>Attribute</th> /// <th>Optional</th> /// <th>Description</th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td><see cref="P:iTin.Export.Model.BaseBehaviorModel.CanExecute" /></td> /// <td align="center">Yes</td> /// <td>Determines whether executes behavior. The default is <see cref="F:iTin.Export.Model.YesNo.Yes" />.</td> /// </tr> /// <tr> /// <td><see cref="P:iTin.Export.Model.TransformFileBehaviorModel.Indented" /></td> /// <td align="center">Yes</td> /// <td>Determines whether transform the file is saved indented. The default is <see cref="F:iTin.Export.Model.YesNo.Yes" />.</td> /// </tr> /// <tr> /// <td><see cref="P:iTin.Export.Model.TransformFileBehaviorModel.Save" /></td> /// <td align="center">Yes</td> /// <td>If the writer has been designed to generate transform files, set this attribute to <see cref="F:iTin.Export.Model.YesNo.Yes" /> for get a copy of the file. The default is <see cref="F:iTin.Export.Model.YesNo.No" />.</td> /// </tr> /// <tr> /// <td><see cref="P:iTin.Export.Model.TransformFileBehaviorModel.Path" /></td> /// <td align="center">Yes</td> /// <td> /// Sets the file path of transformation, if omitted used the same output element path. To specify a relative path use the character (~). The default is "<c>Default</c>". /&gt;.<br /> /// Applies only in desktop mode. /// </td> /// </tr> /// </tbody> /// </table> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br /><see cref="T:iTin.Export.Writers.CsvWriter" /></th> /// <th>Tab-Separated Values<br /><see cref="T:iTin.Export.Writers.TsvWriter" /></th> /// <th>SQL Script<br /><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th> /// <th>XML Spreadsheet 2003<br /><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml"> /// &lt;Behaviors&gt; /// &lt;Downdload LocalCopy="Yes"/&gt; /// &lt;TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/&gt; /// &lt;/Behaviors&gt; /// </code> /// </example> public partial class TransformFileBehaviorModel { #region private constants [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const YesNo DefaultSave = YesNo.No; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const string DefaultPath = "Default"; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const YesNo DefaultIndented = YesNo.Yes; #endregion #region field members [DebuggerBrowsable(DebuggerBrowsableState.Never)] private YesNo _save; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string _path; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private YesNo _indented; #endregion #region constructor/s #region [public] TransformFileBehaviorModel(): Initializes a new instance of this class /// <inheritdoc /> /// <summary> /// Initializes a new instance of the <see cref="T:iTin.Export.Model.TransformFileBehaviorModel" /> class. /// </summary> public TransformFileBehaviorModel() { Save = DefaultSave; Path = DefaultPath; Indented = DefaultIndented; } #endregion #endregion #region public static properties #region [public] {static} (TransformFileBehaviorModel) Default: Gets a reference to default behavior /// <summary> /// Gets a reference to default behavior. /// </summary> /// <value> /// Default behavior. /// </value> public static TransformFileBehaviorModel Default => new TransformFileBehaviorModel(); #endregion #endregion #region public properties #region [public] (YesNo) Indented: Gets or sets a value that determines whether transform file is saved indented /// <summary> /// Gets or sets a value that determines whether transform file is saved indented. /// </summary> /// <value> /// <see cref="iTin.Export.Model.YesNo.Yes" /> if transform the file is saved indented; otherwise <see cref="iTin.Export.Model.YesNo.No" />. The default is <see cref="iTin.Export.Model.YesNo.Yes" />. /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;TransformFile Indented="Yes|No" .../&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter" /></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter" /></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml"> /// &lt;Behaviors&gt; /// &lt;Downdload LocalCopy="Yes"/&gt; /// &lt;TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/&gt; /// &lt;/Behaviors&gt; /// </code> /// </example> /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The value specified is outside the range of valid values.</exception> [XmlAttribute] [DefaultValue(DefaultIndented)] public YesNo Indented { get => GetStaticBindingValue(_indented.ToString()).ToUpperInvariant() == "NO" ? YesNo.No : YesNo.Yes; set { SentinelHelper.IsEnumValid(value); _indented = value; } } #endregion #region [public] (string) Path: Gets or sets the path of transformation file, applies only in desktop mode /// <summary> /// Gets or sets the path of transformation file, applies only in desktop mode. /// </summary> /// <value> /// Path of transformation file, if omitted used the same output element path. To specify a relative path use the character (~). The default is "<c>Default</c>". /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;TransformFile Path="Default|string" .../&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter" /></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter" /></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml"> /// &lt;Behaviors&gt; /// &lt;Downdload LocalCopy="Yes"/&gt; /// &lt;TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/&gt; /// &lt;/Behaviors&gt; /// </code> /// </example> /// <exception cref="T:System.ArgumentNullException">If <paramref name="value" /> is <strong>null</strong>.</exception> /// <exception cref="T:iTin.Export.Model.InvalidPathNameException">If <paramref name="value" /> is an invalid path.</exception> [XmlAttribute] [DefaultValue(DefaultPath)] public string Path { get => _path; set { SentinelHelper.ArgumentNull(value); SentinelHelper.IsFalse(RegularExpressionHelper.IsValidPath(value), new InvalidPathNameException(ErrorMessageHelper.ModelPathErrorMessage("Path", value))); _path = value; } } #endregion #region [public] (YesNo) Save: Gets or sets a value that determines whether to save the transform file /// <summary> /// Gets or sets a value that determines whether to save the transform file. /// If the writer has been designed to generate transform files, set this attribute to <see cref="iTin.Export.Model.YesNo.Yes" /> for get a copy of the file. /// </summary> /// <value> /// <see cref="iTin.Export.Model.YesNo.Yes" /> if save the transform file; otherwise <see cref="iTin.Export.Model.YesNo.No" />. The default is <see cref="iTin.Export.Model.YesNo.No" />. /// </value> /// <remarks> /// <code lang="xml" title="ITEE Object Element Usage"> /// &lt;TransformFile Indented="Yes|No" .../&gt; /// </code> /// <para> /// <para><strong>Compatibility table with native writers.</strong></para> /// <table> /// <thead> /// <tr> /// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter" /></th> /// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter" /></th> /// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th> /// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th> /// </tr> /// </thead> /// <tbody> /// <tr> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// <td align="center">X</td> /// </tr> /// </tbody> /// </table> /// A <strong><c>X</c></strong> value indicates that the writer supports this element. /// </para> /// </remarks> /// <example> /// <code lang="xml"> /// &lt;Behaviors&gt; /// &lt;Downdload LocalCopy="Yes"/&gt; /// &lt;TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/&gt; /// &lt;/Behaviors&gt; /// </code> /// </example> /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The value specified is outside the range of valid values.</exception> [XmlAttribute] [DefaultValue(DefaultSave)] public YesNo Save { get => GetStaticBindingValue(_save.ToString()).ToUpperInvariant() == "NO" ? YesNo.No : YesNo.Yes; set { SentinelHelper.IsEnumValid(value); _save = value; } } #endregion #endregion #region public override properties #region [public] {overide} (bool) IsDefault: Gets a value indicating whether this instance is default /// <inheritdoc /> /// <summary> /// Gets a value indicating whether this instance is default. /// </summary> /// <value> /// <strong>true</strong> if this instance contains the default; otherwise, <strong>false</strong>. /// </value> public override bool IsDefault => base.IsDefault && Path.Equals(DefaultPath) && Save.Equals(DefaultSave) && Indented.Equals(DefaultIndented); #endregion #endregion #region protected override methods #region [protected] {override} (void) ExecuteBehavior(IWriter, ExportSettings): Code for execute download behavior /// <summary> /// Code for execute download behavior. /// </summary> /// <param name="writer">The writer.</param> /// <param name="settings">Exporter settings.</param> protected override void ExecuteBehavior(IWriter writer, ExportSettings settings) { var isTransformFile = writer.IsTransformationFile; if (!isTransformFile) { return; } if (Save.Equals(YesNo.No)) { return; } CopyToTransformOutputDirectory(writer); } #endregion #endregion #region private static methods #region [private] {static} (void) CopyToTransformOutputDirectory(IWriter): Copy transform file to specified destination /// <summary> /// Copy transform file to specified destination. /// </summary> /// <param name="writer">The writer.</param> private static void CopyToTransformOutputDirectory(IWriter writer) { var root = writer.Provider.Input.Model; var outputDirectory = root.ResolveRelativePath(KnownRelativeFilePath.TransformFileBehaviorDir); var existOutputDirectory = Directory.Exists(outputDirectory); if (!existOutputDirectory) { Directory.CreateDirectory(outputDirectory); } var searchPattern = string.Format(CultureInfo.InvariantCulture, "*.{0}", writer.TransformFileExtension); FileHelper.CopyFiles(FileHelper.TinExportTempDirectory, outputDirectory, searchPattern, true); } #endregion #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ConversationThreadsCollectionRequest. /// </summary> public partial class ConversationThreadsCollectionRequest : BaseRequest, IConversationThreadsCollectionRequest { /// <summary> /// Constructs a new ConversationThreadsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ConversationThreadsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified ConversationThread to the collection via POST. /// </summary> /// <param name="conversationThread">The ConversationThread to add.</param> /// <returns>The created ConversationThread.</returns> public System.Threading.Tasks.Task<ConversationThread> AddAsync(ConversationThread conversationThread) { return this.AddAsync(conversationThread, CancellationToken.None); } /// <summary> /// Adds the specified ConversationThread to the collection via POST. /// </summary> /// <param name="conversationThread">The ConversationThread to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ConversationThread.</returns> public System.Threading.Tasks.Task<ConversationThread> AddAsync(ConversationThread conversationThread, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<ConversationThread>(conversationThread, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IConversationThreadsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IConversationThreadsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<ConversationThreadsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest Expand(Expression<Func<ConversationThread, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest Select(Expression<Func<ConversationThread, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IConversationThreadsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// Copyright 2013 Cultural Heritage Agency of the Netherlands, Dutch National Military Museum and Trezorix bv // // 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.Specialized; using System.IO; using System.Net; using System.Text; using System.Xml; using System.Xml.Linq; using Trezorix.Common.Web; namespace Trezorix.Checkers.Analyzer.Indexes.Solr { public class SolrIndex { // member variables private readonly string _solrUrl = ""; private readonly string _solrSearchUrl; private readonly string _solrUpdateUrl; // constructor public SolrIndex(string solrUrl) { _solrUrl = solrUrl; _solrSearchUrl = solrUrl + "/select/"; _solrUpdateUrl = _solrUrl + "/update"; } public void Update(XDocument aDoc) { string statusDescription = ""; WebPost(_solrUpdateUrl, aDoc, ref statusDescription); } /* solr 1.4 will support multiple deletes <delete> <id>05991</id> <id>06000</id> <query>office:Bridgewater</query> <query>office:Osaka</query> </delete> */ // <delete><id>05991</id></delete> public void DeleteDoc(string id) { string statusDescription = ""; WebPost(_solrUpdateUrl, "<delete><id>" + id + "</id></delete>", ref statusDescription); } public void Clear() { string statusDescription = ""; WebPost(_solrUpdateUrl, "<delete><query>*:*</query></delete>", ref statusDescription); } public void Commit(bool waitFlush = false, bool waitSearcher = true) { string statusDescription = ""; WebPost(_solrUpdateUrl, String.Format("<commit waitFlush=\"{0}\" waitSearcher=\"{1}\" />", waitFlush, waitSearcher), ref statusDescription); } public void Optimize() { string statusDescription = ""; WebPost(_solrUpdateUrl, "<optimize />", ref statusDescription); } private static HttpStatusCode WebPost(string url, XDocument doc, ref string statusDescription) { var settings = new XmlWriterSettings() { Encoding = Encoding.UTF8, OmitXmlDeclaration = true, }; return WebPost(url, (Stream request) => { using(var xmlWriter = XmlWriter.Create(request, settings)) { doc.WriteTo(xmlWriter); } }, ref statusDescription); } private static HttpStatusCode WebPost(string url, string data, ref string statusDescription) { // Uploads xml to solr, must be utf-8 data byte[] bytesToPost = Encoding.UTF8.GetBytes(data); var code = WebPost(url, bytesToPost, ref statusDescription); return code; } private static HttpStatusCode WebPost(string url, byte[] postData, ref string statusDescription) { return WebPost(url, (s) => s.Write(postData, 0, postData.Length), ref statusDescription); } private delegate void DataWriter(Stream writer); private static HttpStatusCode WebPost(string url, DataWriter writer, ref string statusDescription) { HttpStatusCode iCode; var oRequest = (HttpWebRequest)WebRequest.Create(url); oRequest.Method = "POST"; oRequest.ContentType = "text/xml"; using (var dataStream = oRequest.GetRequestStream()) { writer(dataStream); dataStream.Close(); } try { using (var oResponse = (HttpWebResponse)oRequest.GetResponse()) { statusDescription = oResponse.StatusDescription; iCode = oResponse.StatusCode; } } catch (WebException ex) { var errorResponse = (HttpWebResponse)ex.Response; var tomcatResult = GetTomcatErrorResponseMessage(errorResponse); throw new SolrIndexerException(tomcatResult, ex); } return iCode; } private static WebResponse WebGet(string url, NameValueCollection parameters) { var getUrl = url + parameters.ToQueryString(); var request = WebRequest.Create(getUrl); return request.GetResponse(); } public XDocument SolrSelectXml(NameValueCollection searchParameters) { WebResponse response; try { response = WebGet(_solrSearchUrl, searchParameters); } catch (WebException ex) { string errorMessage = GetTomcatErrorResponseMessage(ex.Response); throw new SolrIndexerException(errorMessage, ex); } return XDocument.Load(response.GetResponseStream()); } private static string GetTomcatErrorResponseMessage(WebResponse errorResponse) { if (errorResponse.ContentLength != 0) { using (var stream = errorResponse.GetResponseStream()) { if (stream != null) { using (var reader = new StreamReader(stream)) { string message = reader.ReadToEnd(); return ParseApacheTomcatErrorDescription(message); } } } } return "No error response content received from server, examine inner exception."; } // TI: perhaps put this in a util/extension method? private static string ParseApacheTomcatErrorDescription(string message) { try { int startIndex = message.IndexOf("<h1>"); int endIndex = message.IndexOf("</h1>", startIndex + 4); var desc = message.Substring(startIndex + 4, endIndex - startIndex - 4); if (!string.IsNullOrWhiteSpace(desc)) { return desc; } } catch (Exception) { ;// no uglies here, non critical code } return "Could not parse Tomcat error Description, please examine the response body: \r\n" + message; } public class SolrIndexerException : Exception { public SolrIndexerException(string message, Exception innerException) : base(message, innerException) { } } } }
using AT_Utils.UI; using UnityEngine.Events; using UnityEngine.UI; namespace CC.UI { public class TankControlsUI : TankManagerUIPart { public Button deleteButton, fullTankButton, emptyTankButton, editVolumeButton, editMaxAmountButton, editMaxMassButton; public Text resourceVolume, resourceMaxAmount, resourceAmount, resourceMaxMass, resourceMass, tankFullness; public Dropdown tankTypeDropdown, resourceDropdown; public TooltipTrigger tankTypeTooltip; public Colorizer resourceAmountColorizer; public PanelledUI volumeDisplay; public FloatController volumeEditor; private ITankInfo tank; private void updateResourcesDropdown() => resourceDropdown.options = UI_Utils.namesToOptions(tank.SupportedResources); private void updateTankTypeDropdownTooltip(string tankType) => tankTypeTooltip.SetText(tank.Manager.GetTypeInfo(tankType)); public void SetTank(ITankInfo newTank) { if(newTank == tank) return; tank = newTank; if(tank == null) return; tankTypeDropdown.SetOptionsSafe(UI_Utils.namesToOptions(tank.SupportedTypes)); updateTankTypeDropdownTooltip(tank.SupportedTypes[tankTypeDropdown.value]); updateResourcesDropdown(); UpdateDisplay(); } public void UpdateDisplay() { tankTypeDropdown.SetInteractable(tank.Manager.Capabilities.TypeChangeEnabled); editVolumeButton.SetInteractable(tank.Manager.Capabilities.VolumeChangeEnabled); editMaxAmountButton.SetInteractable(editVolumeButton.interactable); editMaxMassButton.SetInteractable(editVolumeButton.interactable); deleteButton.gameObject.SetActive(tank.Manager.Capabilities.AddRemoveEnabled); resourceVolume.text = FormatUtils.formatVolume(tank.Volume); if(tank.Valid) { editMaxAmountButton.gameObject.SetActive(true); tankFullness.gameObject.SetActive(true); fullTankButton.gameObject.SetActive(tank.Manager.Capabilities.FillEnabled); emptyTankButton.gameObject.SetActive(tank.Manager.Capabilities.EmptyEnabled); resourceMaxAmount.text = FormatUtils.formatBigValue((float)tank.MaxAmount, "u"); resourceAmount.text = FormatUtils.formatBigValue((float)tank.Amount, "u"); tankFullness.text = (tank.Amount / tank.MaxAmount).ToString("P1"); resourceAmountColorizer.SetColor(Colors.Selected1); if(tank.ResourceDensity > 0) { editMaxMassButton.gameObject.SetActive(true); resourceMass.gameObject.SetActive(true); resourceMaxMass.text = FormatUtils.formatMass((float)(tank.MaxAmount * tank.ResourceDensity)); resourceMass.text = FormatUtils.formatMass((float)(tank.Amount * tank.ResourceDensity)); } else { editMaxMassButton.gameObject.SetActive(false); resourceMass.gameObject.SetActive(false); } } else { editMaxAmountButton.gameObject.SetActive(false); editMaxMassButton.gameObject.SetActive(false); resourceMass.gameObject.SetActive(false); tankFullness.gameObject.SetActive(false); fullTankButton.gameObject.SetActive(false); emptyTankButton.gameObject.SetActive(false); resourceAmount.text = "TANK CONFIGURATION IS INVALID"; resourceAmountColorizer.SetColor(Colors.Danger); } var resourcesDropdownUpdated = false; if(!string.IsNullOrEmpty(tank.TankType) && (tankTypeDropdown.value >= tank.SupportedTypes.Count || tank.TankType != tank.SupportedTypes[tankTypeDropdown.value])) { tankTypeDropdown.SetValueWithoutNotify(tank.SupportedTypes.IndexOf(tank.TankType)); updateTankTypeDropdownTooltip(tank.TankType); updateResourcesDropdown(); resourcesDropdownUpdated = true; } // ReSharper disable once InvertIf if(!string.IsNullOrEmpty(tank.CurrentResource) && (resourceDropdown.value >= tank.SupportedResources.Count || tank.CurrentResource != tank.SupportedResources[resourceDropdown.value])) { if(!resourcesDropdownUpdated) updateResourcesDropdown(); resourceDropdown.SetValueWithoutNotify(tank.SupportedResources.IndexOf(tank.CurrentResource)); } } private void Awake() { volumeDisplay.SetActive(true); volumeEditor.SetActive(false); editVolumeButton.onClick.AddListener(showVolumeEditor); editMaxAmountButton.onClick.AddListener(showMaxAmountEditor); editMaxMassButton.onClick.AddListener(showMaxMassEditor); tankTypeDropdown.onValueChanged.AddListener(changeTankType); resourceDropdown.onValueChanged.AddListener(changeResource); fullTankButton.onClick.AddListener(fillTank); emptyTankButton.onClick.AddListener(emptyTank); deleteButton.onClick.AddListener(onDelete); } private void OnDestroy() { editVolumeButton.onClick.RemoveAllListeners(); editMaxAmountButton.onClick.RemoveAllListeners(); editMaxMassButton.onClick.RemoveAllListeners(); tankTypeDropdown.onValueChanged.RemoveAllListeners(); resourceDropdown.onValueChanged.RemoveAllListeners(); fullTankButton.onClick.RemoveAllListeners(); emptyTankButton.onClick.RemoveAllListeners(); deleteButton.onClick.RemoveAllListeners(); } private void onDelete() { if(tank.Manager.Capabilities.ConfirmRemove) DialogFactory .Danger($"Are you sure you want to <b>{Colors.Danger.Tag("delete")}</b> this tank?", deleteSelf); else deleteSelf(); } private void deleteSelf() { if(!tank.Manager.RemoveTank(tank)) return; if(managerUI != null) managerUI.UpdateDisplay(); else Destroy(gameObject); } private void hideEditor() { volumeEditor.onDoneEditing.RemoveAllListeners(); volumeEditor.SetActive(false); volumeDisplay.SetActive(true); } private void showEditor(string units, float value, float max, UnityAction<float> onDone) { volumeEditor.suffix.text = units; volumeEditor.Max = max; volumeEditor.SetStep(volumeEditor.Max / 10); volumeEditor.SetValueWithoutNotify(value); volumeEditor.onDoneEditing.AddListener(onDone); volumeDisplay.SetActive(false); volumeEditor.SetActive(true); } private void showVolumeEditor() { if(tank == null) return; showEditor( "m3", tank.Volume, tank.Volume + tank.Manager.AvailableVolume, changeTankVolume ); } private void changeTankVolume(float newVolume) { if(tank == null) return; tank.SetVolume(newVolume, true); hideEditor(); UpdateDisplay(); } private void showMaxAmountEditor() { if(tank == null) return; showEditor( "u", (float)tank.MaxAmount, tank.ResourceAmountInVolume(tank.Volume + tank.Manager.AvailableVolume), changeTankMaxAmount ); } private void changeTankMaxAmount(float newMaxAmount) { if(tank == null) return; changeTankVolume(tank.VolumeForResourceAmount(newMaxAmount)); } private void showMaxMassEditor() { if(tank == null) return; showEditor( "t", (float)(tank.MaxAmount * tank.ResourceDensity), tank.ResourceAmountInVolume(tank.Volume + tank.Manager.AvailableVolume) * tank.ResourceDensity, changeTankMaxMass ); } private void changeTankMaxMass(float newMaxMass) { if(tank == null) return; changeTankMaxAmount(newMaxMass / tank.ResourceDensity); } private void fillTank() { if(tank == null) return; tank.SetAmount((float)tank.MaxAmount); UpdateDisplay(); } private void emptyTank() { if(tank == null) return; tank.SetAmount(0); UpdateDisplay(); } private void changeTankType(int index) { if(tank == null) return; var tankType = tank.SupportedTypes[index]; tank.ChangeTankType(tankType); updateTankTypeDropdownTooltip(tankType); updateResourcesDropdown(); UpdateDisplay(); } private void changeResource(int index) { if(tank == null) return; tank.ChangeResource(tank.SupportedResources[index]); UpdateDisplay(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // Name used for AGGDECLs in the symbol table. // AggregateSymbol - a symbol representing an aggregate type. These are classes, // interfaces, and structs. Parent is a namespace or class. Children are methods, // properties, and member variables, and types (including its own AGGTYPESYMs). internal class AggregateSymbol : NamespaceOrAggregateSymbol { public Type AssociatedSystemType; public Assembly AssociatedAssembly; // This InputFile is some infile for the assembly containing this AggregateSymbol. // It is used for fast access to the filter BitSet and assembly ID. private InputFile _infile; // The instance type. Created when first needed. private AggregateType _atsInst; private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused. private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct. private TypeArray _ifaces; // The explicit base interfaces for a class or interface. private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces. private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations. private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes. private TypeManager _pTypeManager; // This is so AGGTYPESYMs can instantiate their baseClass and ifacesAll members on demand. // First UD conversion operator. This chain is for this type only (not base types). // The hasConversion flag indicates whether this or any base types have UD conversions. private MethodSymbol _pConvFirst; // ------------------------------------------------------------------------ // // Put members that are bits under here in a contiguous section. // // ------------------------------------------------------------------------ private AggKindEnum _aggKind; private bool _isLayoutError; // Whether there is a cycle in the layout for the struct // Where this came from - fabricated, source, import // Fabricated AGGs have isSource == true but hasParseTree == false. // N.B.: in incremental builds, it is quite possible for // isSource==TRUE and hasParseTree==FALSE. Be // sure you use the correct variable for what you are trying to do! private bool _isSource; // This class is defined in source, although the // source might not be being read during this compile. // Predefined private bool _isPredefined; // A special predefined type. private PredefinedType _iPredef; // index of the predefined type, if isPredefined. // Flags private bool _isAbstract; // Can it be instantiated? private bool _isSealed; // Can it be derived from? // Attribute private bool _isUnmanagedStruct; // Set if the struct is known to be un-managed (for unsafe code). Set in FUNCBREC. private bool _isManagedStruct; // Set if the struct is known to be managed (for unsafe code). Set during import. // Constructors private bool _hasPubNoArgCtor; // Whether it has a public instance ructor taking no args // private struct members should not be checked for assignment or references private bool _hasExternReference; // User defined operators private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate). private bool _isComImport; // Does it have [ComImport] private bool _isAnonymousType; // true if the class is an anonymous type // When this is unset we don't know if we have conversions. When this // is set it indicates if this type or any base type has user defined // conversion operators private bool? _hasConversion; // ---------------------------------------------------------------------------- // AggregateSymbol // ---------------------------------------------------------------------------- public AggregateSymbol GetBaseAgg() { return _pBaseClass == null ? null : _pBaseClass.getAggregate(); } public AggregateType getThisType() { if (_atsInst == null) { Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested()); AggregateType pOuterType = this.isNested() ? GetOuterAgg().getThisType() : null; _atsInst = _pTypeManager.GetAggregate(this, pOuterType, GetTypeVars()); } //Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count); return _atsInst; } public void InitFromInfile(InputFile infile) { _infile = infile; _isSource = infile.isSource; } public bool FindBaseAgg(AggregateSymbol agg) { for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg()) { if (aggT == agg) return true; } return false; } public NamespaceOrAggregateSymbol Parent { get { return parent.AsNamespaceOrAggregateSymbol(); } } public new AggregateDeclaration DeclFirst() { return (AggregateDeclaration)base.DeclFirst(); } public AggregateDeclaration DeclOnly() { //Debug.Assert(DeclFirst() != null && DeclFirst().DeclNext() == null); return DeclFirst(); } public bool InAlias(KAID aid) { Debug.Assert(_infile != null); //Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID()); Debug.Assert(0 <= aid); if (aid < KAID.kaidMinModule) return _infile.InAlias(aid); return (aid == GetModuleID()); } public KAID GetModuleID() { return 0; } public KAID GetAssemblyID() { Debug.Assert(_infile != null); //Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID()); return _infile.GetAssemblyID(); } public bool IsUnresolved() { return _infile != null && _infile.GetAssemblyID() == KAID.kaidUnresolved; } public bool isNested() { return parent != null && parent.IsAggregateSymbol(); } public AggregateSymbol GetOuterAgg() { return parent != null && parent.IsAggregateSymbol() ? parent.AsAggregateSymbol() : null; } public bool isPredefAgg(PredefinedType pt) { return _isPredefined && (PredefinedType)_iPredef == pt; } // ---------------------------------------------------------------------------- // The following are the Accessor functions for AggregateSymbol. // ---------------------------------------------------------------------------- public AggKindEnum AggKind() { return (AggKindEnum)_aggKind; } public void SetAggKind(AggKindEnum aggKind) { // NOTE: When importing can demote types: // - enums with no underlying type go to struct // - delegates which are abstract or have no .ctor/Invoke method goto class _aggKind = aggKind; //An interface is always abstract if (aggKind == AggKindEnum.Interface) { this.SetAbstract(true); } } public bool IsClass() { return AggKind() == AggKindEnum.Class; } public bool IsDelegate() { return AggKind() == AggKindEnum.Delegate; } public bool IsInterface() { return AggKind() == AggKindEnum.Interface; } public bool IsStruct() { return AggKind() == AggKindEnum.Struct; } public bool IsEnum() { return AggKind() == AggKindEnum.Enum; } public bool IsValueType() { return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum; } public bool IsRefType() { return AggKind() == AggKindEnum.Class || AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate; } public bool IsStatic() { return (_isAbstract && _isSealed); } public bool IsAnonymousType() { return _isAnonymousType; } public void SetAnonymousType(bool isAnonymousType) { _isAnonymousType = isAnonymousType; } public bool IsAbstract() { return _isAbstract; } public void SetAbstract(bool @abstract) { _isAbstract = @abstract; } public bool IsPredefined() { return _isPredefined; } public void SetPredefined(bool predefined) { _isPredefined = predefined; } public PredefinedType GetPredefType() { return (PredefinedType)_iPredef; } public void SetPredefType(PredefinedType predef) { _iPredef = predef; } public bool IsLayoutError() { return _isLayoutError == true; } public void SetLayoutError(bool layoutError) { _isLayoutError = layoutError; } public bool IsSealed() { return _isSealed == true; } public void SetSealed(bool @sealed) { _isSealed = @sealed; } //////////////////////////////////////////////////////////////////////////////// public bool HasConversion(SymbolLoader pLoader) { pLoader.RuntimeBinderSymbolTable.AddConversionsForType(AssociatedSystemType); if (!_hasConversion.HasValue) { // ok, we tried defining all the conversions, and we didn't get anything // for this type. However, we will still think this type has conversions // if it's base type has conversions. _hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion(pLoader); } return _hasConversion.Value; } //////////////////////////////////////////////////////////////////////////////// public void SetHasConversion() { _hasConversion = true; } //////////////////////////////////////////////////////////////////////////////// public bool IsUnmanagedStruct() { return _isUnmanagedStruct == true; } public void SetUnmanagedStruct(bool unmanagedStruct) { _isUnmanagedStruct = unmanagedStruct; } public bool IsManagedStruct() { return _isManagedStruct == true; } public void SetManagedStruct(bool managedStruct) { _isManagedStruct = managedStruct; } public bool IsKnownManagedStructStatus() { Debug.Assert(this.IsStruct()); Debug.Assert(!IsManagedStruct() || !IsUnmanagedStruct()); return IsManagedStruct() || IsUnmanagedStruct(); } public bool HasPubNoArgCtor() { return _hasPubNoArgCtor == true; } public void SetHasPubNoArgCtor(bool hasPubNoArgCtor) { _hasPubNoArgCtor = hasPubNoArgCtor; } public bool HasExternReference() { return _hasExternReference == true; } public void SetHasExternReference(bool hasExternReference) { _hasExternReference = hasExternReference; } public bool IsSkipUDOps() { return _isSkipUDOps == true; } public void SetSkipUDOps(bool skipUDOps) { _isSkipUDOps = skipUDOps; } public void SetComImport(bool comImport) { _isComImport = comImport; } public bool IsSource() { return _isSource == true; } public TypeArray GetTypeVars() { return _typeVarsThis; } public void SetTypeVars(TypeArray typeVars) { if (typeVars == null) { _typeVarsThis = null; _typeVarsAll = null; } else { TypeArray outerTypeVars; if (this.GetOuterAgg() != null) { Debug.Assert(this.GetOuterAgg().GetTypeVars() != null); Debug.Assert(this.GetOuterAgg().GetTypeVarsAll() != null); outerTypeVars = this.GetOuterAgg().GetTypeVarsAll(); } else { outerTypeVars = BSYMMGR.EmptyTypeArray(); } _typeVarsThis = typeVars; _typeVarsAll = _pTypeManager.ConcatenateTypeArrays(outerTypeVars, typeVars); } } public TypeArray GetTypeVarsAll() { return _typeVarsAll; } public AggregateType GetBaseClass() { return _pBaseClass; } public void SetBaseClass(AggregateType baseClass) { _pBaseClass = baseClass; } public AggregateType GetUnderlyingType() { return _pUnderlyingType; } public void SetUnderlyingType(AggregateType underlyingType) { _pUnderlyingType = underlyingType; } public TypeArray GetIfaces() { return _ifaces; } public void SetIfaces(TypeArray ifaces) { _ifaces = ifaces; } public TypeArray GetIfacesAll() { return _ifacesAll; } public void SetIfacesAll(TypeArray ifacesAll) { _ifacesAll = ifacesAll; } public TypeManager GetTypeManager() { return _pTypeManager; } public void SetTypeManager(TypeManager typeManager) { _pTypeManager = typeManager; } public MethodSymbol GetFirstUDConversion() { return _pConvFirst; } public void SetFirstUDConversion(MethodSymbol conv) { _pConvFirst = conv; } public new bool InternalsVisibleTo(Assembly assembly) { return _pTypeManager.InternalsVisibleTo(AssociatedAssembly, assembly); } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComSale.Order.DS { public class SO_ConfirmShipMasterDS { private const string THIS = "PCSComSale.Order.DS.SO_ConfirmShipMasterDS"; public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { SO_ConfirmShipMasterVO objObject = (SO_ConfirmShipMasterVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO SO_ConfirmShipMaster(" + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + "," + SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD + "," + SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD + "," + SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD + "," + SO_ConfirmShipMasterTable.CCNID_FLD + ")" + "VALUES(?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD].Value = objObject.ConfirmShipNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD].Value = objObject.ShippedDate; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + SO_ConfirmShipMasterTable.TABLE_NAME + " WHERE " + "ConfirmShipMasterID" + "=" + pintID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD + "," + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + "," + SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD + "," + SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD + "," + SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD + "," + SO_ConfirmShipMasterTable.CCNID_FLD + " FROM " + SO_ConfirmShipMasterTable.TABLE_NAME + " WHERE " + SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); SO_ConfirmShipMasterVO objObject = new SO_ConfirmShipMasterVO(); while (odrPCS.Read()) { objObject.ConfirmShipMasterID = int.Parse(odrPCS[SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD].ToString().Trim()); objObject.ConfirmShipNo = odrPCS[SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD].ToString().Trim(); objObject.ShippedDate = DateTime.Parse(odrPCS[SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD].ToString().Trim()); objObject.SaleOrderMasterID = int.Parse(odrPCS[SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD].ToString().Trim()); objObject.MasterLocationID = int.Parse(odrPCS[SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[SO_ConfirmShipMasterTable.CCNID_FLD].ToString().Trim()); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; SO_ConfirmShipMasterVO objObject = (SO_ConfirmShipMasterVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE SO_ConfirmShipMaster SET " + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.CURRENCYID_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.EXCHANGERATE_FLD + "= ?" + "," //+ SO_ConfirmShipMasterTable.GATEID_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.SHIPCODE_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.FROMPORT_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.CNO_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.MEASUREMENT_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.NETWEIGHT_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.ISSUINGBANK_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.LCNO_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.VESSELNAME_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.COMMENT_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.REFERENCENO_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.INVOICENO_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.LCDATE_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.ONBOARDDATE_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.INVOICEDATE_FLD + "= ?" + "," + SO_ConfirmShipMasterTable.CCNID_FLD + "= ?" + " WHERE " + SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD].Value = objObject.ConfirmShipNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD].Value = objObject.ShippedDate; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CURRENCYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate; // ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.GATEID_FLD, OleDbType.Integer)); // if (objObject.GateID != 0) // { // ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GATEID_FLD].Value = objObject.GateID; // } // else // ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GATEID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SHIPCODE_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SHIPCODE_FLD].Value = objObject.ShipCode; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.FROMPORT_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.FROMPORT_FLD].Value = objObject.FromPort; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CNO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CNO_FLD].Value = objObject.CNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.MEASUREMENT_FLD, OleDbType.Decimal)); if (objObject.Measurement != 0) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.MEASUREMENT_FLD].Value = objObject.Measurement; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.MEASUREMENT_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD, OleDbType.Decimal)); if (objObject.GrossWeight != 0) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD].Value = objObject.GrossWeight; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.NETWEIGHT_FLD, OleDbType.Decimal)); if (objObject.NetWeight != 0) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.NETWEIGHT_FLD].Value = objObject.NetWeight; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.NETWEIGHT_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.ISSUINGBANK_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.ISSUINGBANK_FLD].Value = objObject.IssuingBank; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.LCNO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.LCNO_FLD].Value = objObject.LCNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.VESSELNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.VESSELNAME_FLD].Value = objObject.VesselName; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.COMMENT_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.COMMENT_FLD].Value = objObject.Comment; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.REFERENCENO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.REFERENCENO_FLD].Value = objObject.ReferenceNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.INVOICENO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.INVOICENO_FLD].Value = objObject.InvoiceNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.LCDATE_FLD, OleDbType.Date)); if (objObject.LCDate != DateTime.MinValue) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.LCDATE_FLD].Value = objObject.LCDate; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.LCDATE_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.ONBOARDDATE_FLD, OleDbType.Date)); if (objObject.OnBoardDate != DateTime.MinValue) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.ONBOARDDATE_FLD].Value = objObject.OnBoardDate; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.ONBOARDDATE_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.INVOICEDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.INVOICEDATE_FLD].Value = objObject.InvoiceDate; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD].Value = objObject.ConfirmShipMasterID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD + "," + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + "," + SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD + "," + SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD + "," + SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD + "," + SO_ConfirmShipMasterTable.CCNID_FLD + " FROM " + SO_ConfirmShipMasterTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, SO_ConfirmShipMasterTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD + "," + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + "," + SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD + "," + SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD + "," + SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD + "," + SO_ConfirmShipMasterTable.CCNID_FLD + " FROM " + SO_ConfirmShipMasterTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, SO_ConfirmShipMasterTable.TABLE_NAME); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet GetCommitedDelSchLines(int pintSOMasterId, string strGateIDs, DateTime pdtmFromDate, DateTime pdtmToDate, int locationId, int binId, int type) { const string METHOD_NAME = THIS + ".GetCommitedDelSchLines()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = " SELECT CA.Code ITM_CategoryCode, D.Code PartNo, D.Description, D.Revision," + " F.Code UMCode, B.SaleOrderDetailID, A.DeliveryScheduleID, D.ProductID, " + " A.ScheduleDate, G.Code SO_GateCode, DeliveryQuantity AS CommittedQuantity," + " DeliveryQuantity InvoiceQty, 0.0 OldInvoiceQty, ISNULL(D.AllowNegativeQty,0) AllowNegativeQty," + " ISNULL(BC.OHQuantity,0) AvailableQty, " + " B.UnitPrice Price, DeliveryQuantity * B.UnitPrice NetAmount," + " B.VATPercent, DeliveryQuantity * ISNULL(B.VATPercent,0) * B.UnitPrice VATAmount," + locationId + " LocationID, " + binId + " BINID , C.Code, B.SaleOrderLine, A.Line" + " FROM SO_DeliverySchedule A INNER JOIN SO_SaleOrderDetail B ON A.SaleOrderDetailID = B.SaleOrderDetailID" + " INNER JOIN SO_SaleOrderMaster C ON B.SaleOrderMasterID = C.SaleOrderMasterID" + " INNER JOIN ITM_Product D ON B.ProductID = D.ProductID" + " LEFT JOIN ITM_Category CA ON CA.CategoryID = D.CategoryID" + " LEFT JOIN SO_Gate G ON G.GateID = A.GateID" + " INNER JOIN MST_UnitOfMeasure F ON B.SellingUMID = F.UnitOfMeasureID" + " LEFT JOIN IV_BinCache BC ON D.ProductID = BC.ProductID AND BC.BinID = " + binId + " WHERE C.SaleOrderMasterID = ?" + " AND A.ScheduleDate >= ?" + " AND A.ScheduleDate <= ?" + " AND A.DeliveryScheduleID NOT IN"; if (type == (int)ShipViewType.PrintInvoice) { strSql += " (SELECT DISTINCT DeliveryScheduleID FROM SO_InvoiceDetail)"; } else { strSql += string.Format(" (SELECT DISTINCT DeliveryScheduleID FROM {0})", SO_ConfirmShipDetailTable.TABLE_NAME); } if (strGateIDs != string.Empty) { strSql += " AND A." + SO_DeliveryScheduleTable.GATEID_FLD + " IN (" + strGateIDs + ")"; } oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.Parameters.AddWithValue(SO_SaleOrderMasterTable.SALEORDERMASTERID_FLD, pintSOMasterId); ocmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate == DateTime.MinValue ? DateTime.Now : pdtmFromDate; ocmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate == DateTime.MinValue ? DateTime.Now : pdtmToDate; OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int AddReturnID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".AddReturnID()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; object objScalar = null; try { SO_ConfirmShipMasterVO objObject = (SO_ConfirmShipMasterVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO SO_ConfirmShipMaster(" + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + "," + SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD + "," + SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD + "," + SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD + "," + SO_ConfirmShipMasterTable.CURRENCYID_FLD + "," + SO_ConfirmShipMasterTable.EXCHANGERATE_FLD + "," //+ SO_ConfirmShipMasterTable.GATEID_FLD + "," + SO_ConfirmShipMasterTable.SHIPCODE_FLD + "," + SO_ConfirmShipMasterTable.FROMPORT_FLD + "," + SO_ConfirmShipMasterTable.CNO_FLD + "," + SO_ConfirmShipMasterTable.MEASUREMENT_FLD + "," + SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD + "," + SO_ConfirmShipMasterTable.NETWEIGHT_FLD + "," + SO_ConfirmShipMasterTable.ISSUINGBANK_FLD + "," + SO_ConfirmShipMasterTable.LCNO_FLD + "," + SO_ConfirmShipMasterTable.VESSELNAME_FLD + "," + SO_ConfirmShipMasterTable.COMMENT_FLD + "," + SO_ConfirmShipMasterTable.REFERENCENO_FLD + "," + SO_ConfirmShipMasterTable.INVOICENO_FLD + "," + SO_ConfirmShipMasterTable.LCDATE_FLD + "," + SO_ConfirmShipMasterTable.ONBOARDDATE_FLD + "," + SO_ConfirmShipMasterTable.INVOICEDATE_FLD + "," + SO_ConfirmShipMasterTable.CCNID_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" + " SELECT @@IDENTITY"; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD].Value = objObject.ConfirmShipNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SHIPPEDDATE_FLD].Value = objObject.ShippedDate; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CURRENCYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate; // ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.GATEID_FLD, OleDbType.Integer)); // if (objObject.GateID != 0) // { // ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GATEID_FLD].Value = objObject.GateID; // } // else // ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GATEID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.SHIPCODE_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.SHIPCODE_FLD].Value = objObject.ShipCode; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.FROMPORT_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.FROMPORT_FLD].Value = objObject.FromPort; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CNO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CNO_FLD].Value = objObject.CNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.MEASUREMENT_FLD, OleDbType.Decimal)); if (objObject.Measurement != 0) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.MEASUREMENT_FLD].Value = objObject.Measurement; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.MEASUREMENT_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD, OleDbType.Decimal)); if (objObject.GrossWeight != 0) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD].Value = objObject.GrossWeight; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.GROSSWEIGHT_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.NETWEIGHT_FLD, OleDbType.Decimal)); if (objObject.NetWeight != 0) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.NETWEIGHT_FLD].Value = objObject.NetWeight; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.NETWEIGHT_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.ISSUINGBANK_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.ISSUINGBANK_FLD].Value = objObject.IssuingBank; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.LCNO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.LCNO_FLD].Value = objObject.LCNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.VESSELNAME_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.VESSELNAME_FLD].Value = objObject.VesselName; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.COMMENT_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.COMMENT_FLD].Value = objObject.Comment; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.REFERENCENO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.REFERENCENO_FLD].Value = objObject.ReferenceNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.INVOICENO_FLD, OleDbType.WChar)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.INVOICENO_FLD].Value = objObject.InvoiceNo; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.LCDATE_FLD, OleDbType.Date)); if (objObject.LCDate != DateTime.MinValue) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.LCDATE_FLD].Value = objObject.LCDate; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.LCDATE_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.ONBOARDDATE_FLD, OleDbType.Date)); if (objObject.OnBoardDate != DateTime.MinValue) { ocmdPCS.Parameters[SO_ConfirmShipMasterTable.ONBOARDDATE_FLD].Value = objObject.OnBoardDate; } else ocmdPCS.Parameters[SO_ConfirmShipMasterTable.ONBOARDDATE_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.INVOICEDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.INVOICEDATE_FLD].Value = objObject.InvoiceDate; ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[SO_ConfirmShipMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); objScalar = ocmdPCS.ExecuteScalar(); return int.Parse(objScalar.ToString()); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using Discord.Commands; using System.Net; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using BotMyst.Data; using BotMyst.Helpers; namespace BotMyst.Commands { [Summary ("Get dictionary entries about a word. You can also get synonyms and antonyms for a word.")] public class DictionaryCommands : ModuleBase { private string AppID { get { return BotMyst.BotMystConfig.DictionaryAppID; } } private string AppKey { get { return BotMyst.BotMystConfig.DictionaryAppKey; } } [Command ("dictionary"), Summary ("Gets the dictionary information about a word.")] [Alias ("dict")] public async Task Dictionary (string word) { string url = $"https://od-api.oxforddictionaries.com:443/api/v1/entries/en/{word.ToLower ()}"; string json = await FetchJson (url); if (string.IsNullOrEmpty (json)) return; DictionaryData data = DictionaryData.FromJson (json); string finalMessage = string.Empty; bool hasData = false; DictionaryResult result = data.Results [0]; finalMessage += $"**{result.Word.ToUpper ()}**\n"; if (result.LexicalEntries [0].Pronunciations != null) { finalMessage += $"/{result.LexicalEntries [0].Pronunciations [0].PhoneticSpelling}/\n\n"; hasData = true; } foreach (DictionaryLexicalEntry lexicalEntry in result.LexicalEntries ?? Enumerable.Empty<DictionaryLexicalEntry> ()) { finalMessage += $"**{lexicalEntry.LexicalCategory.UppercaseFirst ()}**\n"; foreach (DictionaryEntry entry in lexicalEntry.Entries ?? Enumerable.Empty<DictionaryEntry> ()) { for (int j = 0; j < entry.Senses.Length; j++) { DictionarySense sense = entry.Senses [j]; foreach (string definition in sense.Definitions ?? Enumerable.Empty<string> ()) { finalMessage += $"{j + 1}. {definition.UppercaseFirst ()}\n"; hasData = true; } foreach (DictionaryExample example in sense.Examples ?? Enumerable.Empty<DictionaryExample> ()) { finalMessage += $" {example.Text.UppercaseFirst ()}\n"; hasData = true; } finalMessage += "\n"; } } } if (finalMessage.Length >= 2000 && hasData) { IEnumerable<string> messages = finalMessage.SplitEveryNth (2000); foreach (string message in messages) { await ReplyAsync (message); } return; } else if (hasData) { await ReplyAsync (finalMessage); } else { await ReplyAsync ($"No data found for: {word}."); } } [Command ("thesaurus"), Summary ("Gets the synonyms and antonyms for a specified word.")] [Alias ("word", "synonym", "antonym")] public async Task Thesaurus (string word) { string url = $"https://od-api.oxforddictionaries.com:443/api/v1/entries/en/{word.ToLower ()}/synonyms;antonyms"; string json = await FetchJson (url); if (string.IsNullOrEmpty (json)) return; ThesaurusData data = ThesaurusData.FromJson (json); string finalMessage = string.Empty; ThesaurusResult result = data.Results [0]; finalMessage += $"**{result.Word.ToUpper ()}**\n\n"; foreach (ThesaurusLexicalEntry lexicalEntry in result.LexicalEntries ?? Enumerable.Empty<ThesaurusLexicalEntry> ()) { foreach (ThesaurusEntry entry in lexicalEntry.Entries ?? Enumerable.Empty<ThesaurusEntry> ()) { int nOfSenses = 1; foreach (ThesaurusSense sense in entry.Senses ?? Enumerable.Empty<ThesaurusSense> ()) { if (sense.Examples != null) finalMessage += $"{nOfSenses}. \"{sense.Examples [0].Text.UppercaseFirst ()}\"\n"; else finalMessage += $"{nOfSenses}.\n"; if (sense.Synonyms != null || sense.Synonyms.Length >= 1) { finalMessage += "**Synonyms**\n"; } string synonyms = string.Empty; foreach (DictionaryOnym onym in sense.Synonyms ?? Enumerable.Empty<DictionaryOnym> ()) { synonyms += $"{onym.Text}, "; } if (string.IsNullOrEmpty (synonyms) == false) { finalMessage += $" {synonyms.Remove (synonyms.Length - 2).UppercaseFirst ()}\n"; } foreach (ThesaurusSense subsense in sense.Subsenses ?? Enumerable.Empty<ThesaurusSense> ()) { finalMessage += " "; if (subsense.Regions != null) { if (subsense.Regions [0] != null) { finalMessage += $"___{subsense.Regions [0].UppercaseFirst ()}___ "; } } if (subsense.Registers != null) { if (subsense.Registers [0] != null) { finalMessage += $"___{subsense.Registers [0].UppercaseFirst ()}___ "; } } string ssynonyms = string.Empty; foreach (DictionaryOnym onym in subsense.Synonyms ?? Enumerable.Empty<DictionaryOnym> ()) { ssynonyms += $"{onym.Text}, "; } if (string.IsNullOrEmpty (ssynonyms) == false) { finalMessage += $"{ssynonyms.Remove (ssynonyms.Length - 2).UppercaseFirst ()}\n"; } } if (sense.Antonyms != null) { if (sense.Antonyms.Length > 0) { finalMessage += "\n**Antonyms**\n"; } } string antonyms = string.Empty; foreach (DictionaryOnym onym in sense.Antonyms ?? Enumerable.Empty<DictionaryOnym> ()) { antonyms += $"{onym.Text}, "; } if (string.IsNullOrEmpty (antonyms) == false) { finalMessage += $" {antonyms.Remove (antonyms.Length - 2).UppercaseFirst ()}\n"; } foreach (ThesaurusSense subsense in sense.Subsenses ?? Enumerable.Empty<ThesaurusSense> ()) { string santonyms = string.Empty; foreach (DictionaryOnym onym in subsense.Antonyms ?? Enumerable.Empty<DictionaryOnym> ()) { santonyms += $"{onym.Text}, "; } if (string.IsNullOrEmpty (santonyms)) { continue; } finalMessage += " "; if (subsense.Regions != null) { if (subsense.Regions [0] != null) { finalMessage += $"___{subsense.Regions [0].UppercaseFirst ()}___ "; } } if (subsense.Registers != null) { if (subsense.Registers [0] != null) { finalMessage += $"___{subsense.Registers [0].UppercaseFirst ()}___ "; } } if (string.IsNullOrEmpty (santonyms) == false) { finalMessage += $"{santonyms.Remove (santonyms.Length - 2).UppercaseFirst ()}\n"; } } finalMessage += "\n"; nOfSenses++; } } } if (finalMessage.Length >= 2000) { IEnumerable<string> messages = finalMessage.SplitEveryNth (2000); foreach (string message in messages) { await ReplyAsync (message); } return; } await ReplyAsync (finalMessage); } private async Task<string> FetchJson (string url) { string json = string.Empty; HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url); request.Headers ["app_id"] = AppID; request.Headers ["app_key"] = AppKey; request.Method = "GET"; request.Accept = "application/json"; try { using (HttpWebResponse response = (HttpWebResponse) (await request.GetResponseAsync ())) { using (Stream stream = response.GetResponseStream ()) using (StreamReader reader = new StreamReader (stream)) json += await reader.ReadToEndAsync () + "\n"; } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { HttpStatusCode code = ((HttpWebResponse) e.Response).StatusCode; if (code == HttpStatusCode.NotFound) await ReplyAsync ("Word not found. Try again using a different word."); if (code == HttpStatusCode.BadRequest) await ReplyAsync ("The word contains unsupported characters. Try again using a different word."); } } return json; } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Shell.Interop; using GelUtilities = Microsoft.Internal.VisualStudio.PlatformUI.Utilities; namespace Microsoft.Samples.VisualStudio.IDE.OptionsPage { /// <summary> /// This class implements UI for the Custom options page. /// An OptionsPageCustom object provides the backing data. /// </summary> public class OptionsCompositeControl : UserControl { #region Fields private PictureBox pictureBox; private Button buttonChooseImage; private Button buttonClearImage; private OptionsPageCustom customOptionsPage; // ImageMoniker data private PictureBox bitmapPictureBox; #endregion #region Constructors public OptionsCompositeControl() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } #endregion #region Methods #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pictureBox = new System.Windows.Forms.PictureBox(); this.buttonChooseImage = new System.Windows.Forms.Button(); this.buttonClearImage = new System.Windows.Forms.Button(); this.bitmapPictureBox = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bitmapPictureBox)).BeginInit(); this.SuspendLayout(); // // pictureBox // this.pictureBox.Location = new System.Drawing.Point(16, 16); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size(264, 120); this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.pictureBox.TabIndex = 0; this.pictureBox.TabStop = false; // // buttonChooseImage // this.buttonChooseImage.Location = new System.Drawing.Point(16, 152); this.buttonChooseImage.Name = "buttonChooseImage"; this.buttonChooseImage.Size = new System.Drawing.Size(112, 23); this.buttonChooseImage.TabIndex = 1; this.buttonChooseImage.Text = global::Microsoft.Samples.VisualStudio.IDE.OptionsPage.Resources.ChooseImageButtonText; this.buttonChooseImage.Click += new System.EventHandler(this.OnChooseImage); // // buttonClearImage // this.buttonClearImage.Location = new System.Drawing.Point(160, 152); this.buttonClearImage.Name = "buttonClearImage"; this.buttonClearImage.Size = new System.Drawing.Size(96, 23); this.buttonClearImage.TabIndex = 2; this.buttonClearImage.Text = global::Microsoft.Samples.VisualStudio.IDE.OptionsPage.Resources.ButtonClearImageText; this.buttonClearImage.Click += new System.EventHandler(this.OnClearImage); // // bitmapPictureBox // this.bitmapPictureBox.Location = new System.Drawing.Point(290, 16); this.bitmapPictureBox.Name = "bitmapPictureBox"; this.bitmapPictureBox.Size = new System.Drawing.Size(32, 32); this.bitmapPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.bitmapPictureBox.TabIndex = 3; this.bitmapPictureBox.TabStop = false; // // OptionsCompositeControl // this.AllowDrop = true; this.Controls.Add(this.buttonClearImage); this.Controls.Add(this.buttonChooseImage); this.Controls.Add(this.pictureBox); this.Controls.Add(this.bitmapPictureBox); this.Name = "OptionsCompositeControl"; this.Size = new System.Drawing.Size(355, 195); // this.Load += new System.EventHandler(this.LoadMoniker); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bitmapPictureBox)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// Called whenever the 'Choose Image' button is pressed. This function summons an /// OpenFileDialog, and allows the user to select an image file to display in the /// PictureBox. Once the file has been selected, the PictureBox is refreshed. /// </summary> private void OnChooseImage(object sender, EventArgs e) { var openImageFileDialog = new OpenFileDialog(); if (openImageFileDialog.ShowDialog() == DialogResult.OK) { if (customOptionsPage != null) { customOptionsPage.CustomBitmap = openImageFileDialog.FileName; } RefreshImage(); } } /// <summary> /// Called whenever the 'Clear Image' button is pressed. This function sets /// the filename to null and refreshes the PictureBox. No image is displayed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnClearImage(object sender, EventArgs e) { if (customOptionsPage != null) { customOptionsPage.CustomBitmap = null; } RefreshImage(); } /// <summary> /// Refresh PictureBox Image data. Display the desired image(or nothing). /// </summary> /// <remarks>The image is reloaded from the file specified by CustomBitmap (full path to the file).</remarks> private void RefreshImage() { if (customOptionsPage == null) { return; } string fileName = customOptionsPage.CustomBitmap; if (!string.IsNullOrEmpty(fileName)) { try { // Avoid using Image.FromFile() method for image loading because it locks the file. using (FileStream lStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { pictureBox.Image = Image.FromStream(lStream); } } catch (IOException) { pictureBox.Image = null; } } else { pictureBox.Image = null; } } /// <summary> /// Gets or sets the reference to the underlying OptionsPage object. /// </summary> public OptionsPageCustom OptionsPage { get { return customOptionsPage; } set { customOptionsPage = value; RefreshImage(); } } /// <summary> /// Load and display an image moniker in a PictureBox /// </summary> private void LoadMoniker(object sender, EventArgs e) { IVsImageService2 imageService = (IVsImageService2)OptionsPagePackageCS.GetGlobalService(typeof(SVsImageService)); ImageAttributes attributes = new ImageAttributes { StructSize = Marshal.SizeOf(typeof(ImageAttributes)), ImageType = (uint)_UIImageType.IT_Bitmap, Format = (uint)_UIDataFormat.DF_WinForms, LogicalWidth = 32, LogicalHeight = 32, // Desired RGBA color, don't set IAF_Background below unless you also use this Background = 0xFFFFFFFF, // (uint)(_ImageAttributesFlags.IAF_RequiredFlags | _ImageAttributesFlags.IAF_Background) Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags, }; IVsUIObject uIObj = imageService.GetImage(KnownMonikers.Search, attributes); bitmapPictureBox.Image = (Bitmap)GelUtilities.GetObjectData(uIObj); } #endregion } }
/******************************************************************************\ * Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. * * Leap Motion proprietary and confidential. Not for distribution. * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * \******************************************************************************/ namespace LeapInternal { using System; using System.Runtime.InteropServices; public enum eLeapConnectionStatus : uint { eLeapConnectionStatus_NotConnected = 0, //!< // A connection has been established eLeapConnectionStatus_Connected, //!< The connection has not been completed. Call OpenConnection. eLeapConnectionStatus_HandshakeIncomplete, //!< The connection handshake has not completed eLeapConnectionStatus_NotRunning = 0xE7030004 //!< A connection could not be established because the server does not appear to be running }; public enum eLeapDeviceCaps : uint { eLeapDeviceCaps_Color = 0x00000001, //!< The device can send color images }; public enum eLeapDeviceType : uint { eLeapDeviceType_Peripheral = 0x0003, //!< The Leap Motion consumer peripheral eLeapDeviceType_Dragonfly = 0x1102, //!< Internal research product codename "Dragonfly" eLeapDeviceType_Nightcrawler = 0x1201 //!< Internal research product codename "Nightcrawler" }; public enum eDistortionMatrixType { eDistortionMatrixType_64x64 //!< A 64x64 matrix of pairs of points. }; public enum eLeapPolicyFlag : uint { eLeapPolicyFlag_BackgroundFrames = 0x00000001, //!< Allows frame receipt even when this application is not the foreground application eLeapPolicyFlag_OptimizeHMD = 0x00000004, //!< Optimize HMD Policy Flag eLeapPolicyFlag_AllowPauseResume = 0x00000008, //!< Modifies the security token to allow calls to LeapPauseDevice to succeed eLeapPolicyFlag_IncludeAllFrames = 0x00008000, //!< Include native-app frames when receiving background frames. eLeapPolicyFlag_NonExclusive = 0x00800000 //!< Allow background apps to also receive frames. }; public enum eLeapDeviceStatus : uint { eLeapDeviceStatus_Streaming = 0x00000001, //!< Presently sending frames to all clients that have requested them eLeapDeviceStatus_Paused = 0x00000002, //!< Device streaming has been paused eLeapDeviceStatus_UnknownFailure = 0xE8010000, //!< The device has failed, but the failure reason is not known eLeapDeviceStatus_BadCalibration = 0xE8010001, //!< Bad calibration, cannot send frames eLeapDeviceStatus_BadFirmware = 0xE8010002, //!< Corrupt firmware and/or cannot receive a required firmware update eLeapDeviceStatus_BadTransport = 0xE8010003, //!< Exhibiting USB communications issues eLeapDeviceStatus_BadControl = 0xE8010004, //!< Missing critical control interfaces needed for communication }; public enum eLeapImageType { eLeapImageType_Unknown = 0, eLeapImageType_Default, //!< Default processed IR image eLeapImageType_Raw //!< Image from raw sensor values }; public enum eLeapImageFormat : uint { eLeapImageFormat_UNKNOWN = 0, //!< Unknown format (shouldn't happen) eLeapImageType_IR = 0x317249, //!< An infrared image eLeapImageType_RGBIr_Bayer = 0x49425247, //!< A Bayer RGBIr image with uncorrected RGB channels }; public enum eLeapPerspectiveType { eLeapPerspectiveType_invalid = 0, //!< Reserved, invalid eLeapPerspectiveType_stereo_left = 1, //!< A canonically left image eLeapPerspectiveType_stereo_right = 2, //!< A canonically right image eLeapPerspectiveType_mono = 3, //!< Reserved for future use }; public enum eLeapImageRequestError { eLeapImageRequestError_Unknown, //!< The reason for the failure is unknown eLeapImageRequestError_ImagesDisabled, //!< Images are turned off in the user's configuration eLeapImageRequestError_Unavailable, //!< The requested images are not available eLeapImageRequestError_InsufficientBuffer, //!< The provided buffer is not large enough for the requested images } public enum eLeapHandType { eLeapHandType_Left, //!< Left hand eLeapHandType_Right //!< Right hand }; public enum eLeapLogSeverity { eLeapLogSeverity_Unknown = 0, eLeapLogSeverity_Critical, eLeapLogSeverity_Warning, eLeapLogSeverity_Information }; public enum eLeapValueType : int { eLeapValueType_Unknown, eLeapValueType_Boolean, eLeapValueType_Int32, eLeapValueType_Float, eLeapValueType_String }; public enum eLeapRS : uint { eLeapRS_Success = 0x00000000, //!< The operation completed successfully eLeapRS_UnknownError = 0xE2010000, //!< An unknown error has occurred eLeapRS_InvalidArgument = 0xE2010001, //!< An invalid argument was specified eLeapRS_InsufficientResources = 0xE2010002, //!< Insufficient resources existed to complete the request eLeapRS_InsufficientBuffer = 0xE2010003, //!< The specified buffer was not large enough to complete the request eLeapRS_Timeout = 0xE2010004, //!< The requested operation has timed out eLeapRS_NotConnected = 0xE2010005, //!< The connection is not open eLeapRS_HandshakeIncomplete = 0xE2010006, //!< The request did not succeed because the client has not finished connecting to the server eLeapRS_BufferSizeOverflow = 0xE2010007, //!< The specified buffer size is too large eLeapRS_ProtocolError = 0xE2010008, //!< A communications protocol error has occurred eLeapRS_InvalidClientID = 0xE2010009, //!< The server incorrectly specified zero as a client ID eLeapRS_UnexpectedClosed = 0xE201000A, //!< The connection to the service was unexpectedly closed while reading a message eLeapRS_CannotCancelImageFrameRequest = 0xE201000B, //!< An attempt to cancel an image request failed (either too late, or the image token was invalid) eLeapRS_NotAvailable = 0xE7010002, //!< A connection could not be established to the Leap Motion service eLeapRS_NotStreaming = 0xE7010004, //!< The requested operation can only be performed while the device is streaming /** * It is possible that the device identifier * is invalid, or that the device has been disconnected since being enumerated. */ eLeapRS_CannotOpenDevice = 0xE7010005, //!< The specified device could not be opened. Invalid device identifier or the device has been disconnected since being enumerated. }; public enum eLeapEventType { eLeapEventType_None = 0, //!< No event occurred in the specified timeout period eLeapEventType_Connection, //!< A connection event has occurred eLeapEventType_ConnectionLost, //!< The connection with the service has been lost eLeapEventType_Device, //!< A device event has occurred eLeapEventType_DeviceFailure, //!< A device failure event has occurred eLeapEventType_PolicyChange, //!< A change in policy occurred eLeapEventType_Tracking = 0x100, //!< A tracking frame has been received /** * The user must invoke LeapReceiveImage(evt->Image, ...) if image data is desired. If this call * is not made, the image will be discarded from the stream. * * Depending on the image types the user has requested, this event may be asserted more than once * per frame. */ eLeapEventType_ImageRequestError, //!< A requested image could not be acquired eLeapEventType_ImageComplete, //!< An image transfer is complete eLeapEventType_LogEvent, //!< A diagnostic event has occured /** * The eLeapEventType_DeviceLost event type will always be asserted regardless of the user flags assignment. * Users are required to correctly handle this event when it is received. * * This event is generally asserted when the device has been detached from the system, when the * connection to the service has been lost, or if the device is closed while streaming. Generally, * any event where the system can conclude no further frames will be received will cause this * method to be invoked. */ eLeapEventType_DeviceLost, //!< Event asserted when the underlying device object has been lost eLeapEventType_ConfigResponse, //!< Response to a Config value request eLeapEventType_ConfigChange, //!< Success response to a Config value change eLeapEventType_DeviceStatusChange, eLeapEventType_DroppedFrame, }; public enum eLeapDeviceFlag : uint { /** * This flag is updated when the user pauses or resumes tracking on the device from the Leap control * panel. Modification of this flag will fail if the AllowPauseResume policy is not set on this device * object. */ eLeapDeviceFlag_Stream = 0x00000001 //!< Flag set if the device is presently streaming frames }; public enum eLeapConnectionFlags : uint { eLeapConnectionFlags_Default = 0x00000000, //!< Currently there is only a default state flag. }; public enum eLeapDroppedFrameType { eLeapDroppedFrameType_PreprocessingQueue, eLeapDroppedFrameType_TrackingQueue, eLeapDroppedFrameType_Other }; //Note the following LeapC structs are just IntPtrs in C#: // LEAP_CONNECTION is an IntPtr // LEAP_DEVICE is an IntPtr // LEAP_CLOCK_REBASER is an IntPtr [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_CONNECTION_CONFIG { public UInt32 size; public UInt32 flags; public string server_namespace; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_CONNECTION_INFO { public UInt32 size; public eLeapConnectionStatus status; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_CONNECTION_EVENT { public UInt32 flags; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_DEVICE_REF { public IntPtr handle; //void * public UInt32 id; public LEAP_DEVICE_REF(IntPtr handle, UInt32 id) { this.handle = handle; this.id = id; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_CONNECTION_LOST_EVENT { public UInt32 flags; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_DEVICE_EVENT { public UInt32 flags; public LEAP_DEVICE_REF device; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_DEVICE_FAILURE_EVENT { public eLeapDeviceStatus status; public IntPtr hDevice; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_TRACKING_EVENT { public LEAP_FRAME_HEADER info; public Int64 tracking_id; public LEAP_VECTOR interaction_box_size; public LEAP_VECTOR interaction_box_center; public UInt32 nHands; public IntPtr pHands; //LEAP_HAND* public float framerate; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_DROPPED_FRAME_EVENT { public Int64 frame_id; public eLeapDroppedFrameType reason; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_CONNECTION_MESSAGE { public UInt32 size; public eLeapEventType type; public IntPtr eventStructPtr; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_DISCONNECTION_EVENT { public UInt32 reserved; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_DEVICE_INFO { public UInt32 size; public UInt32 status; public UInt32 caps; public eLeapDeviceType type; public UInt32 baseline; public UInt32 serial_length; public IntPtr serial; //char* public float h_fov; public float v_fov; public UInt32 range; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_DISTORTION_MATRIX { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2 * 64 * 64 * 2)]//2floats * 64 width * 64 height * 2 matrices public float[] matrix_data; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_FRAME_HEADER { public IntPtr reserved; public Int64 frame_id; public Int64 timestamp; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_IMAGE_FRAME_REQUEST_TOKEN { public UInt32 requestID; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_IMAGE_COMPLETE_EVENT { public LEAP_IMAGE_FRAME_REQUEST_TOKEN token; public LEAP_FRAME_HEADER info; public IntPtr properties; //LEAP_IMAGE_PROPERTIES* public UInt64 matrix_version; public IntPtr calib; //LEAP_CALIBRATION public IntPtr distortionMatrix; //LEAP_DISTORTION_MATRIX* distortion_matrix[2] public IntPtr pfnData; // void* the user-supplied buffer public UInt64 data_written; //The amount of data written to the buffer } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_IMAGE_FRAME_DESCRIPTION { public Int64 frame_id; public eLeapImageType type; public UInt64 buffer_len; public IntPtr pBuffer; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_IMAGE_FRAME_REQUEST_ERROR_EVENT { public LEAP_IMAGE_FRAME_REQUEST_TOKEN token; public eLeapImageRequestError error; public UInt64 required_buffer_len; //The required buffer size, for insufficient buffer errors public LEAP_IMAGE_FRAME_DESCRIPTION description; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_IMAGE_PROPERTIES { public eLeapImageType type; public eLeapImageFormat format; public UInt32 bpp; public UInt32 width; public UInt32 height; public float x_scale; public float y_scale; public float x_offset; public float y_offset; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_VECTOR { public float x; public float y; public float z; public Leap.Vector ToLeapVector() { return new Leap.Vector(x, y, z); } public LEAP_VECTOR(Leap.Vector leap) { x = leap.x; y = leap.y; z = leap.z; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_QUATERNION { public float x; public float y; public float z; public float w; public Leap.LeapQuaternion ToLeapQuaternion() { return new Leap.LeapQuaternion(x, y, z, w); } public LEAP_QUATERNION(Leap.LeapQuaternion q) { x = q.x; y = q.y; z = q.z; w = q.w; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_BONE { public LEAP_VECTOR prev_joint; public LEAP_VECTOR next_joint; public float width; public LEAP_QUATERNION rotation; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_DIGIT { public Int32 finger_id; public LEAP_BONE metacarpal; public LEAP_BONE proximal; public LEAP_BONE intermediate; public LEAP_BONE distal; public LEAP_VECTOR tip_velocity; public LEAP_VECTOR stabilized_tip_position; public Int32 is_extended; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_PALM { public LEAP_VECTOR position; public LEAP_VECTOR stabilized_position; public LEAP_VECTOR velocity; public LEAP_VECTOR normal; public float width; public LEAP_VECTOR direction; public LEAP_QUATERNION orientation; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_HAND { public UInt32 id; public UInt32 flags; public eLeapHandType type; public float confidence; public UInt64 visible_time; public float pinch_distance; public float grab_angle; public float pinch_strength; public float grab_strength; public LEAP_PALM palm; public LEAP_DIGIT thumb; public LEAP_DIGIT index; public LEAP_DIGIT middle; public LEAP_DIGIT ring; public LEAP_DIGIT pinky; public LEAP_BONE arm; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_TIP { public LEAP_VECTOR position; public float radius; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_LOG_EVENT { public eLeapLogSeverity severity; public Int64 timestamp; public string message; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_POLICY_EVENT { public UInt32 reserved; public UInt32 current_policy; } [StructLayout(LayoutKind.Explicit, Pack = 1)] public struct LEAP_VARIANT_VALUE_TYPE { [FieldOffset(0)] public eLeapValueType type; [FieldOffset(4)] public Int32 boolValue; [FieldOffset(4)] public Int32 intValue; [FieldOffset(4)] public float floatValue; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_VARIANT_REF_TYPE { public eLeapValueType type; public string stringValue; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_CONFIG_RESPONSE_EVENT { public UInt32 requestId; public LEAP_VARIANT_VALUE_TYPE value; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_CONFIG_RESPONSE_EVENT_WITH_REF_TYPE { public UInt32 requestId; public LEAP_VARIANT_REF_TYPE value; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LEAP_CONFIG_CHANGE_EVENT { public UInt32 requestId; public Int32 status; } public class LeapC { private LeapC() { } public static int DistortionSize = 64; [DllImport("LeapC", EntryPoint = "LeapGetNow")] public static extern long GetNow(); [DllImport("LeapC", EntryPoint = "LeapCreateClockRebaser")] public static extern eLeapRS CreateClockRebaser(out IntPtr phClockRebaser); [DllImport("LeapC", EntryPoint = "LeapDestroyClockRebaser")] public static extern eLeapRS DestroyClockRebaser(IntPtr hClockRebaser); [DllImport("LeapC", EntryPoint = "LeapUpdateRebase")] public static extern eLeapRS UpdateRebase(IntPtr hClockRebaser, Int64 userClock, Int64 leapClock); [DllImport("LeapC", EntryPoint = "LeapRebaseClock")] public static extern eLeapRS RebaseClock(IntPtr hClockRebaser, Int64 userClock, out Int64 leapClock); [DllImport("LeapC", EntryPoint = "LeapCreateConnection")] public static extern eLeapRS CreateConnection(ref LEAP_CONNECTION_CONFIG pConfig, out IntPtr pConnection); //Overrides to allow config to be set to null to use default config [DllImport("LeapC", EntryPoint = "LeapCreateConnection")] private static extern eLeapRS CreateConnection(IntPtr nulled, out IntPtr pConnection); public static eLeapRS CreateConnection(out IntPtr pConnection) { return CreateConnection(IntPtr.Zero, out pConnection); } [DllImport("LeapC", EntryPoint = "LeapGetConnectionInfo")] public static extern eLeapRS GetConnectionInfo(IntPtr hConnection, out LEAP_CONNECTION_INFO pInfo); [DllImport("LeapC", EntryPoint = "LeapOpenConnection")] public static extern eLeapRS OpenConnection(IntPtr hConnection); [DllImport("LeapC", EntryPoint = "LeapGetDeviceList")] public static extern eLeapRS GetDeviceList(IntPtr hConnection, [In, Out] LEAP_DEVICE_REF[] pArray, out UInt32 pnArray); [DllImport("LeapC", EntryPoint = "LeapGetDeviceList")] private static extern eLeapRS GetDeviceList(IntPtr hConnection, [In, Out] IntPtr pArray, out UInt32 pnArray); //Override to allow pArray argument to be set to null (IntPtr.Zero) in order to get the device count public static eLeapRS GetDeviceCount(IntPtr hConnection, out UInt32 deviceCount) { return GetDeviceList(hConnection, IntPtr.Zero, out deviceCount); } [DllImport("LeapC", EntryPoint = "LeapOpenDevice")] public static extern eLeapRS OpenDevice(LEAP_DEVICE_REF rDevice, out IntPtr pDevice); [DllImport("LeapC", EntryPoint = "LeapGetDeviceInfo", CharSet = CharSet.Ansi)] public static extern eLeapRS GetDeviceInfo(IntPtr hDevice, out LEAP_DEVICE_INFO info); [DllImport("LeapC", EntryPoint = "LeapSetPolicyFlags")] public static extern eLeapRS SetPolicyFlags(IntPtr hConnection, UInt64 set, UInt64 clear); [DllImport("LeapC", EntryPoint = "LeapSetDeviceFlags")] public static extern eLeapRS SetDeviceFlags(IntPtr hDevice, UInt64 set, UInt64 clear, out UInt64 prior); [DllImport("LeapC", EntryPoint = "LeapPollConnection")] public static extern eLeapRS PollConnection(IntPtr hConnection, UInt32 timeout, ref LEAP_CONNECTION_MESSAGE msg); [DllImport("LeapC", EntryPoint = "LeapGetFrameSize")] public static extern eLeapRS GetFrameSize(IntPtr hConnection, Int64 timestamp, out UInt64 pncbEvent); [DllImport("LeapC", EntryPoint = "LeapInterpolateFrame")] public static extern eLeapRS InterpolateFrame(IntPtr hConnection, Int64 timestamp, IntPtr pEvent, UInt64 ncbEvent); [DllImport("LeapC", EntryPoint = "LeapRequestImages")] public static extern eLeapRS RequestImages(IntPtr hConnection, ref LEAP_IMAGE_FRAME_DESCRIPTION description, out LEAP_IMAGE_FRAME_REQUEST_TOKEN pToken); [DllImport("LeapC", EntryPoint = "LeapCancelImageFrameRequest")] public static extern eLeapRS CancelImageFrameRequest(IntPtr hConnection, LEAP_IMAGE_FRAME_REQUEST_TOKEN token); [DllImport("LeapC", EntryPoint = "LeapPixelToRectilinear")] public static extern LEAP_VECTOR LeapPixelToRectilinear(IntPtr hConnection, eLeapPerspectiveType camera, LEAP_VECTOR pixel); [DllImport("LeapC", EntryPoint = "LeapRectilinearToPixel")] public static extern LEAP_VECTOR LeapRectilinearToPixel(IntPtr hConnection, eLeapPerspectiveType camera, LEAP_VECTOR rectilinear); [DllImport("LeapC", EntryPoint = "LeapCloseDevice")] public static extern void CloseDevice(IntPtr pDevice); [DllImport("LeapC", EntryPoint = "LeapDestroyConnection")] public static extern void DestroyConnection(IntPtr connection); [DllImport("LeapC", EntryPoint = "LeapSaveConfigValue")] private static extern eLeapRS SaveConfigValue(IntPtr hConnection, string key, IntPtr value, out UInt32 requestId); [DllImport("LeapC", EntryPoint = "LeapRequestConfigValue")] public static extern eLeapRS RequestConfigValue(IntPtr hConnection, string name, out UInt32 request_id); public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, bool value, out UInt32 requestId) { LEAP_VARIANT_VALUE_TYPE valueStruct = new LEAP_VARIANT_VALUE_TYPE(); //This is a C# approximation of a C union valueStruct.type = eLeapValueType.eLeapValueType_Boolean; valueStruct.boolValue = value ? 1 : 0; return LeapC.SaveConfigWithValueType(hConnection, key, valueStruct, out requestId); } public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, Int32 value, out UInt32 requestId) { LEAP_VARIANT_VALUE_TYPE valueStruct = new LEAP_VARIANT_VALUE_TYPE(); valueStruct.type = eLeapValueType.eLeapValueType_Int32; valueStruct.intValue = value; return LeapC.SaveConfigWithValueType(hConnection, key, valueStruct, out requestId); } public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, float value, out UInt32 requestId) { LEAP_VARIANT_VALUE_TYPE valueStruct = new LEAP_VARIANT_VALUE_TYPE(); valueStruct.type = eLeapValueType.eLeapValueType_Float; valueStruct.floatValue = value; return LeapC.SaveConfigWithValueType(hConnection, key, valueStruct, out requestId); } public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, string value, out UInt32 requestId) { LEAP_VARIANT_REF_TYPE valueStruct; valueStruct.type = eLeapValueType.eLeapValueType_String; valueStruct.stringValue = value; return LeapC.SaveConfigWithRefType(hConnection, key, valueStruct, out requestId); } private static eLeapRS SaveConfigWithValueType(IntPtr hConnection, string key, LEAP_VARIANT_VALUE_TYPE valueStruct, out UInt32 requestId) { IntPtr configValue = Marshal.AllocHGlobal(Marshal.SizeOf(valueStruct)); eLeapRS callResult = eLeapRS.eLeapRS_UnknownError; try { Marshal.StructureToPtr(valueStruct, configValue, false); callResult = SaveConfigValue(hConnection, key, configValue, out requestId); } finally { Marshal.FreeHGlobal(configValue); } return callResult; } private static eLeapRS SaveConfigWithRefType(IntPtr hConnection, string key, LEAP_VARIANT_REF_TYPE valueStruct, out UInt32 requestId) { IntPtr configValue = Marshal.AllocHGlobal(Marshal.SizeOf(valueStruct)); eLeapRS callResult = eLeapRS.eLeapRS_UnknownError; try { Marshal.StructureToPtr(valueStruct, configValue, false); callResult = SaveConfigValue(hConnection, key, configValue, out requestId); } finally { Marshal.FreeHGlobal(configValue); } return callResult; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_RECORDING_PARAMETERS { public UInt32 mode; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct LEAP_RECORDING_STATUS { public UInt32 mode; } [DllImport("LeapC", EntryPoint = "LeapRecordingOpen")] public static extern eLeapRS RecordingOpen(ref IntPtr ppRecording, string userPath, LEAP_RECORDING_PARAMETERS parameters); [DllImport("LeapC", EntryPoint = "LeapRecordingClose")] public static extern eLeapRS RecordingClose(ref IntPtr ppRecording); [DllImport("LeapC", EntryPoint = "LeapRecordingGetStatus")] public static extern eLeapRS LeapRecordingGetStatus(IntPtr pRecording, ref LEAP_RECORDING_STATUS status); [DllImport("LeapC", EntryPoint = "LeapRecordingReadSize")] public static extern eLeapRS RecordingReadSize(IntPtr pRecording, ref UInt64 pncbEvent); [DllImport("LeapC", EntryPoint = "LeapRecordingRead")] public static extern eLeapRS RecordingRead(IntPtr pRecording, ref LEAP_TRACKING_EVENT pEvent, UInt64 ncbEvent); [DllImport("LeapC", EntryPoint = "LeapRecordingWrite")] public static extern eLeapRS RecordingWrite(IntPtr pRecording, ref LEAP_TRACKING_EVENT pEvent, ref UInt64 pnBytesWritten); }//end LeapC } //end LeapInternal namespace
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Experimental.UI.BoundsControl; using Microsoft.MixedReality.Toolkit.UI; using UnityEngine; using Microsoft.MixedReality.Toolkit.Experimental.UI.BoundsControlTypes; using UnityEditor; using Microsoft.MixedReality.Toolkit.Utilities; namespace Microsoft.MixedReality.Toolkit.Experimental.Utilities { /// <summary> /// Migration handler for migrating bounding box gameobjects to bounds control gameobjects. /// </summary> public class BoundsControlMigrationHandler : IMigrationHandler { /// <inheritdoc /> public bool CanMigrate(GameObject gameObject) { return gameObject.GetComponent<BoundingBox>() != null; } /// <inheritdoc /> public void Migrate(GameObject gameObject) { #if UNITY_EDITOR var boundingBox = gameObject.GetComponent<BoundingBox>(); var boundsControl = gameObject.AddComponent<BoundsControl>(); boundsControl.enabled = boundingBox.enabled; { Undo.RecordObject(gameObject, "BoundsControl migration: swapping BoundingBox with BoundsControl."); // migrate logic settings boundsControl.Target = boundingBox.Target; boundsControl.BoundsOverride = boundingBox.BoundsOverride; boundsControl.CalculationMethod = MigrateCalculationMethod(boundingBox.CalculationMethod); boundsControl.BoundsControlActivation = MigrateActivationFlag(boundingBox.BoundingBoxActivation); // only carry over min max scaling values if user hasn't attached min max scale constraint component yet if (gameObject.GetComponent<MinMaxScaleConstraint>() == null) { #pragma warning disable 0618 // create a minmaxscaleconstraint in case there's a min max scale set up if (boundingBox.ScaleMinimum != 0.0f || boundingBox.ScaleMaximum != 0.0f) { MinMaxScaleConstraint scaleConstraint = gameObject.AddComponent<MinMaxScaleConstraint>(); scaleConstraint.ScaleMinimum = boundingBox.ScaleMinimum; scaleConstraint.ScaleMaximum = boundingBox.ScaleMaximum; } #pragma warning restore 0618 } // migrate visuals boundsControl.FlattenAxis = MigrateFlattenAxis(boundingBox.FlattenAxis); boundsControl.BoxPadding = boundingBox.BoxPadding; string configDir = GetBoundsControlConfigDirectory(boundingBox); MigrateBoxDisplay(boundsControl, boundingBox, configDir); MigrateLinks(boundsControl, boundingBox, configDir); MigrateScaleHandles(boundsControl, boundingBox, configDir); MigrateRotationHandles(boundsControl, boundingBox, configDir); MigrateProximityEffect(boundsControl, boundingBox, configDir); // debug properties boundsControl.DebugText = boundingBox.debugText; boundsControl.HideElementsInInspector = boundingBox.HideElementsInInspector; // events boundsControl.RotateStarted = boundingBox.RotateStarted; boundsControl.RotateStopped = boundingBox.RotateStopped; boundsControl.ScaleStarted = boundingBox.ScaleStarted; boundsControl.ScaleStopped = boundingBox.ScaleStopped; } // look in the scene for app bars and upgrade them too to point to the new component MigrateAppBar(boundingBox, boundsControl); { Undo.RecordObject(gameObject, "Removing obsolete BoundingBox component"); // destroy obsolete component Object.DestroyImmediate(boundingBox); } #endif } #if UNITY_EDITOR virtual protected string GetBoundsControlConfigDirectory(BoundingBox boundingBox) { var scene = boundingBox.gameObject.scene; if (scene != null) { string scenePath = scene.path; string sceneDir = System.IO.Path.GetDirectoryName(scenePath); // if empty we're creating the folder in the asset root. // This should only happen if we're trying to migrate a dynamically created // gameobject - which is usually only in test scenarios if (sceneDir == "") { sceneDir = "Assets"; } const string configDir = "BoundsControlConfigs"; string configPath = System.IO.Path.Combine(sceneDir, configDir); if (AssetDatabase.IsValidFolder(configPath)) { return configPath; } else { string guid = AssetDatabase.CreateFolder(sceneDir, configDir); return AssetDatabase.GUIDToAssetPath(guid); } } return ""; } private string GenerateUniqueConfigName(string directory, GameObject migratingFrom, string configName) { return directory + "/" + migratingFrom.name + migratingFrom.GetInstanceID() + configName + ".asset"; } #region Flags Migration private BoundsCalculationMethod MigrateCalculationMethod(BoundingBox.BoundsCalculationMethod calculationMethod) { switch (calculationMethod) { case BoundingBox.BoundsCalculationMethod.RendererOverCollider: return BoundsCalculationMethod.RendererOverCollider; case BoundingBox.BoundsCalculationMethod.ColliderOverRenderer: return BoundsCalculationMethod.ColliderOverRenderer; case BoundingBox.BoundsCalculationMethod.ColliderOnly: return BoundsCalculationMethod.ColliderOnly; case BoundingBox.BoundsCalculationMethod.RendererOnly: return BoundsCalculationMethod.RendererOnly; } Debug.Assert(false, "Tried to migrate unsupported bounds calculation method in bounding box / bounds control"); return BoundsCalculationMethod.RendererOverCollider; } private BoundsControlActivationType MigrateActivationFlag(BoundingBox.BoundingBoxActivationType activationFlag) { switch (activationFlag) { case BoundingBox.BoundingBoxActivationType.ActivateOnStart: return BoundsControlActivationType.ActivateOnStart; case BoundingBox.BoundingBoxActivationType.ActivateByProximity: return BoundsControlActivationType.ActivateByProximity; case BoundingBox.BoundingBoxActivationType.ActivateByPointer: return BoundsControlActivationType.ActivateByPointer; case BoundingBox.BoundingBoxActivationType.ActivateByProximityAndPointer: return BoundsControlActivationType.ActivateByProximityAndPointer; case BoundingBox.BoundingBoxActivationType.ActivateManually: return BoundsControlActivationType.ActivateManually; } Debug.Assert(false, "Tried to migrate unsupported activation flag in bounding box / bounds control"); return BoundsControlActivationType.ActivateOnStart; } private FlattenModeType MigrateFlattenAxis(BoundingBox.FlattenModeType flattenAxisType) { switch (flattenAxisType) { case BoundingBox.FlattenModeType.DoNotFlatten: return FlattenModeType.DoNotFlatten; case BoundingBox.FlattenModeType.FlattenX: return FlattenModeType.FlattenX; case BoundingBox.FlattenModeType.FlattenY: return FlattenModeType.FlattenY; case BoundingBox.FlattenModeType.FlattenZ: return FlattenModeType.FlattenZ; case BoundingBox.FlattenModeType.FlattenAuto: return FlattenModeType.FlattenAuto; } Debug.Assert(false, "Tried to migrate unsupported flatten axis type in bounding box / bounds control"); return FlattenModeType.DoNotFlatten; } private WireframeType MigrateWireframeShape(BoundingBox.WireframeType wireframeType) { switch (wireframeType) { case BoundingBox.WireframeType.Cubic: return WireframeType.Cubic; case BoundingBox.WireframeType.Cylindrical: return WireframeType.Cylindrical; } Debug.Assert(false, "Tried to migrate unsupported wireframe type in bounding box / bounds control"); return WireframeType.Cubic; } private HandlePrefabCollider MigrateRotationHandleColliderType(BoundingBox.RotationHandlePrefabCollider rotationHandlePrefabColliderType) { switch (rotationHandlePrefabColliderType) { case BoundingBox.RotationHandlePrefabCollider.Sphere: return HandlePrefabCollider.Sphere; case BoundingBox.RotationHandlePrefabCollider.Box: return HandlePrefabCollider.Box; } Debug.Assert(false, "Tried to migrate unsupported rotation handle collider type in bounding box / bounds control"); return HandlePrefabCollider.Sphere; } #endregion Flags Migration #region Visuals Configuration Migration private void MigrateBoxDisplay(BoundsControl control, BoundingBox box, string configAssetDirectory) { BoxDisplayConfiguration config = ScriptableObject.CreateInstance<BoxDisplayConfiguration>(); config.BoxMaterial = box.BoxMaterial; config.BoxGrabbedMaterial = box.BoxGrabbedMaterial; config.FlattenAxisDisplayScale = box.FlattenAxisDisplayScale; AssetDatabase.CreateAsset(config, GenerateUniqueConfigName(configAssetDirectory, box.gameObject, "BoxDisplayConfiguration")); control.BoxDisplayConfig = config; } private void MigrateLinks(BoundsControl control, BoundingBox box, string configAssetDirectory) { LinksConfiguration config = ScriptableObject.CreateInstance<LinksConfiguration>(); config.WireframeMaterial = box.WireframeMaterial; config.WireframeEdgeRadius = box.WireframeEdgeRadius; config.WireframeShape = MigrateWireframeShape(box.WireframeShape); config.ShowWireFrame = box.ShowWireFrame; AssetDatabase.CreateAsset(config, GenerateUniqueConfigName(configAssetDirectory, box.gameObject, "LinksConfiguration")); control.LinksConfig = config; } private void MigrateScaleHandles(BoundsControl control, BoundingBox box, string configAssetDirectory) { ScaleHandlesConfiguration config = ScriptableObject.CreateInstance<ScaleHandlesConfiguration>(); config.HandleSlatePrefab = box.ScaleHandleSlatePrefab; config.ShowScaleHandles = box.ShowScaleHandles; config.HandleMaterial = box.HandleMaterial; config.HandleGrabbedMaterial = box.HandleGrabbedMaterial; config.HandlePrefab = box.ScaleHandlePrefab; config.HandleSize = box.ScaleHandleSize; config.ColliderPadding = box.ScaleHandleColliderPadding; config.DrawTetherWhenManipulating = box.DrawTetherWhenManipulating; config.HandlesIgnoreCollider = box.HandlesIgnoreCollider; AssetDatabase.CreateAsset(config, GenerateUniqueConfigName(configAssetDirectory, box.gameObject, "ScaleHandlesConfiguration")); control.ScaleHandlesConfig = config; } private void MigrateRotationHandles(BoundsControl control, BoundingBox box, string configAssetDirectory) { RotationHandlesConfiguration config = ScriptableObject.CreateInstance<RotationHandlesConfiguration>(); config.RotationHandlePrefabColliderType = MigrateRotationHandleColliderType(box.RotationHandlePrefabColliderType); config.ShowRotationHandleForX = box.ShowRotationHandleForX; config.ShowRotationHandleForY = box.ShowRotationHandleForY; config.ShowRotationHandleForZ = box.ShowRotationHandleForZ; config.HandleMaterial = box.HandleMaterial; config.HandleGrabbedMaterial = box.HandleGrabbedMaterial; config.HandlePrefab = box.RotationHandlePrefab; config.HandleSize = box.RotationHandleSize; config.ColliderPadding = box.RotateHandleColliderPadding; config.DrawTetherWhenManipulating = box.DrawTetherWhenManipulating; config.HandlesIgnoreCollider = box.HandlesIgnoreCollider; AssetDatabase.CreateAsset(config, GenerateUniqueConfigName(configAssetDirectory, box.gameObject, "RotationHandlesConfiguration")); control.RotationHandlesConfig = config; } private void MigrateProximityEffect(BoundsControl control, BoundingBox box, string configAssetDirectory) { ProximityEffectConfiguration config = ScriptableObject.CreateInstance<ProximityEffectConfiguration>(); config.ProximityEffectActive = box.ProximityEffectActive; config.ObjectMediumProximity = box.HandleMediumProximity; config.ObjectCloseProximity = box.HandleCloseProximity; config.FarScale = box.FarScale; config.MediumScale = box.MediumScale; config.CloseScale = box.CloseScale; config.FarGrowRate = box.FarGrowRate; config.MediumGrowRate = box.MediumGrowRate; config.CloseGrowRate = box.CloseGrowRate; AssetDatabase.CreateAsset(config, GenerateUniqueConfigName(configAssetDirectory, box.gameObject, "ProximityEffectConfiguration")); control.HandleProximityEffectConfig = config; } #endregion Visuals Configuration Migration private void MigrateAppBar(BoundingBox boundingBox, BoundsControl boundsControl) { // note: this might be expensive for larger scenes but we don't know where the appbar is // placed in the hierarchy so we have to search the scene for it AppBar[] appBars = Object.FindObjectsOfType<AppBar>(); for (int i = 0; i < appBars.Length; ++i) { AppBar appBar = appBars[i]; if (appBar.Target == boundingBox) { Undo.RecordObject(appBar, "BoundsControl migration: changed target of app bar."); appBar.Target = boundsControl; EditorUtility.SetDirty(appBar); } } } #endif } }
// // System.Data.Common.DbDataUpdatableRecord.cs // // Author: // Tim Coleman (tim@timcoleman.com) // // Copyright (C) Tim Coleman, 2003 // // // Copyright (C) 2004 Novell, Inc (http://www.novell.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. // #if NET_2_0 using System.ComponentModel; namespace System.Data.Common { public class DbDataUpdatableRecord : IDataUpdatableRecord, IDataRecord, ISetTypedData, ICustomTypeDescriptor, IGetTypedData { #region Properties [MonoTODO] public virtual int FieldCount { get { throw new NotImplementedException (); } } [MonoTODO] public virtual object this [string x] { get { throw new NotImplementedException (); } } [MonoTODO] public virtual object this [int x] { get { throw new NotImplementedException (); } } [MonoTODO] public virtual bool Updatable { get { throw new NotImplementedException (); } } #endregion // Properties #region Methods [MonoTODO] public virtual bool GetBoolean (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual byte GetByte (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual long GetBytes (int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw new NotImplementedException (); } [MonoTODO] public virtual char GetChar (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual long GetChars (int i, long dataIndex, char[] buffer, int bufferIndex, int length) { throw new NotImplementedException (); } [MonoTODO] public virtual IDataReader GetData (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual string GetDataTypeName (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual DateTime GetDateTime (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual decimal GetDecimal (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual double GetDouble (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual Type GetFieldType (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual float GetFloat (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual Guid GetGuid (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual short GetInt16 (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual int GetInt32 (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual long GetInt64 (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual string GetName (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual object GetObjectRef (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual int GetOrdinal (string name) { throw new NotImplementedException (); } [MonoTODO] public virtual string GetString (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual object GetValue (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual int GetValues (object[] values) { throw new NotImplementedException (); } [MonoTODO] AttributeCollection ICustomTypeDescriptor.GetAttributes () { throw new NotImplementedException (); } [MonoTODO] string ICustomTypeDescriptor.GetClassName () { throw new NotImplementedException (); } [MonoTODO] string ICustomTypeDescriptor.GetComponentName () { throw new NotImplementedException (); } [MonoTODO] TypeConverter ICustomTypeDescriptor.GetConverter () { throw new NotImplementedException (); } [MonoTODO] EventDescriptor ICustomTypeDescriptor.GetDefaultEvent () { throw new NotImplementedException (); } [MonoTODO] PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty () { throw new NotImplementedException (); } [MonoTODO] object ICustomTypeDescriptor.GetEditor (Type editorBaseType) { throw new NotImplementedException (); } [MonoTODO] EventDescriptorCollection ICustomTypeDescriptor.GetEvents () { throw new NotImplementedException (); } [MonoTODO] EventDescriptorCollection ICustomTypeDescriptor.GetEvents (Attribute[] attributes) { throw new NotImplementedException (); } [MonoTODO] PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties () { throw new NotImplementedException (); } [MonoTODO] PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties (Attribute[] attributes) { throw new NotImplementedException (); } [MonoTODO] object ICustomTypeDescriptor.GetPropertyOwner (PropertyDescriptor pd) { throw new NotImplementedException (); } [MonoTODO] int IDataUpdatableRecord.SetValues (object[] values) { throw new NotImplementedException (); } [MonoTODO] public virtual bool IsDBNull (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual bool IsSetAsDefault (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetBoolean (int i, bool value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetByte (int i, byte value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetBytes (int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetChar (int i, char value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetChars (int i, long dataIndex, char[] buffer, int bufferIndex, int length) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetDateTime (int i, DateTime value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetDecimal (int i, decimal value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetDefault (int i) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetDouble (int i, double value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetFloat (int i, float value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetGuid (int i, Guid value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetInt16 (int i, short value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetInt32 (int i, int value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetInt64 (int i, long value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetObjectRef (int i, object o) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetString (int i, string value) { throw new NotImplementedException (); } [MonoTODO] public virtual void SetValue (int i, object value) { throw new NotImplementedException (); } [MonoTODO] public virtual int SetValues (int i, object[] value) { throw new NotImplementedException (); } #endregion // Methods } } #endif // NET_2_0
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Xml; using System.Text; namespace MindTouch.Xml { /// <summary> /// Provides a mechanism to verify and enforce document structure and content rules on an <see cref="XDoc"/>. /// </summary> public class XDocCop { //--- Types --- private enum ProcessingMode { Default, RemoveEmpty, PadEmpty } private class Element { //--- Fields --- public readonly string[] Names; public ProcessingMode Mode; public Dictionary<string, Attribute> Attributes = new Dictionary<string, Attribute>(StringComparer.Ordinal); //--- Constructors --- public Element(string[] names, ProcessingMode mode, params Attribute[] attributes) { if(ArrayUtil.IsNullOrEmpty(names)) { throw new ArgumentNullException("names"); } this.Names = names; this.Mode = mode; foreach(Attribute attribute in attributes) { this.Attributes[attribute.Name] = attribute; } } //--- Properties --- public string Name { get { return Names[0]; } } //--- Methods --- public Element Attr(string name, string defaultValue, params string[] legalValues) { Attributes[name] = new Attribute(name, defaultValue, legalValues); return this; } public Element Attr(string name) { Attributes[name] = new Attribute(name, null); return this; } public override string ToString() { StringBuilder result = new StringBuilder(); switch(Mode) { case ProcessingMode.PadEmpty: result.Append("+"); break; case ProcessingMode.RemoveEmpty: result.Append("-"); break; } result.Append(string.Join("/", Names)); if(Attributes.Count > 0) { result.Append("["); bool first = true; foreach(Attribute attribute in Attributes.Values) { if(!first) { result.Append("|"); } first = false; result.Append(attribute.ToString()); } result.Append("]"); } return result.ToString(); } } private class Attribute { //--- Fields --- public readonly string Name; public readonly string DefaultValue; public readonly string[] LegalValues; //--- Constructors --- public Attribute(string name, string defaultValue, params string[] legalValues) { this.Name = name; this.DefaultValue = defaultValue; this.LegalValues = legalValues; Array.Sort(this.LegalValues, StringComparer.Ordinal); } //--- Methods --- public override string ToString() { StringBuilder result = new StringBuilder(); result.Append(Name); if(DefaultValue != null) { result.Append("="); result.Append(DefaultValue); } if(LegalValues.Length > 0) { result.Append("<"); bool first = true; foreach(string value in LegalValues) { if(!first) { result.Append("?"); } first = false; result.Append(value); } } return result.ToString(); } } //--- Fields --- private readonly Dictionary<string, Element> Elements = new Dictionary<string, Element>(StringComparer.Ordinal); private Element _wildcardElement; private bool _initialized = false; //--- Constructors --- /// <summary> /// Create a new instance without any predefined rules. /// </summary> public XDocCop() { } /// <summary> /// Create a new instance with a set of initial rules. /// </summary> /// <param name="rules">Array of rules.</param> public XDocCop(string[] rules) { AddRules(rules); } //--- Methods --- /// <summary> /// Add rules to the instance. /// </summary> /// <param name="rules">Array of rules.</param> public void AddRules(string[] rules) { if(rules == null) { throw new ArgumentNullException("rules"); } foreach(string rule in rules) { AddRule(rule); } } /// <summary> /// Add a single rule to the instance. /// </summary> /// <param name="rule">Rule to add.</param> public void AddRule(string rule) { if(string.IsNullOrEmpty(rule)) { return; } rule = rule.Trim(); if(rule.StartsWith("#")) { return; } ProcessingMode mode = ProcessingMode.Default; switch(rule[0]) { case '-': mode = ProcessingMode.RemoveEmpty; rule = rule.Substring(1); break; case '+': mode = ProcessingMode.PadEmpty; rule = rule.Substring(1); break; } int square = rule.IndexOf('['); if(square >= 0) { string[] names = rule.Substring(0, square).Split('/'); List<Attribute> attributes = new List<Attribute>(); foreach(string attr in rule.Substring(square + 1).TrimEnd(']').Split('|')) { // TODO (steveb): we should support '=' and '<' for default and valid values set int sep = attr.IndexOfAny(new char[] { '=', '<' }); attributes.Add(new Attribute((sep >= 0) ? attr.Substring(0, sep) : attr, null)); } Add(new Element(names, mode, attributes.ToArray())); } else { Add(rule); } } /// <summary> /// Enforce the specified rules on the document. /// </summary> /// <param name="doc">Document to process.</param> public void Enforce(XDoc doc) { Initialize(); Enforce(doc, true, true); } /// <summary> /// Enforce the specified rules on the document. /// </summary> /// <param name="doc">Document to process.</param> /// <param name="removeIllegalElements">If <see langword="True"/> strip illegal elements from the document.</param> public void Enforce(XDoc doc, bool removeIllegalElements) { Initialize(); Enforce(doc, removeIllegalElements, true); } /// <summary> /// Verify that the document conforms to the specified rules. /// </summary> /// <param name="doc">Document to process.</param> /// <returns></returns> public bool Verify(XDoc doc) { Initialize(); Elements.TryGetValue("*", out _wildcardElement); return Verify(doc, true); } /// <summary> /// Checks if the tag name is legal for the specified rules. /// </summary> /// <param name="tag">XML tag name to check.</param> /// <returns></returns> public bool IsLegalElement(string tag) { Initialize(); return Elements.ContainsKey(tag); } /// <summary> /// Checks if the attribute name is legal for the given tag name is legal using the specified rules. /// </summary> /// <param name="tag">XML tag name to check.</param> /// <param name="name">XML attribute name to check.</param> /// <returns></returns> public bool IsLegalAttribute(string tag, string name) { Initialize(); Element element; return (Elements.TryGetValue(tag, out element) && element.Attributes.ContainsKey(name)) || ((_wildcardElement != null) && _wildcardElement.Attributes.ContainsKey(name)); } /// <summary> /// Create a string representation of the document analysis. /// </summary> /// <returns>A string instance.</returns> public override string ToString() { StringBuilder result = new StringBuilder(); foreach(KeyValuePair<string, Element> element in Elements) { if(element.Key == element.Value.Name) { result.AppendLine(element.Value.ToString()); } } return result.ToString(); } private void Enforce(XDoc doc, bool removeIllegalElements, bool isRoot) { if(doc.IsEmpty) { return; } // process child elements List<XDoc> list = doc.Elements.ToList(); foreach(XDoc child in list) { Enforce(child, removeIllegalElements, false); } // skip processing of root element if(!isRoot) { // process element Element elementRule; if(!Elements.TryGetValue(doc.Name, out elementRule)) { // element is not valid; determine what to do with it if(removeIllegalElements) { // replace it with its contents doc.ReplaceWithNodes(doc); } else { StringBuilder attributes = new StringBuilder(); foreach(XmlAttribute attribute in doc.AsXmlNode.Attributes) { attributes.Append(" "); attributes.Append(attribute.OuterXml); } // replace it with text version of itself if(doc.AsXmlNode.ChildNodes.Count == 0) { doc.AddBefore("<" + doc.Name + attributes.ToString() + "/>"); doc.Remove(); } else { doc.AddBefore("<" + doc.Name + attributes.ToString() + ">"); doc.AddAfter("</" + doc.Name + ">"); doc.ReplaceWithNodes(doc); } } return; } else if(doc.Name != elementRule.Name) { // element has an obsolete name, substitute it doc.Rename(elementRule.Name); } // process attributes List<XmlAttribute> attributeList = new List<XmlAttribute>(); foreach(XmlAttribute attribute in doc.AsXmlNode.Attributes) { attributeList.Add(attribute); } // remove unsupported attributes if(!elementRule.Attributes.ContainsKey("*")) { foreach(XmlAttribute attribute in attributeList) { Attribute attributeRule; elementRule.Attributes.TryGetValue(attribute.Name, out attributeRule); if((attributeRule == null) && (_wildcardElement != null)) { _wildcardElement.Attributes.TryGetValue(attribute.Name, out attributeRule); } if((attributeRule == null) || ((attributeRule.LegalValues.Length > 0) && (Array.BinarySearch<string>(attributeRule.LegalValues, attribute.Value) < 0))) { doc.RemoveAttr(attribute.Name); } } } // add default attributes foreach(Attribute attributeRule in elementRule.Attributes.Values) { if((attributeRule.DefaultValue != null) && (doc.AsXmlNode.Attributes[attributeRule.Name] == null)) { doc.Attr(attributeRule.Name, attributeRule.DefaultValue); } } // process empty element if(list.Count == 0) { // check if the contents are empty string contents = doc.Contents; if((contents.Trim().Length == 0) && (contents.IndexOf('\u00A0') < 0)) { switch(elementRule.Mode) { case ProcessingMode.PadEmpty: // add '&nbsp;' doc.ReplaceValue("\u00A0"); break; case ProcessingMode.RemoveEmpty: doc.Remove(); break; } } } } } private bool Verify(XDoc doc, bool isRoot) { if(doc.IsEmpty) { return true; } // check child elements List<XDoc> list = doc.Elements.ToList(); foreach(XDoc child in list) { if(!Verify(child, false)) { return false; } } // skip processing of root element if(!isRoot) { // process element Element elementRule; if(!Elements.TryGetValue(doc.Name, out elementRule)) { // element is not valid return false; } // process attributes List<XmlAttribute> attributeList = new List<XmlAttribute>(); foreach(XmlAttribute attribute in doc.AsXmlNode.Attributes) { attributeList.Add(attribute); } // check for unsupported attributes if(!elementRule.Attributes.ContainsKey("*")) { foreach(XmlAttribute attribute in attributeList) { Attribute attributeRule; elementRule.Attributes.TryGetValue(attribute.Name, out attributeRule); if((attributeRule == null) && (_wildcardElement != null)) { _wildcardElement.Attributes.TryGetValue(attribute.Name, out attributeRule); } if((attributeRule == null) || ((attributeRule.LegalValues.Length > 0) && (Array.BinarySearch<string>(attributeRule.LegalValues, attribute.Value) < 0))) { // attribute is not valid return false; } } } } return true; } private void Add(Element element) { _initialized = false; foreach(string name in element.Names) { Elements.Add(name, element); } } private void Add(string[] names, ProcessingMode mode, params Attribute[] attributes) { Element result = new Element(names, mode, attributes); Add(result); } private void Add(string names, ProcessingMode mode) { Add(names.Split('/'), mode, new Attribute[0]); } private void Add(string names) { Add(names, ProcessingMode.Default); } private void Initialize() { if(!_initialized) { Elements.TryGetValue("*", out _wildcardElement); _initialized = true; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using System.Collections.Generic; using System.Collections; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Scripting.LSLHttp { public class UrlData { public UUID hostID; public UUID itemID; public IScriptModule engine; public string url; public UUID urlcode; public Dictionary<UUID, RequestData> requests; } public class RequestData { public UUID requestID; public Dictionary<string, string> headers; public string body; public int responseCode; public string responseBody; //public ManualResetEvent ev; public bool requestDone; public int startTime; public string uri; } public class UrlModule : ISharedRegionModule, IUrlModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<UUID, UrlData> m_RequestMap = new Dictionary<UUID, UrlData>(); private Dictionary<string, UrlData> m_UrlMap = new Dictionary<string, UrlData>(); private int m_TotalUrls = 100; private IHttpServer m_HttpServer = null; private string m_ExternalHostNameForLSL = ""; public Type ReplaceableInterface { get { return null; } } private Hashtable HandleHttpPoll(Hashtable request) { return new Hashtable(); } public string Name { get { return "UrlModule"; } } public void Initialise(IConfigSource config) { m_ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", System.Environment.MachineName); } public void PostInitialise() { } public void AddRegion(Scene scene) { if (m_HttpServer == null) { // There can only be one // m_HttpServer = MainServer.Instance; } scene.RegisterModuleInterface<IUrlModule>(this); scene.EventManager.OnScriptReset += OnScriptReset; } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } public void Close() { } public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); lock (m_UrlMap) { if (m_UrlMap.Count >= m_TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new Dictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttp/" + urlcode.ToString() + "/"; m_HttpServer.AddPollServiceHTTPHandler(uri,HandleHttpPoll, new PollServiceEventArgs(HttpRequestHandler,HasEvents, GetEvents, NoEvents, urlcode)); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } public void ReleaseURL(string url) { lock (m_UrlMap) { UrlData data; if (!m_UrlMap.TryGetValue(url, out data)) { return; } foreach (UUID req in data.requests.Keys) m_RequestMap.Remove(req); RemoveUrl(data); m_UrlMap.Remove(url); } } public void HttpResponse(UUID request, int status, string body) { if (m_RequestMap.ContainsKey(request)) { UrlData urlData = m_RequestMap[request]; urlData.requests[request].responseCode = status; urlData.requests[request].responseBody = body; //urlData.requests[request].ev.Set(); urlData.requests[request].requestDone =true; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } public string GetHttpHeader(UUID requestId, string header) { if (m_RequestMap.ContainsKey(requestId)) { UrlData urlData=m_RequestMap[requestId]; string value; if (urlData.requests[requestId].headers.TryGetValue(header,out value)) return value; } else { m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId); } return String.Empty; } public int GetFreeUrls() { return m_TotalUrls - m_UrlMap.Count; } public void ScriptRemoved(UUID itemID) { lock (m_UrlMap) { List<string> removeURLs = new List<string>(); foreach (KeyValuePair<string, UrlData> url in m_UrlMap) { if (url.Value.itemID == itemID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } } foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } } public void ObjectRemoved(UUID objectID) { lock (m_UrlMap) { List<string> removeURLs = new List<string>(); foreach (KeyValuePair<string, UrlData> url in m_UrlMap) { if (url.Value.hostID == objectID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } } foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } } private void RemoveUrl(UrlData data) { m_HttpServer.RemoveHTTPHandler("", "/lslhttp/"+data.urlcode.ToString()+"/"); } private Hashtable NoEvents(UUID requestID, UUID sessionID) { Hashtable response = new Hashtable(); UrlData url; lock (m_RequestMap) { if (!m_RequestMap.ContainsKey(requestID)) return response; url = m_RequestMap[requestID]; } if (System.Environment.TickCount - url.requests[requestID].startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map lock (url) { url.requests.Remove(requestID); m_RequestMap.Remove(requestID); } return response; } return response; } private bool HasEvents(UUID requestID, UUID sessionID) { UrlData url=null; lock (m_RequestMap) { if (!m_RequestMap.ContainsKey(requestID)) { return false; } url = m_RequestMap[requestID]; if (!url.requests.ContainsKey(requestID)) { return false; } } if (System.Environment.TickCount-url.requests[requestID].startTime>25000) { return true; } if (url.requests[requestID].requestDone) return true; else return false; } private Hashtable GetEvents(UUID requestID, UUID sessionID, string request) { UrlData url = null; RequestData requestData = null; lock (m_RequestMap) { if (!m_RequestMap.ContainsKey(requestID)) return NoEvents(requestID,sessionID); url = m_RequestMap[requestID]; requestData = url.requests[requestID]; } if (!requestData.requestDone) return NoEvents(requestID,sessionID); Hashtable response = new Hashtable(); if (System.Environment.TickCount - requestData.startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; return response; } //put response response["int_response_code"] = requestData.responseCode; response["str_response_string"] = requestData.responseBody; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map lock (url) { url.requests.Remove(requestID); m_RequestMap.Remove(requestID); } return response; } public void HttpRequestHandler(UUID requestID, Hashtable request) { lock (request) { string uri = request["uri"].ToString(); try { Hashtable headers = (Hashtable)request["headers"]; // string uri_full = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/"; int pos1 = uri.IndexOf("/");// /lslhttp int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/ int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/ string uri_tmp = uri.Substring(0, pos3 + 1); //HTTP server code doesn't provide us with QueryStrings string pathInfo; string queryString; queryString = ""; pathInfo = uri.Substring(pos3); UrlData url = m_UrlMap["http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp]; //for llGetHttpHeader support we need to store original URI here //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader RequestData requestData = new RequestData(); requestData.requestID = requestID; requestData.requestDone = false; requestData.startTime = System.Environment.TickCount; requestData.uri = uri; if (requestData.headers == null) requestData.headers = new Dictionary<string, string>(); foreach (DictionaryEntry header in headers) { string key = (string)header.Key; string value = (string)header.Value; requestData.headers.Add(key, value); } foreach (DictionaryEntry de in request) { if (de.Key.ToString() == "querystringkeys") { System.String[] keys = (System.String[])de.Value; foreach (String key in keys) { if (request.ContainsKey(key)) { string val = (String)request[key]; queryString = queryString + key + "=" + val + "&"; } } if (queryString.Length > 1) queryString = queryString.Substring(0, queryString.Length - 1); } } //if this machine is behind DNAT/port forwarding, currently this is being //set to address of port forwarding router requestData.headers["x-remote-ip"] = requestData.headers["remote_addr"]; requestData.headers["x-path-info"] = pathInfo; requestData.headers["x-query-string"] = queryString; requestData.headers["x-script-url"] = url.url; //requestData.ev = new ManualResetEvent(false); lock (url.requests) { url.requests.Add(requestID, requestData); } lock (m_RequestMap) { //add to request map m_RequestMap.Add(requestID, url); } url.engine.PostScriptEvent(url.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() }); //send initial response? // Hashtable response = new Hashtable(); return; } catch (Exception we) { //Hashtable response = new Hashtable(); m_log.Warn("[HttpRequestHandler]: http-in request failed"); m_log.Warn(we.Message); m_log.Warn(we.StackTrace); } } } private void OnScriptReset(uint localID, UUID itemID) { ScriptRemoved(itemID); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.Security.Cryptography { public class CryptoConfig { private const string AssemblyName_Cng = "System.Security.Cryptography.Cng"; private const string AssemblyName_Csp = "System.Security.Cryptography.Csp"; private const string AssemblyName_Pkcs = "System.Security.Cryptography.Pkcs"; private const string AssemblyName_X509Certificates = "System.Security.Cryptography.X509Certificates"; private const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; private const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6"; private const string OID_RSA_MD5 = "1.2.840.113549.2.5"; private const string OID_RSA_RC2CBC = "1.2.840.113549.3.2"; private const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7"; private const string OID_OIWSEC_desCBC = "1.3.14.3.2.7"; private const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26"; private const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1"; private const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2"; private const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3"; private const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1"; private static volatile Dictionary<string, string> s_defaultOidHT = null; private static volatile Dictionary<string, object> s_defaultNameHT = null; private static readonly char[] SepArray = { '.' }; // valid ASN.1 separators // CoreFx does not support AllowOnlyFipsAlgorithms public static bool AllowOnlyFipsAlgorithms => false; private static Dictionary<string, string> DefaultOidHT { get { if (s_defaultOidHT != null) { return s_defaultOidHT; } Dictionary<string, string> ht = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); ht.Add("SHA", OID_OIWSEC_SHA1); ht.Add("SHA1", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1CryptoServiceProvider", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1Cng", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1Managed", OID_OIWSEC_SHA1); ht.Add("SHA256", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256Cng", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256Managed", OID_OIWSEC_SHA256); ht.Add("SHA384", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Cng", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Managed", OID_OIWSEC_SHA384); ht.Add("SHA512", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Cng", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Managed", OID_OIWSEC_SHA512); ht.Add("RIPEMD160", OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160", OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160Managed", OID_OIWSEC_RIPEMD160); ht.Add("MD5", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5CryptoServiceProvider", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5Managed", OID_RSA_MD5); ht.Add("TripleDESKeyWrap", OID_RSA_SMIMEalgCMS3DESwrap); ht.Add("RC2", OID_RSA_RC2CBC); ht.Add("System.Security.Cryptography.RC2CryptoServiceProvider", OID_RSA_RC2CBC); ht.Add("DES", OID_OIWSEC_desCBC); ht.Add("System.Security.Cryptography.DESCryptoServiceProvider", OID_OIWSEC_desCBC); ht.Add("TripleDES", OID_RSA_DES_EDE3_CBC); ht.Add("System.Security.Cryptography.TripleDESCryptoServiceProvider", OID_RSA_DES_EDE3_CBC); s_defaultOidHT = ht; return s_defaultOidHT; } } private static Dictionary<string, object> DefaultNameHT { get { if (s_defaultNameHT != null) { return s_defaultNameHT; } Dictionary<string, object> ht = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); Type HMACMD5Type = typeof(System.Security.Cryptography.HMACMD5); Type HMACSHA1Type = typeof(System.Security.Cryptography.HMACSHA1); Type HMACSHA256Type = typeof(System.Security.Cryptography.HMACSHA256); Type HMACSHA384Type = typeof(System.Security.Cryptography.HMACSHA384); Type HMACSHA512Type = typeof(System.Security.Cryptography.HMACSHA512); Type RijndaelManagedType = typeof(System.Security.Cryptography.RijndaelManaged); Type AesManagedType = typeof(System.Security.Cryptography.AesManaged); Type SHA256DefaultType = typeof(System.Security.Cryptography.SHA256Managed); Type SHA384DefaultType = typeof(System.Security.Cryptography.SHA384Managed); Type SHA512DefaultType = typeof(System.Security.Cryptography.SHA512Managed); string SHA1CryptoServiceProviderType = "System.Security.Cryptography.SHA1CryptoServiceProvider, " + AssemblyName_Csp; string MD5CryptoServiceProviderType = "System.Security.Cryptography.MD5CryptoServiceProvider," + AssemblyName_Csp; string RSACryptoServiceProviderType = "System.Security.Cryptography.RSACryptoServiceProvider, " + AssemblyName_Csp; string DSACryptoServiceProviderType = "System.Security.Cryptography.DSACryptoServiceProvider, " + AssemblyName_Csp; string DESCryptoServiceProviderType = "System.Security.Cryptography.DESCryptoServiceProvider, " + AssemblyName_Csp; string TripleDESCryptoServiceProviderType = "System.Security.Cryptography.TripleDESCryptoServiceProvider, " + AssemblyName_Csp; string RC2CryptoServiceProviderType = "System.Security.Cryptography.RC2CryptoServiceProvider, " + AssemblyName_Csp; string RNGCryptoServiceProviderType = "System.Security.Cryptography.RNGCryptoServiceProvider, " + AssemblyName_Csp; string AesCryptoServiceProviderType = "System.Security.Cryptography.AesCryptoServiceProvider, " + AssemblyName_Csp; string ECDsaCngType = "System.Security.Cryptography.ECDsaCng, " + AssemblyName_Cng; // Random number generator ht.Add("RandomNumberGenerator", RNGCryptoServiceProviderType); ht.Add("System.Security.Cryptography.RandomNumberGenerator", RNGCryptoServiceProviderType); // Hash functions ht.Add("SHA", SHA1CryptoServiceProviderType); ht.Add("SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.HashAlgorithm", SHA1CryptoServiceProviderType); ht.Add("MD5", MD5CryptoServiceProviderType); ht.Add("System.Security.Cryptography.MD5", MD5CryptoServiceProviderType); ht.Add("SHA256", SHA256DefaultType); ht.Add("SHA-256", SHA256DefaultType); ht.Add("System.Security.Cryptography.SHA256", SHA256DefaultType); ht.Add("SHA384", SHA384DefaultType); ht.Add("SHA-384", SHA384DefaultType); ht.Add("System.Security.Cryptography.SHA384", SHA384DefaultType); ht.Add("SHA512", SHA512DefaultType); ht.Add("SHA-512", SHA512DefaultType); ht.Add("System.Security.Cryptography.SHA512", SHA512DefaultType); // Keyed Hash Algorithms ht.Add("System.Security.Cryptography.HMAC", HMACSHA1Type); ht.Add("System.Security.Cryptography.KeyedHashAlgorithm", HMACSHA1Type); ht.Add("HMACMD5", HMACMD5Type); ht.Add("System.Security.Cryptography.HMACMD5", HMACMD5Type); ht.Add("HMACSHA1", HMACSHA1Type); ht.Add("System.Security.Cryptography.HMACSHA1", HMACSHA1Type); ht.Add("HMACSHA256", HMACSHA256Type); ht.Add("System.Security.Cryptography.HMACSHA256", HMACSHA256Type); ht.Add("HMACSHA384", HMACSHA384Type); ht.Add("System.Security.Cryptography.HMACSHA384", HMACSHA384Type); ht.Add("HMACSHA512", HMACSHA512Type); ht.Add("System.Security.Cryptography.HMACSHA512", HMACSHA512Type); // Asymmetric algorithms ht.Add("RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.AsymmetricAlgorithm", RSACryptoServiceProviderType); ht.Add("DSA", DSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.DSA", DSACryptoServiceProviderType); ht.Add("ECDsa", ECDsaCngType); ht.Add("ECDsaCng", ECDsaCngType); ht.Add("System.Security.Cryptography.ECDsaCng", ECDsaCngType); // Symmetric algorithms ht.Add("DES", DESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.DES", DESCryptoServiceProviderType); ht.Add("3DES", TripleDESCryptoServiceProviderType); ht.Add("TripleDES", TripleDESCryptoServiceProviderType); ht.Add("Triple DES", TripleDESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.TripleDES", TripleDESCryptoServiceProviderType); ht.Add("RC2", RC2CryptoServiceProviderType); ht.Add("System.Security.Cryptography.RC2", RC2CryptoServiceProviderType); ht.Add("Rijndael", RijndaelManagedType); ht.Add("System.Security.Cryptography.Rijndael", RijndaelManagedType); // Rijndael is the default symmetric cipher because (a) it's the strongest and (b) we know we have an implementation everywhere ht.Add("System.Security.Cryptography.SymmetricAlgorithm", RijndaelManagedType); ht.Add("AES", AesCryptoServiceProviderType); ht.Add("AesCryptoServiceProvider", AesCryptoServiceProviderType); ht.Add("System.Security.Cryptography.AesCryptoServiceProvider", AesCryptoServiceProviderType); ht.Add("AesManaged", AesManagedType); ht.Add("System.Security.Cryptography.AesManaged", AesManagedType); // Xml Dsig/ Enc Hash algorithms ht.Add("http://www.w3.org/2000/09/xmldsig#sha1", SHA1CryptoServiceProviderType); // Add the other hash algorithms introduced with XML Encryption ht.Add("http://www.w3.org/2001/04/xmlenc#sha256", SHA256DefaultType); ht.Add("http://www.w3.org/2001/04/xmlenc#sha512", SHA512DefaultType); // Xml Encryption symmetric keys ht.Add("http://www.w3.org/2001/04/xmlenc#des-cbc", DESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", TripleDESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-tripledes", TripleDESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes128-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes128", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes192-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes192", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes256-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes256", RijndaelManagedType); // Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/ ht.Add("http://www.w3.org/2000/09/xmldsig#hmac-sha1", HMACSHA1Type); // Xml Dsig-more Uri's as defined in http://www.ietf.org/rfc/rfc4051.txt ht.Add("http://www.w3.org/2001/04/xmldsig-more#md5", MD5CryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#sha384", SHA384DefaultType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-md5", HMACMD5Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", HMACSHA256Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", HMACSHA384Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", HMACSHA512Type); // X509 Extensions (custom decoders) // Basic Constraints OID value ht.Add("2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates); ht.Add("2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates); // Subject Key Identifier OID value ht.Add("2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension, " + AssemblyName_X509Certificates); // Key Usage OID value ht.Add("2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension, " + AssemblyName_X509Certificates); // Enhanced Key Usage OID value ht.Add("2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension, " + AssemblyName_X509Certificates); // X509Chain class can be overridden to use a different chain engine. ht.Add("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain, " + AssemblyName_X509Certificates); // PKCS9 attributes ht.Add("1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType, " + AssemblyName_Pkcs); ht.Add("1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest, " + AssemblyName_Pkcs); ht.Add("1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime, " + AssemblyName_Pkcs); ht.Add("1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName, " + AssemblyName_Pkcs); ht.Add("1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription, " + AssemblyName_Pkcs); s_defaultNameHT = ht; return s_defaultNameHT; // Types in Desktop but currently unsupported in CoreFx: // Type HMACRIPEMD160Type = typeof(System.Security.Cryptography.HMACRIPEMD160); // Type MAC3DESType = typeof(System.Security.Cryptography.MACTripleDES); // Type DSASignatureDescriptionType = typeof(System.Security.Cryptography.DSASignatureDescription); // Type RSAPKCS1SHA1SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription); // Type RSAPKCS1SHA256SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA256SignatureDescription); // Type RSAPKCS1SHA384SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA384SignatureDescription); // Type RSAPKCS1SHA512SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA512SignatureDescription); // string RIPEMD160ManagedType = "System.Security.Cryptography.RIPEMD160Managed" + AssemblyName_Encoding; // string ECDiffieHellmanCngType = "System.Security.Cryptography.ECDiffieHellmanCng, " + AssemblyName_Cng; // string MD5CngType = "System.Security.Cryptography.MD5Cng, " + AssemblyName_Cng; // string SHA1CngType = "System.Security.Cryptography.SHA1Cng, " + AssemblyName_Cng; // string SHA256CngType = "System.Security.Cryptography.SHA256Cng, " + AssemblyName_Cng; // string SHA384CngType = "System.Security.Cryptography.SHA384Cng, " + AssemblyName_Cng; // string SHA512CngType = "System.Security.Cryptography.SHA512Cng, " + AssemblyName_Cng; // string SHA256CryptoServiceProviderType = "System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyName_Csp; // string SHA384CryptoSerivceProviderType = "System.Security.Cryptography.SHA384CryptoServiceProvider, " + AssemblyName_Csp; // string SHA512CryptoServiceProviderType = "System.Security.Cryptography.SHA512CryptoServiceProvider, " + AssemblyName_Csp; // string DpapiDataProtectorType = "System.Security.Cryptography.DpapiDataProtector, " + AssemblyRef.SystemSecurity; } } public static void AddAlgorithm(Type algorithm, params string[] names) { throw new PlatformNotSupportedException(); } public static object CreateFromName(string name, params object[] args) { if (name == null) throw new ArgumentNullException(nameof(name)); Type retvalType = null; // We allow the default table to Types and Strings // Types get used for types in .Algorithms assembly. // strings get used for delay-loaded stuff in other assemblies such as .Csp. object retvalObj; if (DefaultNameHT.TryGetValue(name, out retvalObj)) { if (retvalObj is Type) { retvalType = (Type)retvalObj; } else if (retvalObj is string) { retvalType = Type.GetType((string)retvalObj, false, false); if (retvalType != null && !retvalType.IsVisible) { retvalType = null; } } else { Debug.Fail("Unsupported Dictionary value:" + retvalObj.ToString()); } } // Maybe they gave us a classname. if (retvalType == null) { retvalType = Type.GetType(name, false, false); if (retvalType != null && !retvalType.IsVisible) { retvalType = null; } } // Still null? Then we didn't find it. if (retvalType == null) { return null; } // Locate all constructors. MethodBase[] cons = retvalType.GetConstructors(ConstructorDefault); if (cons == null) { return null; } if (args == null) { args = new object[] { }; } List<MethodBase> candidates = new List<MethodBase>(); for (int i = 0; i < cons.Length; i++) { MethodBase con = cons[i]; if (con.GetParameters().Length == args.Length) { candidates.Add(con); } } if (candidates.Count == 0) { return null; } cons = candidates.ToArray(); // Bind to matching ctor. object state; ConstructorInfo rci = Type.DefaultBinder.BindToMethod( ConstructorDefault, cons, ref args, null, null, null, out state) as ConstructorInfo; // Check for ctor we don't like (non-existent, delegate or decorated with declarative linktime demand). if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType)) { return null; } // Ctor invoke and allocation. object retval = rci.Invoke(ConstructorDefault, Type.DefaultBinder, args, null); // Reset any parameter re-ordering performed by the binder. if (state != null) { Type.DefaultBinder.ReorderArgumentArray(ref args, state); } return retval; } public static object CreateFromName(string name) { return CreateFromName(name, null); } public static void AddOID(string oid, params string[] names) { throw new PlatformNotSupportedException(); } public static string MapNameToOID(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); string oidName; if (!DefaultOidHT.TryGetValue(name, out oidName)) { try { Oid oid = Oid.FromFriendlyName(name, OidGroup.All); oidName = oid.Value; } catch (CryptographicException) { } } return oidName; } public static byte[] EncodeOID(string str) { if (str == null) throw new ArgumentNullException(nameof(str)); string[] oidString = str.Split(SepArray); uint[] oidNums = new uint[oidString.Length]; for (int i = 0; i < oidString.Length; i++) { oidNums[i] = unchecked((uint)int.Parse(oidString[i], CultureInfo.InvariantCulture)); } // Handle the first two oidNums special if (oidNums.Length < 2) throw new CryptographicUnexpectedOperationException(SR.Cryptography_InvalidOID); uint firstTwoOidNums = unchecked((oidNums[0] * 40) + oidNums[1]); // Determine length of output array int encodedOidNumsLength = 2; // Reserve first two bytes for later EncodeSingleOidNum(firstTwoOidNums, null, ref encodedOidNumsLength); for (int i = 2; i < oidNums.Length; i++) { EncodeSingleOidNum(oidNums[i], null, ref encodedOidNumsLength); } // Allocate the array to receive encoded oidNums byte[] encodedOidNums = new byte[encodedOidNumsLength]; int encodedOidNumsIndex = 2; // Encode each segment EncodeSingleOidNum(firstTwoOidNums, encodedOidNums, ref encodedOidNumsIndex); for (int i = 2; i < oidNums.Length; i++) { EncodeSingleOidNum(oidNums[i], encodedOidNums, ref encodedOidNumsIndex); } Debug.Assert(encodedOidNumsIndex == encodedOidNumsLength); // Final return value is 06 <length> encodedOidNums[] if (encodedOidNumsIndex - 2 > 0x7f) throw new CryptographicUnexpectedOperationException(SR.Cryptography_Config_EncodedOIDError); encodedOidNums[0] = (byte)0x06; encodedOidNums[1] = (byte)(encodedOidNumsIndex - 2); return encodedOidNums; } private static void EncodeSingleOidNum(uint value, byte[] destination, ref int index) { // Write directly to destination starting at index, and update index based on how many bytes written. // If destination is null, just return updated index. if (unchecked((int)value) < 0x80) { if (destination != null) { destination[index++] = unchecked((byte)value); } else { index += 1; } } else if (value < 0x4000) { if (destination != null) { destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } else { index += 2; } } else if (value < 0x200000) { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 3; } } else if (value < 0x10000000) { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 21) | 0x80); destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 4; } } else { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 28) | 0x80); destination[index++] = (byte)((value >> 21) | 0x80); destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 5; } } } } }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using System.IO.IsolatedStorage; namespace Microsoft.WindowsAzure.MobileServices { /// <summary> /// Provides basic access to Mobile Services. /// </summary> public sealed partial class MobileServiceClient { /// <summary> /// Name of the config setting that stores the installation ID. /// </summary> private const string ConfigureAsyncInstallationConfigPath = "MobileServices.Installation.config"; /// <summary> /// Name of the JSON member in the config setting that stores the /// installation ID. /// </summary> private const string ConfigureAsyncApplicationIdKey = "applicationInstallationId"; /// <summary> /// Name of the JSON member in the config setting that stores the /// authentication token. /// </summary> private const string LoginAsyncAuthenticationTokenKey = "authenticationToken"; /// <summary> /// Relative URI fragment of the login endpoint. /// </summary> private const string LoginAsyncUriFragment = "login"; /// <summary> /// Relative URI fragment of the login/done endpoint. /// </summary> private const string LoginAsyncDoneUriFragment = "login/done"; /// <summary> /// Name of the Installation ID header included on each request. /// </summary> private const string RequestInstallationIdHeader = "X-ZUMO-INSTALLATION-ID"; /// <summary> /// Name of the application key header included when there's a key. /// </summary> private const string RequestApplicationKeyHeader = "X-ZUMO-APPLICATION"; /// <summary> /// Name of the authentication header included when the user's logged /// in. /// </summary> private const string RequestAuthenticationHeader = "X-ZUMO-AUTH"; /// <summary> /// Content type for request bodies and accepted responses. /// </summary> private const string RequestJsonContentType = "application/json"; /// <summary> /// Gets or sets the ID used to identify this installation of the /// application to provide telemetry data. It will either be retrieved /// from local settings or generated fresh. /// </summary> private static string applicationInstallationId = null; /// <summary> /// A JWT token representing the current user's successful OAUTH /// authorization. /// </summary> /// <remarks> /// This is passed on every request (when it exists) as the X-ZUMO-AUTH /// header. /// </remarks> private string currentUserAuthenticationToken = null; /// <summary> /// Represents a filter used to process HTTP requests and responses /// made by the Mobile Service. This can only be set by calling /// WithFilter to create a new MobileServiceClient with the filter /// applied. /// </summary> private IServiceFilter filter = null; /// <summary> /// Indicates whether a login operation is currently in progress. /// </summary> public bool LoginInProgress { get; private set; } /// <summary> /// Initialize the shared applicationInstallationId. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Initialization is nontrivial.")] static MobileServiceClient() { // Try to get the AppInstallationId from settings if (IsolatedStorageSettings.ApplicationSettings.Contains(ConfigureAsyncApplicationIdKey)) { JToken config = null; try { config = JToken.Parse(IsolatedStorageSettings.ApplicationSettings[ConfigureAsyncApplicationIdKey] as string); applicationInstallationId = config.Get(ConfigureAsyncApplicationIdKey).AsString(); } catch (Exception) { } } // Generate a new AppInstallationId if we failed to find one if (applicationInstallationId == null) { applicationInstallationId = Guid.NewGuid().ToString(); string configText = new JObject() .Set(ConfigureAsyncApplicationIdKey, applicationInstallationId) .ToString(); IsolatedStorageSettings.ApplicationSettings[ConfigureAsyncInstallationConfigPath] = configText; } } /// <summary> /// Initializes a new instance of the MobileServiceClient class. /// </summary> /// <param name="applicationUri"> /// The Uri to the Mobile Services application. /// </param> public MobileServiceClient(Uri applicationUri) : this(applicationUri, null) { } /// <summary> /// Initializes a new instance of the MobileServiceClient class. /// </summary> /// <param name="applicationUri"> /// The Uri to the Mobile Services application. /// </param> /// <param name="applicationKey"> /// The application name for the Mobile Services application. /// </param> public MobileServiceClient(Uri applicationUri, string applicationKey) { if (applicationUri == null) { throw new ArgumentNullException("applicationUri"); } this.ApplicationUri = applicationUri; this.ApplicationKey = applicationKey; } /// <summary> /// Initializes a new instance of the MobileServiceClient class based /// on an existing instance. /// </summary> /// <param name="service"> /// An existing instance of the MobileServices class to copy. /// </param> private MobileServiceClient(MobileServiceClient service) { Debug.Assert(service != null, "service cannot be null!"); this.ApplicationUri = service.ApplicationUri; this.ApplicationKey = service.ApplicationKey; this.CurrentUser = service.CurrentUser; this.currentUserAuthenticationToken = service.currentUserAuthenticationToken; this.filter = service.filter; } /// <summary> /// Gets the Uri to the Mobile Services application that is provided by /// the call to MobileServiceClient(...). /// </summary> public Uri ApplicationUri { get; private set; } /// <summary> /// Gets the Mobile Services application's name that is provided by the /// call to MobileServiceClient(...). /// </summary> public string ApplicationKey { get; private set; } /// <summary> /// The current authenticated user provided after a successful call to /// MobileServiceClient.Login(). /// </summary> public MobileServiceUser CurrentUser { get; private set; } /// <summary> /// Gets a reference to a table and its data operations. /// </summary> /// <param name="tableName">The name of the table.</param> /// <returns>A reference to the table.</returns> public IMobileServiceTable GetTable(string tableName) { if (tableName == null) { throw new ArgumentNullException("tableName"); } else if (string.IsNullOrEmpty(tableName)) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, Resources.EmptyArgumentExceptionMessage, "tableName")); } return new MobileServiceTable(tableName, this); } /// <summary> /// Create a new MobileServiceClient with a filter used to process all /// of its HTTP requests and responses. /// </summary> /// <param name="filter">The filter to use on the service.</param> /// <returns> /// A new MobileServiceClient whose HTTP requests and responses will be /// filtered as desired. /// </returns> [SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "filter", Justification = "Consequence of StyleCop enforced naming conventions")] public MobileServiceClient WithFilter(IServiceFilter filter) { if (filter == null) { throw new ArgumentNullException("filter"); } // "Clone" the current service MobileServiceClient extended = new MobileServiceClient(this); // Chain this service's filter with the new filter for the // extended service. Note that we're extended.filter = (this.filter != null) ? new ComposedServiceFilter(this.filter, filter) : filter; return extended; } /// <summary> /// Log a user into a Mobile Services application given an access /// token. /// </summary> /// <param name="authenticationToken"> /// OAuth access token that authenticates the user. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> internal async Task<MobileServiceUser> SendLoginAsync(string authenticationToken) { if (authenticationToken == null) { throw new ArgumentNullException("authenticationToken"); } else if (string.IsNullOrEmpty(authenticationToken)) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, Resources.EmptyArgumentExceptionMessage, "authenticationToken")); } // TODO: Decide what we should do when CurrentUser isn't null // (i.e., do we just log out the current user or should we throw // an exception?). For now we just overwrite the the current user // and their token on a successful login. JToken request = new JObject() .Set(LoginAsyncAuthenticationTokenKey, authenticationToken); JToken response = await this.RequestAsync("POST", LoginAsyncUriFragment, request); // Get the Mobile Services auth token and user data this.currentUserAuthenticationToken = response.Get(LoginAsyncAuthenticationTokenKey).AsString(); this.CurrentUser = new MobileServiceUser(response.Get("user").Get("userId").AsString()); return this.CurrentUser; } /// <summary> /// Log a user into a Mobile Services application given a provider name and optional token object. /// </summary> /// <param name="provider" type="MobileServiceAuthenticationProvider"> /// Authentication provider to use. /// </param> /// <param name="token" type="JObject"> /// Optional, provider specific object with existing OAuth token to log in with. /// </param> /// <returns> /// Task that will complete when the user has finished authentication. /// </returns> internal async Task<MobileServiceUser> SendLoginAsync(MobileServiceAuthenticationProvider provider, JObject token = null) { if (this.LoginInProgress) { throw new InvalidOperationException(Resources.MobileServiceClient_Login_In_Progress); } if (!Enum.IsDefined(typeof(MobileServiceAuthenticationProvider), provider)) { throw new ArgumentOutOfRangeException("provider"); } string providerName = provider.ToString().ToLower(); this.LoginInProgress = true; try { JToken response = null; if (token != null) { // Invoke the POST endpoint to exchange provider-specific token for a Windows Azure Mobile Services token response = await this.RequestAsync("POST", LoginAsyncUriFragment + "/" + providerName, token); } else { // Use PhoneWebAuthenticationBroker to launch server side OAuth flow using the GET endpoint Uri startUri = new Uri(this.ApplicationUri, LoginAsyncUriFragment + "/" + providerName); Uri endUri = new Uri(this.ApplicationUri, LoginAsyncDoneUriFragment); PhoneAuthenticationResponse result = await PhoneWebAuthenticationBroker.AuthenticateAsync(startUri, endUri); if (result.ResponseStatus == PhoneAuthenticationStatus.ErrorHttp) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.Authentication_Failed, result.ResponseErrorDetail)); } else if (result.ResponseStatus == PhoneAuthenticationStatus.UserCancel) { throw new InvalidOperationException(Resources.Authentication_Canceled); } int i = result.ResponseData.IndexOf("#token="); if (i > 0) { response = JToken.Parse(Uri.UnescapeDataString(result.ResponseData.Substring(i + 7))); } else { i = result.ResponseData.IndexOf("#error="); if (i > 0) { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, Resources.MobileServiceClient_Login_Error_Response, Uri.UnescapeDataString(result.ResponseData.Substring(i + 7)))); } else { throw new InvalidOperationException(Resources.MobileServiceClient_Login_Invalid_Response_Format); } } } // Get the Mobile Services auth token and user data this.currentUserAuthenticationToken = response.Get(LoginAsyncAuthenticationTokenKey).AsString(); this.CurrentUser = new MobileServiceUser(response.Get("user").Get("userId").AsString()); } finally { this.LoginInProgress = false; } return this.CurrentUser; } /// <summary> /// Log a user out of a Mobile Services application. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Logout", Justification = "Logout is preferred by design")] public void Logout() { this.CurrentUser = null; this.currentUserAuthenticationToken = null; } /// <summary> /// Perform a web request and include the standard Mobile Services /// headers. /// </summary> /// <param name="method"> /// The HTTP method used to request the resource. /// </param> /// <param name="uriFragment"> /// URI of the resource to request (relative to the Mobile Services /// runtime). /// </param> /// <param name="content"> /// Optional content to send to the resource. /// </param> /// <returns>The JSON value of the response.</returns> internal async Task<JToken> RequestAsync(string method, string uriFragment, JToken content) { Debug.Assert(!string.IsNullOrEmpty(method), "method cannot be null or empty!"); Debug.Assert(!string.IsNullOrEmpty(uriFragment), "uriFragment cannot be null or empty!"); // Create the web request IServiceFilterRequest request = new ServiceFilterRequest(); request.Uri = new Uri(this.ApplicationUri, uriFragment); request.Method = method.ToUpper(); request.Accept = RequestJsonContentType; // Set Mobile Services authentication, application, and telemetry // headers request.Headers[RequestInstallationIdHeader] = applicationInstallationId; if (!string.IsNullOrEmpty(this.ApplicationKey)) { request.Headers[RequestApplicationKeyHeader] = this.ApplicationKey; } if (!string.IsNullOrEmpty(this.currentUserAuthenticationToken)) { request.Headers[RequestAuthenticationHeader] = this.currentUserAuthenticationToken; } // Add any request as JSON if (content != null) { request.ContentType = RequestJsonContentType; request.Content = content.ToString(); } // Send the request and get the response back as JSON IServiceFilterResponse response = await ServiceFilter.ApplyAsync(request, this.filter); JToken body = GetResponseJsonAsync(response); // Throw errors for any failing responses if (response.ResponseStatus != ServiceFilterResponseStatus.Success || response.StatusCode >= 400) { ThrowInvalidResponse(request, response, body); } return body; } /// <summary> /// Get the response text from an IServiceFilterResponse. /// </summary> /// <param name="response">The response.</param> /// <returns> /// Task that will complete when the response text has been obtained. /// </returns> [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Windows.Data.Json.JsonValue.TryParse(System.String,Windows.Data.Json.JsonValue@)", Justification = "We don't want to do anything if the Parse fails - just return null")] private static JToken GetResponseJsonAsync(IServiceFilterResponse response) { Debug.Assert(response != null, "response cannot be null."); // Try to parse the response as JSON JToken result = null; if (response.Content != null) { try { result = JToken.Parse(response.Content); } catch (Newtonsoft.Json.JsonException) { } } return result; } /// <summary> /// Throw an exception for an invalid response to a web request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> /// <param name="body">The body of the response as JSON.</param> private static void ThrowInvalidResponse(IServiceFilterRequest request, IServiceFilterResponse response, JToken body) { Debug.Assert(request != null, "request cannot be null!"); Debug.Assert(response != null, "response cannot be null!"); Debug.Assert( response.ResponseStatus != ServiceFilterResponseStatus.Success || response.StatusCode >= 400, "response should be failing!"); // Create either an invalid response or connection failed message // (check the status code first because some status codes will // set a protocol ErrorStatus). string message = null; if (response.StatusCode >= 400) { if (body != null) { if (body.Type == JTokenType.String) { // User scripts might return errors with just a plain string message as the // body content, so use it as the exception message message = body.ToString(); } else if (body.Type == JTokenType.Object) { // Get the error message, but default to the status description // below if there's no error message present. message = body.Get("error").AsString() ?? body.Get("description").AsString(); } } if (string.IsNullOrWhiteSpace(message)) { message = string.Format( CultureInfo.InvariantCulture, Resources.MobileServiceClient_ErrorMessage, response.StatusDescription); } } else { message = string.Format( CultureInfo.InvariantCulture, Resources.MobileServiceClient_ErrorMessage, response.ResponseStatus); } // Combine the pieces and throw the exception throw CreateMobileServiceException(message, request, response); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Tencent.Tencentmap.Mapsdk.Map { // Metadata.xml XPath class reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']" [global::Android.Runtime.Register ("com/tencent/tencentmap/mapsdk/map/Overlay", DoNotGenerateAcw=true)] public partial class Overlay : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/field[@name='SHADOW_X_SKEW']" [Register ("SHADOW_X_SKEW")] protected const float ShadowXSkew = (float) -0.890000; // Metadata.xml XPath field reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/field[@name='SHADOW_Y_SCALE']" [Register ("SHADOW_Y_SCALE")] protected const float ShadowYScale = (float) 0.500000; static IntPtr isVisible_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/field[@name='isVisible']" [Register ("isVisible")] protected bool IsVisible { get { if (isVisible_jfieldId == IntPtr.Zero) isVisible_jfieldId = JNIEnv.GetFieldID (class_ref, "isVisible", "Z"); return JNIEnv.GetBooleanField (Handle, isVisible_jfieldId); } set { if (isVisible_jfieldId == IntPtr.Zero) isVisible_jfieldId = JNIEnv.GetFieldID (class_ref, "isVisible", "Z"); JNIEnv.SetField (Handle, isVisible_jfieldId, value); } } static IntPtr mapView_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/field[@name='mapView']" [Register ("mapView")] protected global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView MapView { get { if (mapView_jfieldId == IntPtr.Zero) mapView_jfieldId = JNIEnv.GetFieldID (class_ref, "mapView", "Lcom/tencent/tencentmap/mapsdk/map/MapView;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, mapView_jfieldId); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (mapView_jfieldId == IntPtr.Zero) mapView_jfieldId = JNIEnv.GetFieldID (class_ref, "mapView", "Lcom/tencent/tencentmap/mapsdk/map/MapView;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); JNIEnv.SetField (Handle, mapView_jfieldId, native_value); JNIEnv.DeleteLocalRef (native_value); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/tencent/tencentmap/mapsdk/map/Overlay", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Overlay); } } protected Overlay (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/constructor[@name='Overlay' and count(parameter)=0]" [Register (".ctor", "()V", "")] public Overlay () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (Overlay)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } static Delegate cb_getId; #pragma warning disable 0169 static Delegate GetGetIdHandler () { if (cb_getId == null) cb_getId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetId); return cb_getId; } static IntPtr n_GetId (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Id); } #pragma warning restore 0169 static IntPtr id_getId; public virtual string Id { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='getId' and count(parameter)=0]" [Register ("getId", "()Ljava/lang/String;", "GetGetIdHandler")] get { if (id_getId == IntPtr.Zero) id_getId = JNIEnv.GetMethodID (class_ref, "getId", "()Ljava/lang/String;"); if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getId), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_isVisible; #pragma warning disable 0169 static Delegate GetIsVisibleHandler () { if (cb_isVisible == null) cb_isVisible = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsVisible); return cb_isVisible; } static bool n_IsVisible (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Visible; } #pragma warning restore 0169 static Delegate cb_setVisible_Z; #pragma warning disable 0169 static Delegate GetSetVisible_ZHandler () { if (cb_setVisible_Z == null) cb_setVisible_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetVisible_Z); return cb_setVisible_Z; } static void n_SetVisible_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Visible = p0; } #pragma warning restore 0169 static IntPtr id_isVisible; static IntPtr id_setVisible_Z; public virtual bool Visible { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='isVisible' and count(parameter)=0]" [Register ("isVisible", "()Z", "GetIsVisibleHandler")] get { if (id_isVisible == IntPtr.Zero) id_isVisible = JNIEnv.GetMethodID (class_ref, "isVisible", "()Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_isVisible); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isVisible", "()Z")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='setVisible' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setVisible", "(Z)V", "GetSetVisible_ZHandler")] set { if (id_setVisible_Z == IntPtr.Zero) id_setVisible_Z = JNIEnv.GetMethodID (class_ref, "setVisible", "(Z)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setVisible_Z, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setVisible", "(Z)V"), new JValue (value)); } } static Delegate cb_getZIndex; #pragma warning disable 0169 static Delegate GetGetZIndexHandler () { if (cb_getZIndex == null) cb_getZIndex = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, float>) n_GetZIndex); return cb_getZIndex; } static float n_GetZIndex (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.ZIndex; } #pragma warning restore 0169 static Delegate cb_setZIndex_F; #pragma warning disable 0169 static Delegate GetSetZIndex_FHandler () { if (cb_setZIndex_F == null) cb_setZIndex_F = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, float>) n_SetZIndex_F); return cb_setZIndex_F; } static void n_SetZIndex_F (IntPtr jnienv, IntPtr native__this, float p0) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.ZIndex = p0; } #pragma warning restore 0169 static IntPtr id_getZIndex; static IntPtr id_setZIndex_F; public virtual float ZIndex { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='getZIndex' and count(parameter)=0]" [Register ("getZIndex", "()F", "GetGetZIndexHandler")] get { if (id_getZIndex == IntPtr.Zero) id_getZIndex = JNIEnv.GetMethodID (class_ref, "getZIndex", "()F"); if (GetType () == ThresholdType) return JNIEnv.CallFloatMethod (Handle, id_getZIndex); else return JNIEnv.CallNonvirtualFloatMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getZIndex", "()F")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='setZIndex' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setZIndex", "(F)V", "GetSetZIndex_FHandler")] set { if (id_setZIndex_F == IntPtr.Zero) id_setZIndex_F = JNIEnv.GetMethodID (class_ref, "setZIndex", "(F)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setZIndex_F, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setZIndex", "(F)V"), new JValue (value)); } } static Delegate cb_checkInBounds; #pragma warning disable 0169 static Delegate GetCheckInBoundsHandler () { if (cb_checkInBounds == null) cb_checkInBounds = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_CheckInBounds); return cb_checkInBounds; } static bool n_CheckInBounds (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.CheckInBounds (); } #pragma warning restore 0169 static IntPtr id_checkInBounds; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='checkInBounds' and count(parameter)=0]" [Register ("checkInBounds", "()Z", "GetCheckInBoundsHandler")] public virtual bool CheckInBounds () { if (id_checkInBounds == IntPtr.Zero) id_checkInBounds = JNIEnv.GetMethodID (class_ref, "checkInBounds", "()Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_checkInBounds); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "checkInBounds", "()Z")); } static Delegate cb_destroy; #pragma warning disable 0169 static Delegate GetDestroyHandler () { if (cb_destroy == null) cb_destroy = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Destroy); return cb_destroy; } static void n_Destroy (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Destroy (); } #pragma warning restore 0169 static IntPtr id_destroy; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='destroy' and count(parameter)=0]" [Register ("destroy", "()V", "GetDestroyHandler")] public virtual void Destroy () { if (id_destroy == IntPtr.Zero) id_destroy = JNIEnv.GetMethodID (class_ref, "destroy", "()V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_destroy); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "destroy", "()V")); } static Delegate cb_draw_Landroid_graphics_Canvas_; #pragma warning disable 0169 static Delegate GetDraw_Landroid_graphics_Canvas_Handler () { if (cb_draw_Landroid_graphics_Canvas_ == null) cb_draw_Landroid_graphics_Canvas_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Draw_Landroid_graphics_Canvas_); return cb_draw_Landroid_graphics_Canvas_; } static void n_Draw_Landroid_graphics_Canvas_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Android.Graphics.Canvas p0 = global::Java.Lang.Object.GetObject<global::Android.Graphics.Canvas> (native_p0, JniHandleOwnership.DoNotTransfer); __this.Draw (p0); } #pragma warning restore 0169 static IntPtr id_draw_Landroid_graphics_Canvas_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='draw' and count(parameter)=1 and parameter[1][@type='android.graphics.Canvas']]" [Register ("draw", "(Landroid/graphics/Canvas;)V", "GetDraw_Landroid_graphics_Canvas_Handler")] public virtual void Draw (global::Android.Graphics.Canvas p0) { if (id_draw_Landroid_graphics_Canvas_ == IntPtr.Zero) id_draw_Landroid_graphics_Canvas_ = JNIEnv.GetMethodID (class_ref, "draw", "(Landroid/graphics/Canvas;)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_draw_Landroid_graphics_Canvas_, new JValue (p0)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "draw", "(Landroid/graphics/Canvas;)V"), new JValue (p0)); } static Delegate cb_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_; #pragma warning disable 0169 static Delegate GetDraw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler () { if (cb_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == null) cb_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_Draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_); return cb_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_; } static void n_Draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Android.Graphics.Canvas p0 = global::Java.Lang.Object.GetObject<global::Android.Graphics.Canvas> (native_p0, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p1 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView> (native_p1, JniHandleOwnership.DoNotTransfer); __this.Draw (p0, p1); } #pragma warning restore 0169 static IntPtr id_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='draw' and count(parameter)=2 and parameter[1][@type='android.graphics.Canvas'] and parameter[2][@type='com.tencent.tencentmap.mapsdk.map.MapView']]" [Register ("draw", "(Landroid/graphics/Canvas;Lcom/tencent/tencentmap/mapsdk/map/MapView;)V", "GetDraw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler")] protected virtual void Draw (global::Android.Graphics.Canvas p0, global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p1) { if (id_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == IntPtr.Zero) id_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNIEnv.GetMethodID (class_ref, "draw", "(Landroid/graphics/Canvas;Lcom/tencent/tencentmap/mapsdk/map/MapView;)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_draw_Landroid_graphics_Canvas_Lcom_tencent_tencentmap_mapsdk_map_MapView_, new JValue (p0), new JValue (p1)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "draw", "(Landroid/graphics/Canvas;Lcom/tencent/tencentmap/mapsdk/map/MapView;)V"), new JValue (p0), new JValue (p1)); } static Delegate cb_hashCodeRemote; #pragma warning disable 0169 static Delegate GetHashCodeRemoteHandler () { if (cb_hashCodeRemote == null) cb_hashCodeRemote = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_HashCodeRemote); return cb_hashCodeRemote; } static int n_HashCodeRemote (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.HashCodeRemote (); } #pragma warning restore 0169 static IntPtr id_hashCodeRemote; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='hashCodeRemote' and count(parameter)=0]" [Register ("hashCodeRemote", "()I", "GetHashCodeRemoteHandler")] public virtual int HashCodeRemote () { if (id_hashCodeRemote == IntPtr.Zero) id_hashCodeRemote = JNIEnv.GetMethodID (class_ref, "hashCodeRemote", "()I"); if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_hashCodeRemote); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "hashCodeRemote", "()I")); } static Delegate cb_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_; #pragma warning disable 0169 static Delegate GetInit_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler () { if (cb_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == null) cb_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Init_Lcom_tencent_tencentmap_mapsdk_map_MapView_); return cb_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_; } static void n_Init_Lcom_tencent_tencentmap_mapsdk_map_MapView_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView> (native_p0, JniHandleOwnership.DoNotTransfer); __this.Init (p0); } #pragma warning restore 0169 static IntPtr id_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='init' and count(parameter)=1 and parameter[1][@type='com.tencent.tencentmap.mapsdk.map.MapView']]" [Register ("init", "(Lcom/tencent/tencentmap/mapsdk/map/MapView;)V", "GetInit_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler")] public virtual void Init (global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p0) { if (id_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == IntPtr.Zero) id_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNIEnv.GetMethodID (class_ref, "init", "(Lcom/tencent/tencentmap/mapsdk/map/MapView;)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_init_Lcom_tencent_tencentmap_mapsdk_map_MapView_, new JValue (p0)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "init", "(Lcom/tencent/tencentmap/mapsdk/map/MapView;)V"), new JValue (p0)); } static Delegate cb_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_; #pragma warning disable 0169 static Delegate GetOnEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Handler () { if (cb_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_ == null) cb_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_); return cb_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_; } static void n_OnEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint> (native_p0, JniHandleOwnership.DoNotTransfer); __this.OnEmptyTap (p0); } #pragma warning restore 0169 static IntPtr id_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='onEmptyTap' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.GeoPoint']]" [Register ("onEmptyTap", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;)V", "GetOnEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Handler")] public virtual void OnEmptyTap (global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint p0) { if (id_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_ == IntPtr.Zero) id_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_ = JNIEnv.GetMethodID (class_ref, "onEmptyTap", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_onEmptyTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_, new JValue (p0)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onEmptyTap", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;)V"), new JValue (p0)); } static Delegate cb_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_; #pragma warning disable 0169 static Delegate GetOnLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler () { if (cb_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == null) cb_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, bool>) n_OnLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_); return cb_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_; } static bool n_OnLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint> (native_p0, JniHandleOwnership.DoNotTransfer); global::Android.Views.MotionEvent p1 = global::Java.Lang.Object.GetObject<global::Android.Views.MotionEvent> (native_p1, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p2 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView> (native_p2, JniHandleOwnership.DoNotTransfer); bool __ret = __this.OnLongPress (p0, p1, p2); return __ret; } #pragma warning restore 0169 static IntPtr id_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='onLongPress' and count(parameter)=3 and parameter[1][@type='com.tencent.mapsdk.raster.model.GeoPoint'] and parameter[2][@type='android.view.MotionEvent'] and parameter[3][@type='com.tencent.tencentmap.mapsdk.map.MapView']]" [Register ("onLongPress", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;Landroid/view/MotionEvent;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z", "GetOnLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler")] public virtual bool OnLongPress (global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint p0, global::Android.Views.MotionEvent p1, global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p2) { if (id_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == IntPtr.Zero) id_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNIEnv.GetMethodID (class_ref, "onLongPress", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;Landroid/view/MotionEvent;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z"); bool __ret; if (GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (Handle, id_onLongPress_Lcom_tencent_mapsdk_raster_model_GeoPoint_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_, new JValue (p0), new JValue (p1), new JValue (p2)); else __ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onLongPress", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;Landroid/view/MotionEvent;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z"), new JValue (p0), new JValue (p1), new JValue (p2)); return __ret; } static Delegate cb_onRemoveOverlay; #pragma warning disable 0169 static Delegate GetOnRemoveOverlayHandler () { if (cb_onRemoveOverlay == null) cb_onRemoveOverlay = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_OnRemoveOverlay); return cb_onRemoveOverlay; } static void n_OnRemoveOverlay (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.OnRemoveOverlay (); } #pragma warning restore 0169 static IntPtr id_onRemoveOverlay; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='onRemoveOverlay' and count(parameter)=0]" [Register ("onRemoveOverlay", "()V", "GetOnRemoveOverlayHandler")] public virtual void OnRemoveOverlay () { if (id_onRemoveOverlay == IntPtr.Zero) id_onRemoveOverlay = JNIEnv.GetMethodID (class_ref, "onRemoveOverlay", "()V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_onRemoveOverlay); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onRemoveOverlay", "()V")); } static Delegate cb_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_; #pragma warning disable 0169 static Delegate GetOnTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler () { if (cb_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == null) cb_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, bool>) n_OnTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_); return cb_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_; } static bool n_OnTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint> (native_p0, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p1 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView> (native_p1, JniHandleOwnership.DoNotTransfer); bool __ret = __this.OnTap (p0, p1); return __ret; } #pragma warning restore 0169 static IntPtr id_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='onTap' and count(parameter)=2 and parameter[1][@type='com.tencent.mapsdk.raster.model.GeoPoint'] and parameter[2][@type='com.tencent.tencentmap.mapsdk.map.MapView']]" [Register ("onTap", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z", "GetOnTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler")] public virtual bool OnTap (global::Com.Tencent.Mapsdk.Raster.Model.GeoPoint p0, global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p1) { if (id_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == IntPtr.Zero) id_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNIEnv.GetMethodID (class_ref, "onTap", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z"); bool __ret; if (GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (Handle, id_onTap_Lcom_tencent_mapsdk_raster_model_GeoPoint_Lcom_tencent_tencentmap_mapsdk_map_MapView_, new JValue (p0), new JValue (p1)); else __ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onTap", "(Lcom/tencent/mapsdk/raster/model/GeoPoint;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z"), new JValue (p0), new JValue (p1)); return __ret; } static Delegate cb_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_; #pragma warning disable 0169 static Delegate GetOnTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler () { if (cb_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == null) cb_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, bool>) n_OnTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_); return cb_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_; } static bool n_OnTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Android.Views.MotionEvent p0 = global::Java.Lang.Object.GetObject<global::Android.Views.MotionEvent> (native_p0, JniHandleOwnership.DoNotTransfer); global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p1 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView> (native_p1, JniHandleOwnership.DoNotTransfer); bool __ret = __this.OnTouchEvent (p0, p1); return __ret; } #pragma warning restore 0169 static IntPtr id_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='onTouchEvent' and count(parameter)=2 and parameter[1][@type='android.view.MotionEvent'] and parameter[2][@type='com.tencent.tencentmap.mapsdk.map.MapView']]" [Register ("onTouchEvent", "(Landroid/view/MotionEvent;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z", "GetOnTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_Handler")] public virtual bool OnTouchEvent (global::Android.Views.MotionEvent p0, global::Com.Tencent.Tencentmap.Mapsdk.Map.MapView p1) { if (id_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ == IntPtr.Zero) id_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_ = JNIEnv.GetMethodID (class_ref, "onTouchEvent", "(Landroid/view/MotionEvent;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z"); bool __ret; if (GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (Handle, id_onTouchEvent_Landroid_view_MotionEvent_Lcom_tencent_tencentmap_mapsdk_map_MapView_, new JValue (p0), new JValue (p1)); else __ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onTouchEvent", "(Landroid/view/MotionEvent;Lcom/tencent/tencentmap/mapsdk/map/MapView;)Z"), new JValue (p0), new JValue (p1)); return __ret; } static Delegate cb_remove; #pragma warning disable 0169 static Delegate GetRemoveHandler () { if (cb_remove == null) cb_remove = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Remove); return cb_remove; } static void n_Remove (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Tencentmap.Mapsdk.Map.Overlay> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Remove (); } #pragma warning restore 0169 static IntPtr id_remove; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.tencentmap.mapsdk.map']/class[@name='Overlay']/method[@name='remove' and count(parameter)=0]" [Register ("remove", "()V", "GetRemoveHandler")] public virtual void Remove () { if (id_remove == IntPtr.Zero) id_remove = JNIEnv.GetMethodID (class_ref, "remove", "()V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_remove); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "remove", "()V")); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; namespace Internal.Cryptography.Pal { /// <summary> /// Provides an implementation of an X509Store which is backed by files in a directory. /// </summary> internal class DirectoryBasedStoreProvider : IStorePal { // {thumbprint}.1.pfx to {thumbprint}.9.pfx private const int MaxSaveAttempts = 9; private const string PfxExtension = ".pfx"; // *.pfx ({thumbprint}.pfx or {thumbprint}.{ordinal}.pfx) private const string PfxWildcard = "*" + PfxExtension; // .*.pfx ({thumbprint}.{ordinal}.pfx) private const string PfxOrdinalWildcard = "." + PfxWildcard; private static string s_userStoreRoot; private readonly string _storePath; private readonly object _fileWatcherLock = new object(); private List<X509Certificate2> _certificates; private FileSystemWatcher _watcher; private readonly bool _readOnly; #if DEBUG static DirectoryBasedStoreProvider() { Debug.Assert( 0 == OpenFlags.ReadOnly, "OpenFlags.ReadOnly is not zero, read-only detection will not work"); } #endif internal DirectoryBasedStoreProvider(string storeName, OpenFlags openFlags) { if (string.IsNullOrEmpty(storeName)) { throw new CryptographicException(SR.Arg_EmptyOrNullString); } string directoryName = GetDirectoryName(storeName); if (s_userStoreRoot == null) { // Do this here instead of a static field initializer so that // the static initializer isn't capable of throwing the "home directory not found" // exception. s_userStoreRoot = PersistedFiles.GetUserFeatureDirectory("cryptography", "x509stores"); } _storePath = Path.Combine(s_userStoreRoot, directoryName); if (0 != (openFlags & OpenFlags.OpenExistingOnly)) { if (!Directory.Exists(_storePath)) { throw new CryptographicException(SR.Cryptography_X509_StoreNotFound); } } // ReadOnly is 0x00, so it is implicit unless either ReadWrite or MaxAllowed // was requested. OpenFlags writeFlags = openFlags & (OpenFlags.ReadWrite | OpenFlags.MaxAllowed); if (writeFlags == OpenFlags.ReadOnly) { _readOnly = true; } } public void Dispose() { if (_watcher != null) { _watcher.Dispose(); _watcher = null; } } public void FindAndCopyTo( X509FindType findType, object findValue, bool validOnly, X509Certificate2Collection collection) { } public byte[] Export(X509ContentType contentType, string password) { // Export is for X509Certificate2Collections in their IStorePal guise, // if someone wanted to export whole stores they'd need to do // store.Certificates.Export(...), which would end up in the // CollectionBackedStoreProvider. Debug.Fail("Export was unexpected on a DirectoryBasedStore"); throw new InvalidOperationException(); } public void CopyTo(X509Certificate2Collection collection) { Debug.Assert(collection != null); // Copy the reference locally, any directory change operations // will cause the field to be reset to null. List<X509Certificate2> certificates = _certificates; if (certificates == null) { // ReadDirectory will both load _certificates and return the answer, so this call // will have stable results across multiple adds/deletes happening in parallel. certificates = ReadDirectory(); Debug.Assert(certificates != null); } foreach (X509Certificate2 cert in certificates) { collection.Add(cert); } } private List<X509Certificate2> ReadDirectory() { if (!Directory.Exists(_storePath)) { // Don't assign the field here, because we don't have a FileSystemWatcher // yet to tell us that something has been added. return new List<X509Certificate2>(0); } List<X509Certificate2> certs = new List<X509Certificate2>(); lock (_fileWatcherLock) { if (_watcher == null) { _watcher = new FileSystemWatcher(_storePath, PfxWildcard) { NotifyFilter = NotifyFilters.LastWrite, }; FileSystemEventHandler handler = FlushCache; _watcher.Changed += handler; _watcher.Created += handler; _watcher.Deleted += handler; // The Renamed event has a different delegate type _watcher.Renamed += FlushCache; _watcher.Error += FlushCache; } // Start watching for change events to know that another instance // has messed with the underlying store. This keeps us aligned // with the Windows implementation, which opens stores with change // notifications. _watcher.EnableRaisingEvents = true; foreach (string filePath in Directory.EnumerateFiles(_storePath, PfxWildcard)) { X509Certificate2 cert; try { cert = new X509Certificate2(filePath); } catch (CryptographicException) { // The file wasn't a certificate, move on to the next one. continue; } certs.Add(cert); } // Don't release _fileWatcherLock until _certificates is assigned, otherwise // we may be setting it to a stale value after the change event said to clear it _certificates = certs; } return certs; } public void Add(ICertificatePal certPal) { if (_readOnly) { // Windows compatibility: Remove only throws when it needs to do work, add throws always. throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly); } // Save the collection to a local so it's consistent for the whole method List<X509Certificate2> certificates = _certificates; OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal; using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles())) { // certificates will be null if anything has changed since the last call to // get_Certificates; including Add being called without get_Certificates being // called at all. if (certificates != null) { foreach (X509Certificate2 inCollection in certificates) { if (inCollection.Equals(copy)) { if (!copy.HasPrivateKey || inCollection.HasPrivateKey) { // If the existing store only knows about a public key, but we're // adding a public+private pair, continue with the add. // // So, therefore, if we aren't adding a private key, or already have one, // we don't need to do anything. return; } } } } // This may well be the first time that we've added something to this store. Directory.CreateDirectory(_storePath); string thumbprint = copy.Thumbprint; bool findOpenSlot; // The odds are low that we'd have a thumbprint colission, but check anyways. string existingFilename = FindExistingFilename(copy, _storePath, out findOpenSlot); if (existingFilename != null) { bool dataExistsAlready = false; // If the file on disk is just a public key, but we're trying to add a private key, // we'll want to overwrite it. if (copy.HasPrivateKey) { try { using (X509Certificate2 fromFile = new X509Certificate2(existingFilename)) { if (fromFile.HasPrivateKey) { // We have a private key, the file has a private key, we're done here. dataExistsAlready = true; } } } catch (CryptographicException) { // We can't read this file anymore, but a moment ago it was this certificate, // so go ahead and overwrite it. } } else { // If we're just a public key then the file has at least as much data as we do. dataExistsAlready = true; } if (dataExistsAlready) { // The file was added but our collection hasn't resynced yet. // Set _certificates to null to force a resync. _certificates = null; return; } } string destinationFilename; FileMode mode = FileMode.CreateNew; if (existingFilename != null) { destinationFilename = existingFilename; mode = FileMode.Create; } else if (findOpenSlot) { destinationFilename = FindOpenSlot(thumbprint); } else { destinationFilename = Path.Combine(_storePath, thumbprint + PfxExtension); } using (FileStream stream = new FileStream(destinationFilename, mode)) { byte[] pkcs12 = copy.Export(X509ContentType.Pkcs12); stream.Write(pkcs12, 0, pkcs12.Length); } #if DEBUG // Verify that we're creating files with u+rw and o-rw, g-rw. const Interop.Sys.Permissions requiredPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR; const Interop.Sys.Permissions forbiddenPermissions = Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP; Interop.Sys.FileStatus stat; Debug.Assert(Interop.Sys.Stat(destinationFilename, out stat) == 0); Debug.Assert((stat.Mode & (int)requiredPermissions) != 0, "Created PFX has insufficient permissions to function"); Debug.Assert((stat.Mode & (int)forbiddenPermissions) == 0, "Created PFX has too broad of permissions"); #endif } // Null out _certificates so the next call to get_Certificates causes a re-scan. _certificates = null; } public void Remove(ICertificatePal certPal) { OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal; using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles())) { bool hadCandidates; string currentFilename = FindExistingFilename(copy, _storePath, out hadCandidates); if (currentFilename != null) { if (_readOnly) { // Windows compatibility, the readonly check isn't done until after a match is found. throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly); } File.Delete(currentFilename); } } // Null out _certificates so the next call to get_Certificates causes a re-scan. _certificates = null; } private static string FindExistingFilename(X509Certificate2 cert, string storePath, out bool hadCandidates) { hadCandidates = false; foreach (string maybeMatch in Directory.EnumerateFiles(storePath, cert.Thumbprint + PfxWildcard)) { hadCandidates = true; try { using (X509Certificate2 candidate = new X509Certificate2(maybeMatch)) { if (candidate.Equals(cert)) { return maybeMatch; } } } catch (CryptographicException) { // Contents weren't interpretable as a certificate, so it's not a match. } } return null; } private string FindOpenSlot(string thumbprint) { // We already know that {thumbprint}.pfx is taken, so start with {thumbprint}.1.pfx // We need space for {thumbprint} (thumbprint.Length) // And ".0.pfx" (6) // If MaxSaveAttempts is big enough to use more than one digit, we need that space, too (MaxSaveAttempts / 10) StringBuilder pathBuilder = new StringBuilder(thumbprint.Length + PfxOrdinalWildcard.Length + (MaxSaveAttempts / 10)); pathBuilder.Append(thumbprint); pathBuilder.Append('.'); int prefixLength = pathBuilder.Length; for (int i = 1; i <= MaxSaveAttempts; i++) { pathBuilder.Length = prefixLength; pathBuilder.Append(i); pathBuilder.Append(PfxExtension); string builtPath = Path.Combine(_storePath, pathBuilder.ToString()); if (!File.Exists(builtPath)) { return builtPath; } } throw new CryptographicException(SR.Cryptography_X509_StoreNoFileAvailable); } private void FlushCache(object sender, EventArgs e) { lock (_fileWatcherLock) { // Events might end up not firing until after the object was disposed, which could cause // problems consistently reading _watcher; so save it to a local. FileSystemWatcher watcher = _watcher; if (watcher != null) { // Stop processing events until we read again, particularly because // there's nothing else we'll do until then. watcher.EnableRaisingEvents = false; } _certificates = null; } } private static string GetDirectoryName(string storeName) { Debug.Assert(storeName != null); try { string fileName = Path.GetFileName(storeName); if (!StringComparer.Ordinal.Equals(storeName, fileName)) { throw new CryptographicException(SR.Format(SR.Security_InvalidValue, "storeName")); } } catch (IOException e) { throw new CryptographicException(e.Message, e); } return storeName.ToLowerInvariant(); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Collections; using System.Collections.Generic; #if !NET35 && !NET40 && !NETSTANDARD1_3 && !NETSTANDARD1_5 using System.Dynamic; #endif using System.Linq; using System.Reflection; using NLog.Common; using NLog.Config; /// <summary> /// Converts object into a List of property-names and -values using reflection /// </summary> internal class ObjectReflectionCache : IObjectTypeTransformer { private MruCache<Type, ObjectPropertyInfos> ObjectTypeCache => _objectTypeCache ?? System.Threading.Interlocked.CompareExchange(ref _objectTypeCache, new MruCache<Type, ObjectPropertyInfos>(10000), null) ?? _objectTypeCache; private MruCache<Type, ObjectPropertyInfos> _objectTypeCache; private readonly IServiceProvider _serviceProvider; private IObjectTypeTransformer ObjectTypeTransformation => _objectTypeTransformation ?? (_objectTypeTransformation = _serviceProvider?.GetService<IObjectTypeTransformer>() ?? this); private IObjectTypeTransformer _objectTypeTransformation; public ObjectReflectionCache(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } object IObjectTypeTransformer.TryTransformObject(object obj) { return null; } public ObjectPropertyList LookupObjectProperties(object value) { if (TryLookupExpandoObject(value, out var propertyValues)) { return propertyValues; } if (!ReferenceEquals(ObjectTypeTransformation, this)) { var result = ObjectTypeTransformation.TryTransformObject(value); if (result != null) { if (result is IConvertible) { return new ObjectPropertyList(result, ObjectPropertyInfos.SimpleToString.Properties, ObjectPropertyInfos.SimpleToString.FastLookup); } if (TryLookupExpandoObject(result, out propertyValues)) { return propertyValues; } value = result; } } var objectType = value.GetType(); var propertyInfos = BuildObjectPropertyInfos(value, objectType); ObjectTypeCache.TryAddValue(objectType, propertyInfos); return new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); } /// <summary> /// Try get value from <paramref name="value"/>, using <paramref name="objectPath"/>, and set into <paramref name="foundValue"/> /// </summary> public bool TryGetObjectProperty(object value, string[] objectPath, out object foundValue) { foundValue = null; if (objectPath is null) { return false; } for (int i = 0; i < objectPath.Length; ++i) { if (value is null) { // Found null foundValue = null; return true; } var eventProperties = LookupObjectProperties(value); if (eventProperties.TryGetPropertyValue(objectPath[i], out var propertyValue)) { value = propertyValue.Value; } else { foundValue = null; return false; //Wrong, but done } } foundValue = value; return true; } public bool TryLookupExpandoObject(object value, out ObjectPropertyList objectPropertyList) { if (value is IDictionary<string, object> expando) { objectPropertyList = new ObjectPropertyList(expando); return true; } #if !NET35 && !NET40 && !NETSTANDARD1_3 && !NETSTANDARD1_5 if (value is DynamicObject d) { var dictionary = DynamicObjectToDict(d); objectPropertyList = new ObjectPropertyList(dictionary); return true; } #endif Type objectType = value.GetType(); if (ObjectTypeCache.TryGetValue(objectType, out var propertyInfos)) { if (!propertyInfos.HasFastLookup) { var fastLookup = BuildFastLookup(propertyInfos.Properties, false); propertyInfos = new ObjectPropertyInfos(propertyInfos.Properties, fastLookup); ObjectTypeCache.TryAddValue(objectType, propertyInfos); } objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); return true; } if (TryExtractExpandoObject(objectType, out propertyInfos)) { ObjectTypeCache.TryAddValue(objectType, propertyInfos); objectPropertyList = new ObjectPropertyList(value, propertyInfos.Properties, propertyInfos.FastLookup); return true; } objectPropertyList = default(ObjectPropertyList); return false; } private static bool TryExtractExpandoObject(Type objectType, out ObjectPropertyInfos propertyInfos) { foreach (var interfaceType in objectType.GetInterfaces()) { if (IsGenericDictionaryEnumeratorType(interfaceType)) { var dictionaryEnumerator = (IDictionaryEnumerator)Activator.CreateInstance(typeof(DictionaryEnumerator<,>).MakeGenericType(interfaceType.GetGenericArguments())); propertyInfos = new ObjectPropertyInfos(null, new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => dictionaryEnumerator.GetEnumerator(o)) }); return true; } } propertyInfos = default(ObjectPropertyInfos); return false; } private static ObjectPropertyInfos BuildObjectPropertyInfos(object value, Type objectType) { ObjectPropertyInfos propertyInfos; if (ConvertSimpleToString(objectType)) { propertyInfos = ObjectPropertyInfos.SimpleToString; } else { var properties = GetPublicProperties(objectType); if (value is Exception) { // Special handling of Exception (Include Exception-Type as artificial first property) var fastLookup = BuildFastLookup(properties, true); propertyInfos = new ObjectPropertyInfos(properties, fastLookup); } else if (properties.Length == 0) { propertyInfos = ObjectPropertyInfos.SimpleToString; } else { propertyInfos = new ObjectPropertyInfos(properties, null); } } return propertyInfos; } private static bool ConvertSimpleToString(Type objectType) { if (typeof(IFormattable).IsAssignableFrom(objectType)) return true; if (typeof(Uri).IsAssignableFrom(objectType)) return true; if (typeof(MemberInfo).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(Assembly).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(Module).IsAssignableFrom(objectType)) return true; // Skip serializing all types in the application if (typeof(System.IO.Stream).IsAssignableFrom(objectType)) return true; // Skip serializing properties that often throws exceptions return false; } private static PropertyInfo[] GetPublicProperties(Type type) { PropertyInfo[] properties = null; try { properties = type.GetProperties(PublicProperties); } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to get object properties for type: {0}", type); } // Skip Index-Item-Properties (Ex. public string this[int Index]) if (properties != null) { foreach (var prop in properties) { if (!prop.IsValidPublicProperty()) { properties = properties.Where(p => p.IsValidPublicProperty()).ToArray(); break; } } } return properties ?? ArrayHelper.Empty<PropertyInfo>(); } private static FastPropertyLookup[] BuildFastLookup(PropertyInfo[] properties, bool includeType) { int fastAccessIndex = includeType ? 1 : 0; FastPropertyLookup[] fastLookup = new FastPropertyLookup[properties.Length + fastAccessIndex]; if (includeType) { fastLookup[0] = new FastPropertyLookup("Type", TypeCode.String, (o, p) => o.GetType().ToString()); } foreach (var prop in properties) { var getterMethod = prop.GetGetMethod(); Type propertyType = getterMethod.ReturnType; ReflectionHelpers.LateBoundMethod valueLookup = ReflectionHelpers.CreateLateBoundMethod(getterMethod); #if NETSTANDARD1_3 TypeCode typeCode = propertyType == typeof(string) ? TypeCode.String : (propertyType == typeof(int) ? TypeCode.Int32 : TypeCode.Object); #else TypeCode typeCode = Type.GetTypeCode(propertyType); // Skip cyclic-reference checks when not TypeCode.Object #endif fastLookup[fastAccessIndex++] = new FastPropertyLookup(prop.Name, typeCode, valueLookup); } return fastLookup; } private const BindingFlags PublicProperties = BindingFlags.Instance | BindingFlags.Public; internal struct ObjectPropertyList : IEnumerable<ObjectPropertyList.PropertyValue> { internal static readonly StringComparer NameComparer = StringComparer.Ordinal; private static readonly FastPropertyLookup[] CreateIDictionaryEnumerator = new[] { new FastPropertyLookup(string.Empty, TypeCode.Object, (o, p) => ((IDictionary<string, object>)o).GetEnumerator()) }; private readonly object _object; private readonly PropertyInfo[] _properties; private readonly FastPropertyLookup[] _fastLookup; public struct PropertyValue { public readonly string Name; public readonly object Value; public TypeCode TypeCode => Value is null ? TypeCode.Empty : _typecode; private readonly TypeCode _typecode; public bool HasNameAndValue => Name != null && Value != null; public PropertyValue(string name, object value, TypeCode typeCode) { Name = name; Value = value; _typecode = typeCode; } public PropertyValue(object owner, PropertyInfo propertyInfo) { Name = propertyInfo.Name; Value = propertyInfo.GetValue(owner, null); _typecode = TypeCode.Object; } public PropertyValue(object owner, FastPropertyLookup fastProperty) { Name = fastProperty.Name; Value = fastProperty.ValueLookup(owner, null); _typecode = fastProperty.TypeCode; } } public bool IsSimpleValue => _properties?.Length == 0; public object ObjectValue => _object; internal ObjectPropertyList(object value, PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { _object = value; _properties = properties; _fastLookup = fastLookup; } public ObjectPropertyList(IDictionary<string, object> value) { _object = value; // Expando objects _properties = null; _fastLookup = CreateIDictionaryEnumerator; } public bool TryGetPropertyValue(string name, out PropertyValue propertyValue) { if (_properties != null) { if (_fastLookup != null) { return TryFastLookupPropertyValue(name, out propertyValue); } else { return TrySlowLookupPropertyValue(name, out propertyValue); } } else if (_object is IDictionary<string, object> expandoObject) { if (expandoObject.TryGetValue(name, out var objectValue)) { propertyValue = new PropertyValue(name, objectValue, TypeCode.Object); return true; } propertyValue = default(PropertyValue); return false; } else { return TryListLookupPropertyValue(name, out propertyValue); } } /// <summary> /// Scans properties for name (Skips string-compare and value-lookup until finding match) /// </summary> private bool TryFastLookupPropertyValue(string name, out PropertyValue propertyValue) { int nameHashCode = NameComparer.GetHashCode(name); foreach (var fastProperty in _fastLookup) { if (fastProperty.NameHashCode == nameHashCode && NameComparer.Equals(fastProperty.Name, name)) { propertyValue = new PropertyValue(_object, fastProperty); return true; } } propertyValue = default(PropertyValue); return false; } /// <summary> /// Scans properties for name (Skips property value lookup until finding match) /// </summary> private bool TrySlowLookupPropertyValue(string name, out PropertyValue propertyValue) { foreach (var propInfo in _properties) { if (NameComparer.Equals(propInfo.Name, name)) { propertyValue = new PropertyValue(_object, propInfo); return true; } } propertyValue = default(PropertyValue); return false; } /// <summary> /// Scans properties for name /// </summary> private bool TryListLookupPropertyValue(string name, out PropertyValue propertyValue) { foreach (var item in this) { if (NameComparer.Equals(item.Name, name)) { propertyValue = item; return true; } } propertyValue = default(PropertyValue); return false; } public override string ToString() { return _object?.ToString() ?? "null"; } public Enumerator GetEnumerator() { if (_properties != null) return new Enumerator(_object, _properties, _fastLookup); else return new Enumerator((IEnumerator<KeyValuePair<string, object>>)_fastLookup[0].ValueLookup(_object, null)); } IEnumerator<PropertyValue> IEnumerable<PropertyValue>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<PropertyValue> { private readonly object _owner; private readonly PropertyInfo[] _properties; private readonly FastPropertyLookup[] _fastLookup; private readonly IEnumerator<KeyValuePair<string, object>> _enumerator; private int _index; internal Enumerator(object owner, PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { _owner = owner; _properties = properties; _fastLookup = fastLookup; _index = -1; _enumerator = null; } internal Enumerator(IEnumerator<KeyValuePair<string, object>> enumerator) { _owner = enumerator; _properties = null; _fastLookup = null; _index = 0; _enumerator = enumerator; } public PropertyValue Current { get { try { if (_fastLookup != null) return new PropertyValue(_owner, _fastLookup[_index]); else if (_properties != null) return new PropertyValue(_owner, _properties[_index]); else return new PropertyValue(_enumerator.Current.Key, _enumerator.Current.Value, TypeCode.Object); } catch (Exception ex) { InternalLogger.Debug(ex, "Failed to get property value for object: {0}", _owner); return default(PropertyValue); } } } object IEnumerator.Current => Current; public void Dispose() { _enumerator?.Dispose(); } public bool MoveNext() { if (_properties != null) return ++_index < (_fastLookup?.Length ?? _properties.Length); else return _enumerator.MoveNext(); } public void Reset() { if (_properties != null) _index = -1; else _enumerator.Reset(); } } } internal struct FastPropertyLookup { public readonly string Name; public readonly ReflectionHelpers.LateBoundMethod ValueLookup; public readonly TypeCode TypeCode; public readonly int NameHashCode; public FastPropertyLookup(string name, TypeCode typeCode, ReflectionHelpers.LateBoundMethod valueLookup) { Name = name; ValueLookup = valueLookup; TypeCode = typeCode; NameHashCode = ObjectPropertyList.NameComparer.GetHashCode(name); } } private struct ObjectPropertyInfos : IEquatable<ObjectPropertyInfos> { public readonly PropertyInfo[] Properties; public readonly FastPropertyLookup[] FastLookup; public static readonly ObjectPropertyInfos SimpleToString = new ObjectPropertyInfos(ArrayHelper.Empty<PropertyInfo>(), ArrayHelper.Empty<FastPropertyLookup>()); public ObjectPropertyInfos(PropertyInfo[] properties, FastPropertyLookup[] fastLookup) { Properties = properties; FastLookup = fastLookup; } public bool HasFastLookup => FastLookup != null; public bool Equals(ObjectPropertyInfos other) { return ReferenceEquals(Properties, other.Properties) && FastLookup?.Length == other.FastLookup?.Length; } } #if !NET35 && !NET40 && !NETSTANDARD1_3 && !NETSTANDARD1_5 private static Dictionary<string, object> DynamicObjectToDict(DynamicObject d) { var newVal = new Dictionary<string, object>(); foreach (var propName in d.GetDynamicMemberNames()) { if (d.TryGetMember(new GetBinderAdapter(propName), out var result)) { newVal[propName] = result; } } return newVal; } /// <summary> /// Binder for retrieving value of <see cref="DynamicObject"/> /// </summary> private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(string name) : base(name, false) { } /// <inheritdoc/> public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { return target; } } #endif private static bool IsGenericDictionaryEnumeratorType(Type interfaceType) { if (interfaceType.IsGenericType()) { if (interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>) #if !NET35 || interfaceType.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>) #endif ) { if (interfaceType.GetGenericArguments()[0] == typeof(string)) { return true; } } } return false; } private interface IDictionaryEnumerator { IEnumerator<KeyValuePair<string,object>> GetEnumerator(object value); } internal sealed class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator { public IEnumerator<KeyValuePair<string, object>> GetEnumerator(object value) { if (value is IDictionary<TKey, TValue> dictionary) { if (dictionary.Count > 0) return YieldEnumerator(dictionary); } #if !NET35 else if (value is IReadOnlyDictionary<TKey, TValue> readonlyDictionary) { if (readonlyDictionary.Count > 0) return YieldEnumerator(readonlyDictionary); } #endif return EmptyDictionaryEnumerator.Default; } private IEnumerator<KeyValuePair<string, object>> YieldEnumerator(IDictionary<TKey,TValue> dictionary) { foreach (var item in dictionary) yield return new KeyValuePair<string, object>(item.Key.ToString(), item.Value); } #if !NET35 private IEnumerator<KeyValuePair<string, object>> YieldEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { foreach (var item in dictionary) yield return new KeyValuePair<string, object>(item.Key.ToString(), item.Value); } #endif private sealed class EmptyDictionaryEnumerator : IEnumerator<KeyValuePair<string, object>> { public static readonly EmptyDictionaryEnumerator Default = new EmptyDictionaryEnumerator(); KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current => default(KeyValuePair<string, object>); object IEnumerator.Current => default(KeyValuePair<string, object>); bool IEnumerator.MoveNext() => false; void IDisposable.Dispose() { // Nothing here on purpose } void IEnumerator.Reset() { // Nothing here on purpose } } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //---------------------------------------- function ChooseLevelDlg::onWake( %this ) { CL_levelList.clear(); ChooseLevelWindow->SmallPreviews.clear(); %this->CurrentPreview.visible = false; %this->levelName.visible = false; %this->LevelDescriptionLabel.visible = false; %this->LevelDescription.visible = false; %assetQuery = new AssetQuery(); AssetDatabase.findAssetType(%assetQuery, "LevelAsset"); %count = %assetQuery.getCount(); if(%count == 0 && !IsDirectory("tools")) { //We have no levels found. Prompt the user to open the editor to the default level if the tools are present MessageBoxOK("Error", "No levels were found in any modules. Please ensure you have modules loaded that contain gameplay code and level files.", "Canvas.popDialog(ChooseLevelDlg); if(isObject(ChooseLevelDlg.returnGui) && ChooseLevelDlg.returnGui.isMethod(\"onReturnTo\")) ChooseLevelDlg.returnGui.onReturnTo();"); %assetQuery.delete(); return; } for(%i=0; %i < %count; %i++) { %assetId = %assetQuery.getAsset(%i); %levelAsset = AssetDatabase.acquireAsset(%assetId); %file = %levelAsset.LevelFile; if ( !isFile(%file @ ".mis") && !isFile(%file) ) continue; // Skip our new level/mission if we arent choosing a level // to launch in the editor. if ( !%this.launchInEditor ) { %fileName = fileName(%file); if (strstr(%fileName, "newMission.mis") > -1 || strstr(%fileName, "newLevel.mis") > -1) continue; } %this.addLevelAsset( %levelAsset ); } // Also add the new level mission as defined in the world editor settings // if we are choosing a level to launch in the editor. if ( %this.launchInEditor ) { %file = EditorSettings.value( "WorldEditor/newLevelFile" ); if ( %file !$= "" ) %this.addMissionFile( %file ); } // Sort our list CL_levelList.sort(0); // Set the first row as the selected row CL_levelList.setSelectedRow(0); for (%i = 0; %i < CL_levelList.rowCount(); %i++) { %preview = new GuiButtonCtrl() { profile = "GuiMenuButtonProfile"; internalName = "SmallPreview" @ %i; Extent = "368 35"; text = getField(CL_levelList.getRowText(%i), 0); command = "ChooseLevelWindow.previewSelected(ChooseLevelWindow->SmallPreviews->SmallPreview" @ %i @ ");"; buttonType = "RadioButton"; }; ChooseLevelWindow->SmallPreviews.add(%preview); %rowText = CL_levelList.getRowText(%i); // Set the level index %preview.levelIndex = %i; // Get the name %name = getField(CL_levelList.getRowText(%i), 0); %preview.levelName = %name; %file = getField(CL_levelList.getRowText(%i), 1); // Find the preview image %levelPreview = getField(CL_levelList.getRowText(%i), 3); // Test against all of the different image formats // This should probably be moved into an engine function if (isFile(%levelPreview @ ".png") || isFile(%levelPreview @ ".jpg") || isFile(%levelPreview @ ".bmp") || isFile(%levelPreview @ ".gif") || isFile(%levelPreview @ ".jng") || isFile(%levelPreview @ ".mng") || isFile(%levelPreview @ ".tga")) { %preview.bitmap = %levelPreview; } // Get the description %desc = getField(CL_levelList.getRowText(%i), 2); %preview.levelDesc = %desc; } ChooseLevelWindow->SmallPreviews.firstVisible = -1; ChooseLevelWindow->SmallPreviews.lastVisible = -1; if (ChooseLevelWindow->SmallPreviews.getCount() > 0) { ChooseLevelWindow->SmallPreviews.firstVisible = 0; if (ChooseLevelWindow->SmallPreviews.getCount() < 6) ChooseLevelWindow->SmallPreviews.lastVisible = ChooseLevelWindow->SmallPreviews.getCount() - 1; else ChooseLevelWindow->SmallPreviews.lastVisible = 4; } if (ChooseLevelWindow->SmallPreviews.getCount() > 0) ChooseLevelWindow.previewSelected(ChooseLevelWindow->SmallPreviews.getObject(0)); // If we have 5 or less previews then hide our next/previous buttons // and resize to fill their positions if (ChooseLevelWindow->SmallPreviews.getCount() < 6) { ChooseLevelWindow->PreviousSmallPreviews.setVisible(false); ChooseLevelWindow->NextSmallPreviews.setVisible(false); %previewPos = ChooseLevelWindow->SmallPreviews.getPosition(); %previousPos = ChooseLevelWindow->PreviousSmallPreviews.getPosition(); %previewPosX = getWord(%previousPos, 0); %previewPosY = getWord(%previewPos, 1); ChooseLevelWindow->SmallPreviews.setPosition(%previewPosX, %previewPosY); ChooseLevelWindow->SmallPreviews.colSpacing = 10;//((getWord(NextSmallPreviews.getPosition(), 0)+11)-getWord(PreviousSmallPreviews.getPosition(), 0))/4; ChooseLevelWindow->SmallPreviews.refresh(); } /*if (ChooseLevelWindow->SmallPreviews.getCount() <= 1) { // Hide the small previews ChooseLevelWindow->SmallPreviews.setVisible(false); // Shrink the ChooseLevelWindow so that we don't have a large blank space %extentX = getWord(ChooseLevelWindow.getExtent(), 0); %extentY = getWord(ChooseLevelWindow->SmallPreviews.getPosition(), 1); ChooseLevelWIndow.setExtent(%extentX, %extentY); } else { // Make sure the small previews are visible ChooseLevelWindow->SmallPreviews.setVisible(true); %extentX = getWord(ChooseLevelWindow.getExtent(), 0); %extentY = getWord(ChooseLevelWindow->SmallPreviews.getPosition(), 1); %extentY = %extentY + getWord(ChooseLevelWindow->SmallPreviews.getExtent(), 1); %extentY = %extentY + 9; //ChooseLevelWIndow.setExtent(%extentX, %extentY); //}*/ } function ChooseLevelDlg::addMissionFile( %this, %file ) { %levelName = fileBase(%file); %levelDesc = "A Torque level"; %LevelInfoObject = getLevelInfo(%file); if (%LevelInfoObject != 0) { if(%LevelInfoObject.levelName !$= "") %levelName = %LevelInfoObject.levelName; else if(%LevelInfoObject.name !$= "") %levelName = %LevelInfoObject.name; if (%LevelInfoObject.desc0 !$= "") %levelDesc = %LevelInfoObject.desc0; if (%LevelInfoObject.preview !$= "") %levelPreview = %LevelInfoObject.preview; %LevelInfoObject.delete(); } CL_levelList.addRow( CL_levelList.rowCount(), %levelName TAB %file TAB %levelDesc TAB %levelPreview ); } function ChooseLevelDlg::addLevelAsset( %this, %levelAsset ) { %file = %levelAsset.LevelFile; /*%levelName = fileBase(%file); %levelDesc = "A Torque level"; %LevelInfoObject = getLevelInfo(%file); if (%LevelInfoObject != 0) { if(%LevelInfoObject.levelName !$= "") %levelName = %LevelInfoObject.levelName; else if(%LevelInfoObject.name !$= "") %levelName = %LevelInfoObject.name; if (%LevelInfoObject.desc0 !$= "") %levelDesc = %LevelInfoObject.desc0; if (%LevelInfoObject.preview !$= "") %levelPreview = %LevelInfoObject.preview; %LevelInfoObject.delete(); }*/ %levelName = %levelAsset.friendlyName; %levelDesc = %levelAsset.description; %levelPreview = %levelAsset.levelPreviewImage; CL_levelList.addRow( CL_levelList.rowCount(), %levelName TAB %file TAB %levelDesc TAB %levelPreview ); } function ChooseLevelDlg::onSleep( %this ) { // This is set from the outside, only stays true for a single wake/sleep // cycle. %this.launchInEditor = false; } function ChooseLevelWindow::previewSelected(%this, %preview) { // Set the selected level if (isObject(%preview) && %preview.levelIndex !$= "") CL_levelList.setSelectedRow(%preview.levelIndex); else CL_levelList.setSelectedRow(-1); // Set the large preview image if (isObject(%preview) && %preview.bitmap !$= "") { %this->CurrentPreview.visible = true; %this->CurrentPreview.setBitmap(%preview.bitmap); } else { %this->CurrentPreview.visible = false; } // Set the current level name if (isObject(%preview) && %preview.levelName !$= "") { %this->LevelName.visible = true; %this->LevelName.setText(%preview.levelName); } else { %this->LevelName.visible = false; } // Set the current level description if (isObject(%preview) && %preview.levelDesc !$= "") { %this->LevelDescription.visible = true; %this->LevelDescriptionLabel.visible = true; %this->LevelDescription.setText(%preview.levelDesc); } else { %this->LevelDescription.visible = false; %this->LevelDescriptionLabel.visible = false; } } function ChooseLevelWindow::previousPreviews(%this) { %prevHiddenIdx = %this->SmallPreviews.firstVisible - 1; if (%prevHiddenIdx < 0) return; %lastVisibleIdx = %this->SmallPreviews.lastVisible; if (%lastVisibleIdx >= %this->SmallPreviews.getCount()) return; %prevHiddenObj = %this->SmallPreviews.getObject(%prevHiddenIdx); %lastVisibleObj = %this->SmallPreviews.getObject(%lastVisibleIdx); if (isObject(%prevHiddenObj) && isObject(%lastVisibleObj)) { %this->SmallPreviews.firstVisible--; %this->SmallPreviews.lastVisible--; %prevHiddenObj.setVisible(true); %lastVisibleObj.setVisible(false); } } function ChooseLevelWindow::nextPreviews(%this) { %firstVisibleIdx = %this->SmallPreviews.firstVisible; if (%firstVisibleIdx < 0) return; %firstHiddenIdx = %this->SmallPreviews.lastVisible + 1; if (%firstHiddenIdx >= %this->SmallPreviews.getCount()) return; %firstVisibleObj = %this->SmallPreviews.getObject(%firstVisibleIdx); %firstHiddenObj = %this->SmallPreviews.getObject(%firstHiddenIdx); if (isObject(%firstVisibleObj) && isObject(%firstHiddenObj)) { %this->SmallPreviews.firstVisible++; %this->SmallPreviews.lastVisible++; %firstVisibleObj.setVisible(false); %firstHiddenObj.setVisible(true); } } // Do this onMouseUp not via Command which occurs onMouseDown so we do // not have a lingering mouseUp event lingering in the ether. function ChooseLevelDlgGoBtn::onMouseUp( %this ) { // So we can't fire the button when loading is in progress. if ( isObject( ServerGroup ) ) return; // Launch the chosen level with the editor open? if ( ChooseLevelDlg.launchInEditor ) { activatePackage( "BootEditor" ); ChooseLevelDlg.launchInEditor = false; StartGame("", "SinglePlayer"); } else { StartGame(); } }
/** * JsonData.cs * Generic type to hold JSON data (objects, arrays, and so on). This is * the default type returned by JsonMapper.ToObject(). * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; namespace LeaderboardExample { public class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private float inst_single; private double inst_double; private int inst_int; private long inst_long; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection ().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsSingle { get { return type == JsonType.Single; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection ().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection ().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary ().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary ().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary (); IList<string> keys = new List<string> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add (entry.Key); } return (ICollection) keys; } } ICollection IDictionary.Values { get { EnsureDictionary (); IList<JsonData> values = new List<JsonData> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add (entry.Value); } return (ICollection) values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsSingle { get { return IsSingle; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList ().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList ().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary ()[key]; } set { if (! (key is String)) throw new ArgumentException ( "The key has to be a string"); JsonData data = ToJsonData (value); this[(string) key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary (); return object_list[idx].Value; } set { EnsureDictionary (); JsonData data = ToJsonData (value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList ()[index]; } set { EnsureList (); JsonData data = ToJsonData (value); this[index] = data; } } #endregion #region Public Indexers public JsonData this[string prop_name] { get { EnsureDictionary (); return inst_object[prop_name]; } set { EnsureDictionary (); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (prop_name, value); if (inst_object.ContainsKey (prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add (entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection (); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection (); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData> (entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData () { } public JsonData (bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData(float number) { type = JsonType.Single; inst_single = number; } public JsonData (double number) { type = JsonType.Double; inst_double = number; } public JsonData (int number) { type = JsonType.Int; inst_int = number; } public JsonData (long number) { type = JsonType.Long; inst_long = number; } public JsonData (object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool) obj; return; } if (obj is Single) { type = JsonType.Single; inst_single = (float)obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double) obj; return; } if (obj is Int32) { type = JsonType.Int; inst_int = (int) obj; return; } if (obj is Int64) { type = JsonType.Long; inst_long = (long) obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string) obj; return; } throw new ArgumentException ( "Unable to wrap the given object with JsonData"); } public JsonData (string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData (Boolean data) { return new JsonData (data); } public static implicit operator JsonData(Single data) { return new JsonData(data); } public static implicit operator JsonData (Double data) { return new JsonData (data); } public static implicit operator JsonData (Int32 data) { return new JsonData (data); } public static implicit operator JsonData (Int64 data) { return new JsonData (data); } public static implicit operator JsonData (String data) { return new JsonData (data); } #endregion #region Explicit Conversions public static explicit operator Boolean (JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException ( "Instance of JsonData doesn't hold a boolean"); return data.inst_boolean; } public static explicit operator Single(JsonData data) { if (data.type != JsonType.Single) throw new InvalidCastException( "Instance of JsonData doesn't hold a single"); return data.inst_single; } public static explicit operator Double (JsonData data) { if (data.type != JsonType.Double) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator Int32 (JsonData data) { if (data.type != JsonType.Int) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_int; } public static explicit operator Int64 (JsonData data) { if (data.type != JsonType.Long) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_long; } public static explicit operator String (JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException ( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo (Array array, int index) { EnsureCollection ().CopyTo (array, index); } #endregion #region IDictionary Methods void IDictionary.Add (object key, object value) { JsonData data = ToJsonData (value); EnsureDictionary ().Add (key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> ((string) key, data); object_list.Add (entry); json = null; } void IDictionary.Clear () { EnsureDictionary ().Clear (); object_list.Clear (); json = null; } bool IDictionary.Contains (object key) { return EnsureDictionary ().Contains (key); } IDictionaryEnumerator IDictionary.GetEnumerator () { return ((IOrderedDictionary) this).GetEnumerator (); } void IDictionary.Remove (object key) { EnsureDictionary ().Remove (key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string) key) { object_list.RemoveAt (i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator () { return EnsureCollection ().GetEnumerator (); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean () { if (type != JsonType.Boolean) throw new InvalidOperationException ( "JsonData instance doesn't hold a boolean"); return inst_boolean; } float IJsonWrapper.GetSingle() { if (type != JsonType.Single) throw new InvalidOperationException( "JsonData instance doesn't hold a single"); return inst_single; } double IJsonWrapper.GetDouble () { if (type != JsonType.Double) throw new InvalidOperationException ( "JsonData instance doesn't hold a double"); return inst_double; } int IJsonWrapper.GetInt () { if (type != JsonType.Int) throw new InvalidOperationException ( "JsonData instance doesn't hold an int"); return inst_int; } long IJsonWrapper.GetLong () { if (type != JsonType.Long) throw new InvalidOperationException ( "JsonData instance doesn't hold a long"); return inst_long; } string IJsonWrapper.GetString () { if (type != JsonType.String) throw new InvalidOperationException ( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean (bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetSingle(float val) { type = JsonType.Single; inst_single = val; json = null; } void IJsonWrapper.SetDouble (double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetInt (int val) { type = JsonType.Int; inst_int = val; json = null; } void IJsonWrapper.SetLong (long val) { type = JsonType.Long; inst_long = val; json = null; } void IJsonWrapper.SetString (string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson () { return ToJson (); } void IJsonWrapper.ToJson (JsonWriter writer) { ToJson (writer); } #endregion #region IList Methods int IList.Add (object value) { return Add (value); } void IList.Clear () { EnsureList ().Clear (); json = null; } bool IList.Contains (object value) { return EnsureList ().Contains (value); } int IList.IndexOf (object value) { return EnsureList ().IndexOf (value); } void IList.Insert (int index, object value) { EnsureList ().Insert (index, value); json = null; } void IList.Remove (object value) { EnsureList ().Remove (value); json = null; } void IList.RemoveAt (int index) { EnsureList ().RemoveAt (index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator () { EnsureDictionary (); return new OrderedDictionaryEnumerator ( object_list.GetEnumerator ()); } void IOrderedDictionary.Insert (int idx, object key, object value) { string property = (string) key; JsonData data = ToJsonData (value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (property, data); object_list.Insert (idx, entry); } void IOrderedDictionary.RemoveAt (int idx) { EnsureDictionary (); inst_object.Remove (object_list[idx].Key); object_list.RemoveAt (idx); } #endregion #region Private Methods private ICollection EnsureCollection () { if (type == JsonType.Array) return (ICollection) inst_array; if (type == JsonType.Object) return (ICollection) inst_object; throw new InvalidOperationException ( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary () { if (type == JsonType.Object) return (IDictionary) inst_object; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); return (IDictionary) inst_object; } private IList EnsureList () { if (type == JsonType.Array) return (IList) inst_array; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData> (); return (IList) inst_array; } private JsonData ToJsonData (object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData) obj; return new JsonData (obj); } private static void WriteJson (IJsonWrapper obj, JsonWriter writer) { if (obj.IsString) { writer.Write (obj.GetString ()); return; } if (obj.IsBoolean) { writer.Write (obj.GetBoolean ()); return; } if (obj.IsSingle) { writer.Write(obj.GetSingle()); return; } if (obj.IsDouble) { writer.Write (obj.GetDouble ()); return; } if (obj.IsInt) { writer.Write (obj.GetInt ()); return; } if (obj.IsLong) { writer.Write (obj.GetLong ()); return; } if (obj.IsArray) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteJson ((JsonData) elem, writer); writer.WriteArrayEnd (); return; } if (obj.IsObject) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in ((IDictionary) obj)) { writer.WritePropertyName ((string) entry.Key); WriteJson ((JsonData) entry.Value, writer); } writer.WriteObjectEnd (); return; } } #endregion public int Add (object value) { JsonData data = ToJsonData (value); json = null; return EnsureList ().Add (data); } public void Clear () { if (IsObject) { ((IDictionary) this).Clear (); return; } if (IsArray) { ((IList) this).Clear (); return; } } public bool Equals (JsonData x) { if (x == null) return false; if (x.type != this.type) return false; switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals (x.inst_object); case JsonType.Array: return this.inst_array.Equals (x.inst_array); case JsonType.String: return this.inst_string.Equals (x.inst_string); case JsonType.Int: return this.inst_int.Equals (x.inst_int); case JsonType.Long: return this.inst_long.Equals (x.inst_long); case JsonType.Single: return this.inst_single.Equals(x.inst_single); case JsonType.Double: return this.inst_double.Equals (x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals (x.inst_boolean); } return false; } public JsonType GetJsonType () { return type; } public void SetJsonType (JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); break; case JsonType.Array: inst_array = new List<JsonData> (); break; case JsonType.String: inst_string = default (String); break; case JsonType.Int: inst_int = default (Int32); break; case JsonType.Long: inst_long = default (Int64); break; case JsonType.Single: inst_single = default(Single); break; case JsonType.Double: inst_double = default (Double); break; case JsonType.Boolean: inst_boolean = default (Boolean); break; } this.type = type; } public string ToJson () { if (json != null) return json; StringWriter sw = new StringWriter (); JsonWriter writer = new JsonWriter (sw); writer.Validate = false; WriteJson (this, writer); json = sw.ToString (); return json; } public void ToJson (JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson (this, writer); writer.Validate = old_validate; } public override string ToString () { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString (); case JsonType.Single: return inst_single.ToString(); case JsonType.Double: return inst_double.ToString (); case JsonType.Int: return inst_int.ToString (); case JsonType.Long: return inst_long.ToString (); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry (curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator ( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext () { return list_enumerator.MoveNext (); } public void Reset () { list_enumerator.Reset (); } } }
using System; using System.ComponentModel; using GLib; using Gtk; using MyExtensions; /// <summary> /// Contains basic examples of TreeView CellRenderers /// </summary> public partial class MainWindow : Gtk.Window { private ListStore listStore1; public MainWindow() : base(Gtk.WindowType.Toplevel) { this.Build(); this.SetupTreeView(); } public enum Column : int { [Description("Text String")] TextString, [Description("Text Double")] TextDouble, [Description("Text Bool")] TextBool, [Description("Toggle Check Box")] ToggleCheckBox, [Description("Toggle Radio Button")] ToggleRadioButton, [Description("Spin")] Spin, [Description("Combo")] Combo, [Description("Accel")] Accel, [Description("Progress")] Progress, ProgressText, [Description("Pixbuf Stock Label")] PixbufStockLabel, [Description("Pixbuf Stock Icon")] PixbufStockIcon, [Description("Pixbuf Custom")] PixbufCustom, Count } protected void OnDeleteEvent(object sender, DeleteEventArgs a) { Application.Quit(); a.RetVal = true; } private void SetupTreeView() { this.listStore1 = this.CreateModel(); this.treeview1.Model = this.listStore1; this.AddColumns(this.treeview1); } private ListStore CreateModel() { System.Type[] types = new System.Type[(int)Column.Count]; types[(int)Column.TextString] = typeof(string); types[(int)Column.TextDouble] = typeof(double); types[(int)Column.TextBool] = typeof(bool); types[(int)Column.ToggleCheckBox] = typeof(bool); types[(int)Column.ToggleRadioButton] = typeof(bool); types[(int)Column.Spin] = typeof(float); types[(int)Column.Combo] = typeof(string); types[(int)Column.Accel] = typeof(string); types[(int)Column.Progress] = typeof(int); types[(int)Column.ProgressText] = typeof(string); types[(int)Column.PixbufStockLabel] = typeof(string); types[(int)Column.PixbufStockIcon] = typeof(string); types[(int)Column.PixbufCustom] = typeof(Gdk.Pixbuf); ListStore model = new ListStore(types); string[] accels = new string[3]; accels[0] = Gtk.Accelerator.GetLabel((uint)Gdk.Key.x, Gdk.ModifierType.ControlMask); accels[1] = Gtk.Accelerator.GetLabel((uint)Gdk.Key.c, Gdk.ModifierType.ControlMask); accels[2] = Gtk.Accelerator.GetLabel((uint)Gdk.Key.v, Gdk.ModifierType.ControlMask); string[] stockIcons = new string[3]; stockIcons[0] = Gtk.Stock.Yes; stockIcons[1] = Gtk.Stock.No; stockIcons[2] = Gtk.Stock.Edit; string[] stockLabels = new string[3]; stockLabels[0] = Gtk.Stock.Lookup(stockIcons[0]).Label; stockLabels[1] = Gtk.Stock.Lookup(stockIcons[1]).Label; stockLabels[2] = Gtk.Stock.Lookup(stockIcons[2]).Label; Gdk.Pixbuf[] pixbufs = new Gdk.Pixbuf[3]; pixbufs[0] = Gdk.Pixbuf.LoadFromResource("CellRenderers.Pixbuf.dialog-fewer.png"); pixbufs[1] = Gdk.Pixbuf.LoadFromResource("CellRenderers.Pixbuf.dialog-more.png"); pixbufs[2] = Gdk.Pixbuf.LoadFromResource("CellRenderers.Pixbuf.dialog-fewer.png"); model.AppendValues("String1", 1.11, true, true, false, float.Parse("1.1"), "Value2", accels[0], 25, "25%", stockLabels[0], stockIcons[0], pixbufs[0]); model.AppendValues("String2", 2.22, false, false, true, float.Parse("2.2"), "Value2", accels[1], 50, "50%", stockLabels[1], stockIcons[1], pixbufs[1]); model.AppendValues("String3", 3.33, true, true, false, float.Parse("3.3"), "Value1", accels[2], 75, "75%", stockLabels[2], stockIcons[2], pixbufs[2]); return model; } private void AddColumns(TreeView treeView) { { var column = new TreeViewColumn(); var cell = new CellRendererText(); cell.Editable = true; cell.Edited += this.TextStringEdited; column.Title = Column.TextString.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.TextString); this.treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererText(); cell.Editable = true; cell.Edited += this.TextDoubleEdited; column.Title = Column.TextDouble.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.TextDouble); this.treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererText(); column.Title = Column.TextBool.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.TextBool); this.treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererToggle(); cell.Toggled += this.ToggleCheckBoxToggled; cell.Active = true; cell.Activatable = true; column.Title = Column.ToggleCheckBox.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "active", (int)Column.ToggleCheckBox); this.treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererToggle(); cell.Toggled += this.ToggleRadioButtonToggled; cell.Active = true; cell.Activatable = true; cell.Radio = true; column.Title = Column.ToggleRadioButton.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "active", (int)Column.ToggleRadioButton); this.treeview1.AppendColumn(column); } { // Note: the text in this renderer has to be parseable as a floating point number var column = new TreeViewColumn(); var cell = new CellRendererSpin(); cell.Editable = true; cell.Edited += this.SpinTest1Edited; // Adjustment - Contains the range information for the cell. // Value: Must be non-null for the cell to be editable. cell.Adjustment = new Adjustment(0, 0, float.MaxValue, 1, 2, 0); // ClimbRate - Provides the acceleration rate for when the button is held down. // Value: Defaults to 0, must be greater than or equal to 0. cell.ClimbRate = 0; // Digits - Number of decimal places to display (seems to only work while editing the cell?!?). // Value: An integer between 0 and 20, default value is 0. cell.Digits = 3; column.Title = Column.Spin.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.Spin); this.treeview1.AppendColumn(column); } { ListStore model = new ListStore(typeof(string)); model.AppendValues("Value1"); model.AppendValues("Value2"); model.AppendValues("Value3"); var column = new TreeViewColumn(); var cell = new CellRendererCombo(); cell.Width = 75; cell.Editable = true; cell.Edited += this.ComboEdited; // bool. Whether to use an entry. // If true, the cell renderer will include an entry and allow to // enter values other than the ones in the popup list. cell.HasEntry = true; // TreeModel. Holds a tree model containing the possible values for the combo box. // Use the CellRendererCombo.TextColumn property to specify the column holding the values. cell.Model = model; // int. Specifies the model column which holds the possible values for the combo box. // Note: this refers to the model specified in the model property, not the model // backing the tree view to which this cell renderer is attached. cell.TextColumn = 0; column.Title = Column.Combo.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.Combo); this.treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererAccel(); cell.AccelMode = CellRendererAccelMode.Other; cell.Editable = true; cell.AccelEdited += new AccelEditedHandler(this.OnAccelEdited); cell.AccelCleared += new AccelClearedHandler(this.OnAccelCleared); column.Title = Column.Accel.ToString(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.Accel); this.treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererProgress(); column.Title = Column.Progress.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.ProgressText); column.AddAttribute(cell, "value", (int)Column.Progress); this.treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererText(); column.Title = Column.PixbufStockLabel.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "text", (int)Column.PixbufStockLabel); treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererPixbuf(); column.Title = Column.PixbufStockIcon.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "stock-id", (int)Column.PixbufStockIcon); treeview1.AppendColumn(column); } { var column = new TreeViewColumn(); var cell = new CellRendererPixbuf(); column.Title = Column.PixbufCustom.GetDescription(); column.PackStart(cell, true); column.AddAttribute(cell, "pixbuf", (int)Column.PixbufCustom); treeview1.AppendColumn(column); } } private void OnAccelCleared(object o, AccelClearedArgs args) { Console.WriteLine("OnAccelCleared()"); TreeIter iter; this.listStore1.GetIterFromString(out iter, args.PathString); this.listStore1.SetValue(iter, (int)Column.Accel, string.Empty); } private void OnAccelEdited(object o, AccelEditedArgs args) { Console.WriteLine("OnAccelEdited()"); TreeIter iter; uint accelKey = args.AccelKey; Gdk.ModifierType accelMods = args.AccelMods; if (Gtk.Accelerator.Valid(accelKey, accelMods)) { if (this.listStore1.GetIterFromString(out iter, args.PathString)) { string accel = Gtk.Accelerator.GetLabel(accelKey, accelMods); this.listStore1.SetValue(iter, (int)Column.Accel, accel); } } else { this.StartOrContinueAccelEditing(new Gtk.TreePath(args.PathString)); return; } } private void StartOrContinueAccelEditing(Gtk.TreePath treePath) { this.treeview1.GrabFocus(); this.treeview1.SetCursor(treePath, this.treeview1.GetColumn((int)Column.Accel), true); } private void ComboEdited(object o, EditedArgs args) { Console.WriteLine("ComboEdited()"); TreeIter iter; this.listStore1.GetIterFromString(out iter, args.Path); this.listStore1.SetValue(iter, (int)Column.Combo, args.NewText); } private void SpinTest1Edited(object o, EditedArgs args) { Console.WriteLine("SpinTest1Edited()"); // Note: The args.NewText value must be parsed into the same // data type specified for the column in the model. If it isn't then // the model's SetValue() method will not work. float val; if (!float.TryParse(args.NewText, out val)) { // Maybe alert the user of invalid data entered here. return; } TreeIter iter; this.listStore1.GetIterFromString(out iter, args.Path); this.listStore1.SetValue(iter, (int)Column.Spin, val); } private void TextStringEdited(object o, EditedArgs args) { Console.WriteLine("TextStringEdited()"); TreeIter iter; this.listStore1.GetIterFromString(out iter, args.Path); this.listStore1.SetValue(iter, (int)Column.TextString, args.NewText); } private void TextDoubleEdited(object o, EditedArgs args) { Console.WriteLine("TextDoubleEdited()"); TreeIter iter; this.listStore1.GetIterFromString(out iter, args.Path); this.listStore1.SetValue(iter, (int)Column.TextDouble, args.NewText); } private void ToggleCheckBoxToggled(object o, ToggledArgs args) { Console.WriteLine("ToggleCheckBoxToggled()"); TreeIter iter; if (this.listStore1.GetIterFromString(out iter, args.Path)) { bool value = (bool)this.listStore1.GetValue(iter, (int)Column.ToggleCheckBox); this.listStore1.SetValue(iter, (int)Column.ToggleCheckBox, !value); } } private void ToggleRadioButtonToggled(object o, ToggledArgs args) { Console.WriteLine("ToggleRadioButtonToggled()"); TreeIter iter; // Radio button "group" behavior must be manually implemneted with something like this: if (this.listStore1.GetIterFirst(out iter)) { do { this.listStore1.SetValue(iter, (int)Column.ToggleRadioButton, false); } while (this.listStore1.IterNext(ref iter)); } if (this.listStore1.GetIterFromString(out iter, args.Path)) { this.listStore1.SetValue(iter, (int)Column.ToggleRadioButton, true); } } }
using System; using System.Linq.Expressions; using System.Threading.Tasks; namespace Attest.Fake.Setup.Contracts { /// <summary> /// Used to add new method calls to the existing service call /// </summary> /// <typeparam name="TService">Type of service</typeparam> public interface ICanAddMethods<TService> where TService : class { /// <summary> /// Adds a new method call without return value. /// </summary> /// <typeparam name="TCallback">Type of callback</typeparam> /// <param name="methodCall">Method call</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<TCallback>(IMethodCall<TService, TCallback> methodCall); /// <summary> /// Adds a new async method call without return value. /// </summary> /// <typeparam name="TCallback">Type of callback</typeparam> /// <param name="methodCall">Method call</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<TCallback>(IMethodCallAsync<TService, TCallback> methodCall); /// <summary> /// Adds a new method call with return value. /// </summary> /// <typeparam name="TCallback">Type of callback</typeparam> /// <typeparam name="TResult">Type of return value</typeparam> /// <param name="methodCall">Method call</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<TCallback, TResult>( IMethodCallWithResult<TService, TCallback, TResult> methodCall); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <typeparam name="TCallback">Type of callback</typeparam> /// <typeparam name="TResult">Type of return value</typeparam> /// <param name="methodCall">Method call</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<TCallback, TResult>( IMethodCallWithResult<TService, TCallback, TResult> methodCall); } /// <summary> /// Used to add new method calls to the existing service call using explicit lambda expression API /// </summary> /// <typeparam name="TService">Type of service</typeparam> public interface ICanAddMethodsEx<TService> where TService : class { /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback>, IHaveCallbacks<IMethodCallback>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T>, T>, IHaveCallbacks<IMethodCallback<T>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T>, T>, T, IHaveCallbacks<IMethodCallback<T>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2>, T1, T2>, IHaveCallbacks<IMethodCallback<T1, T2>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2>, T1, T2>, T1, T2, IHaveCallbacks<IMethodCallback<T1, T2>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2, T3>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3>, T1, T2, T3>, IHaveCallbacks<IMethodCallback<T1, T2, T3>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2, T3>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3>, T1, T2, T3>, T1, T2, T3, IHaveCallbacks<IMethodCallback<T1, T2, T3>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2, T3, T4>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4>, T1, T2, T3, T4>, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2, T3, T4>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4>, T1, T2, T3, T4>, T1, T2, T3, T4, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2, T3, T4, T5>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4, T5>, T1, T2, T3, T4, T5>, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4, T5>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCall<T1, T2, T3, T4, T5>(Expression<Action<TService>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4, T5>, T1, T2, T3, T4, T5>, T1, T2, T3, T4, T5, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4, T5>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<TResult>, TResult>, IHaveCallbacks<IMethodCallbackWithResult<TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, T, IHaveCallbacks<IMethodCallbackWithResult<T, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, T1, T2, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, T3, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, T3, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, T1, T2, T3, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, T3, T4, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, T3, T4, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, T1, T2, T3, T4, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, T3, T4, T5, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResult<T1, T2, T3, T4, T5, TResult>(Expression<Func<TService, TResult>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>>> callbacksProducer); } /// <summary> /// Used to add new async method calls to the existing service call /// </summary> /// <typeparam name="TService">Type of service</typeparam> public interface ICanAddMethodsAsync<TService> where TService : class { /// <summary> /// Adds a new async method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback>, IHaveCallbacks<IMethodCallback>> callbacksProducer); /// <summary> /// Adds a new async method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T>, T>, IHaveCallbacks<IMethodCallback<T>>> callbacksProducer); /// <summary> /// Adds a new async method call without return value and one parameter. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T>, T>, T, IHaveCallbacks<IMethodCallback<T>>> callbacksProducer); /// <summary> /// Adds a new async method call without return value and two parameters. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2>, T1, T2>, IHaveCallbacks<IMethodCallback<T1, T2>>> callbacksProducer); /// <summary> /// Adds a new async method call without return value and two parameters. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2>, T1, T2>, T1, T2, IHaveCallbacks<IMethodCallback<T1, T2>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2, T3>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3>, T1, T2, T3>, IHaveCallbacks<IMethodCallback<T1, T2, T3>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2, T3>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3>, T1, T2, T3>, T1, T2, T3, IHaveCallbacks<IMethodCallback<T1, T2, T3>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2, T3, T4>(Expression<Func<TService, Task>> runMethod, Func <IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4>, T1, T2, T3, T4>, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2, T3, T4>(Expression<Func<TService, Task>> runMethod, Func <IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4>, T1, T2, T3, T4>, T1, T2, T3, T4, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2, T3, T4, T5>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4, T5>, T1, T2, T3, T4, T5>, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4, T5>>> callbacksProducer); /// <summary> /// Adds a new method call without return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallAsync<T1, T2, T3, T4, T5>(Expression<Func<TService, Task>> runMethod, Func<IHaveNoCallbacks<IMethodCallback<T1, T2, T3, T4, T5>, T1, T2, T3, T4, T5>, T1, T2, T3, T4, T5, IHaveCallbacks<IMethodCallback<T1, T2, T3, T4, T5>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<TResult>(Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<TResult>, TResult>, IHaveCallbacks<IMethodCallbackWithResult<TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T, TResult>( Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T, TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T, TResult>( Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T, TResult>, T, TResult>, T, IHaveCallbacks<IMethodCallbackWithResult<T, TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, TResult>(Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, TResult>(Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, TResult>, T1, T2, TResult>, T1, T2, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, T3, TResult>(Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, T3, TResult>(Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, TResult>, T1, T2, T3, TResult>, T1, T2, T3, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, T3, T4, TResult>( Expression<Func<TService, Task<TResult>>> runMethod, Func <IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>>> callbacksProducer); /// <summary> /// Adds a new async method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, T3, T4, TResult>( Expression<Func<TService, Task<TResult>>> runMethod, Func <IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>, T1, T2, T3, T4, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, T3, T4, T5, TResult>(Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>>> callbacksProducer); /// <summary> /// Adds a new method call with return value. /// </summary> /// <param name="runMethod">The method to be set up.</param> /// <param name="callbacksProducer">The callbacks producer function.</param> /// <returns>Service call</returns> IServiceCall<TService> AddMethodCallWithResultAsync<T1, T2, T3, T4, T5, TResult>(Expression<Func<TService, Task<TResult>>> runMethod, Func<IHaveNoCallbacksWithResult<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, IHaveCallbacks<IMethodCallbackWithResult<T1, T2, T3, T4, T5, TResult>>> callbacksProducer); } }
using System; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.WebPages; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Web.Models; using Umbraco.Web.Routing; namespace Umbraco.Web.Mvc { /// <summary> /// The View that umbraco front-end views inherit from /// </summary> public abstract class UmbracoViewPage<TModel> : WebViewPage<TModel> { /// <summary> /// Returns the current UmbracoContext /// </summary> public UmbracoContext UmbracoContext { get { //we should always try to return the context from the data tokens just in case its a custom context and not //using the UmbracoContext.Current. //we will fallback to the singleton if necessary. if (ViewContext.RouteData.DataTokens.ContainsKey("umbraco-context")) { return (UmbracoContext)ViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-context"); } //next check if it is a child action and see if the parent has it set in data tokens if (ViewContext.IsChildAction) { if (ViewContext.ParentActionViewContext.RouteData.DataTokens.ContainsKey("umbraco-context")) { return (UmbracoContext)ViewContext.ParentActionViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-context"); } } //lastly, we will use the singleton, the only reason this should ever happen is is someone is rendering a page that inherits from this //class and are rendering it outside of the normal Umbraco routing process. Very unlikely. return UmbracoContext.Current; } } /// <summary> /// Returns the current ApplicationContext /// </summary> public ApplicationContext ApplicationContext { get { return UmbracoContext.Application; } } /// <summary> /// Returns the current PublishedContentRequest /// </summary> internal PublishedContentRequest PublishedContentRequest { get { //we should always try to return the object from the data tokens just in case its a custom object and not //using the UmbracoContext.Current. //we will fallback to the singleton if necessary. if (ViewContext.RouteData.DataTokens.ContainsKey("umbraco-doc-request")) { return (PublishedContentRequest)ViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-doc-request"); } //next check if it is a child action and see if the parent has it set in data tokens if (ViewContext.IsChildAction) { if (ViewContext.ParentActionViewContext.RouteData.DataTokens.ContainsKey("umbraco-doc-request")) { return (PublishedContentRequest)ViewContext.ParentActionViewContext.RouteData.DataTokens.GetRequiredObject("umbraco-doc-request"); } } //lastly, we will use the singleton, the only reason this should ever happen is is someone is rendering a page that inherits from this //class and are rendering it outside of the normal Umbraco routing process. Very unlikely. return UmbracoContext.Current.PublishedContentRequest; } } private UmbracoHelper _helper; /// <summary> /// Gets an UmbracoHelper /// </summary> /// <remarks> /// This constructs the UmbracoHelper with the content model of the page routed to /// </remarks> public virtual UmbracoHelper Umbraco { get { if (_helper == null) { var model = ViewData.Model; var content = model as IPublishedContent; if (content == null && model is IRenderModel) content = ((IRenderModel) model).Content; _helper = content == null ? new UmbracoHelper(UmbracoContext) : new UmbracoHelper(UmbracoContext, content); } return _helper; } } /// <summary> /// Ensure that the current view context is added to the route data tokens so we can extract it if we like /// </summary> /// <remarks> /// Currently this is required by mvc macro engines /// </remarks> protected override void InitializePage() { base.InitializePage(); if (ViewContext.IsChildAction == false) { if (ViewContext.RouteData.DataTokens.ContainsKey(Constants.DataTokenCurrentViewContext) == false) { ViewContext.RouteData.DataTokens.Add(Constants.DataTokenCurrentViewContext, ViewContext); } } } // maps model protected override void SetViewData(ViewDataDictionary viewData) { var source = viewData.Model; if (source == null) { base.SetViewData(viewData); return; } var sourceType = source.GetType(); var targetType = typeof (TModel); // it types already match, nothing to do if (sourceType.Inherits<TModel>()) // includes == { base.SetViewData(viewData); return; } // try to grab the content // if no content is found, return, nothing we can do var sourceContent = source as IPublishedContent; if (sourceContent == null && sourceType.Implements<IRenderModel>()) { sourceContent = ((IRenderModel)source).Content; } if (sourceContent == null) { var attempt = source.TryConvertTo<IPublishedContent>(); if (attempt.Success) sourceContent = attempt.Result; } var ok = sourceContent != null; if (sourceContent != null) { // try to grab the culture // using context's culture by default var culture = UmbracoContext.PublishedContentRequest.Culture; var sourceRenderModel = source as RenderModel; if (sourceRenderModel != null) culture = sourceRenderModel.CurrentCulture; // reassign the model depending on its type if (targetType.Implements<IPublishedContent>()) { // it TModel implements IPublishedContent then use the content // provided that the content is of the proper type if ((sourceContent is TModel) == false) throw new InvalidCastException(string.Format("Cannot cast source content type {0} to view model type {1}.", sourceContent.GetType(), targetType)); viewData.Model = sourceContent; } else if (targetType == typeof(RenderModel)) { // if TModel is a basic RenderModel just create it viewData.Model = new RenderModel(sourceContent, culture); } else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(RenderModel<>)) { // if TModel is a strongly-typed RenderModel<> then create it // provided that the content is of the proper type var targetContentType = targetType.GetGenericArguments()[0]; if ((sourceContent.GetType().Inherits(targetContentType)) == false) throw new InvalidCastException(string.Format("Cannot cast source content type {0} to view model content type {1}.", sourceContent.GetType(), targetContentType)); viewData.Model = Activator.CreateInstance(targetType, sourceContent, culture); } else { ok = false; } } if (ok == false) { // last chance : try to convert var attempt = source.TryConvertTo<TModel>(); if (attempt.Success) viewData.Model = attempt.Result; } base.SetViewData(viewData); } /// <summary> /// This will detect the end /body tag and insert the preview badge if in preview mode /// </summary> /// <param name="value"></param> public override void WriteLiteral(object value) { // filter / add preview banner if (Response.ContentType.InvariantEquals("text/html")) // ASP.NET default value { if (UmbracoContext.Current.IsDebug || UmbracoContext.Current.InPreviewMode) { var text = value.ToString().ToLowerInvariant(); var pos = text.IndexOf("</body>", StringComparison.InvariantCultureIgnoreCase); if (pos > -1) { string markupToInject; if (UmbracoContext.Current.InPreviewMode) { // creating previewBadge markup markupToInject = String.Format(UmbracoSettings.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), IOHelper.ResolveUrl(SystemDirectories.UmbracoClient), Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path)); } else { // creating mini-profiler markup markupToInject = Html.RenderProfiler().ToHtmlString(); } var sb = new StringBuilder(text); sb.Insert(pos, markupToInject); base.WriteLiteral(sb.ToString()); return; } } } base.WriteLiteral(value); } public HelperResult RenderSection(string name, Func<dynamic, HelperResult> defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } public HelperResult RenderSection(string name, HelperResult defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } public HelperResult RenderSection(string name, string defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } public HelperResult RenderSection(string name, IHtmlString defaultContents) { return WebViewPageExtensions.RenderSection(this, name, defaultContents); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A college, university, or other third-level educational institution. /// </summary> public class CollegeOrUniversity_Core : TypeCore, IEducationalOrganization { public CollegeOrUniversity_Core() { this._TypeId = 65; this._Id = "CollegeOrUniversity"; this._Schema_Org_Url = "http://schema.org/CollegeOrUniversity"; string label = ""; GetLabel(out label, "CollegeOrUniversity", typeof(CollegeOrUniversity_Core)); this._Label = label; this._Ancestors = new int[]{266,193,88}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{88}; this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,199,196,13}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// Alumni of educational organization. /// </summary> private Alumni_Core alumni; public Alumni_Core Alumni { get { return alumni; } set { alumni = value; SetPropertyInstance(alumni); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] public partial class DockPane : UserControl, IDockDragSource { public enum AppearanceStyle { ToolWindow, Document } private enum HitTestArea { Caption, TabStrip, Content, None } private struct HitTestResult { public HitTestArea HitArea; public int Index; public HitTestResult(HitTestArea hitTestArea, int index) { HitArea = hitTestArea; Index = index; } } private DockPaneCaptionBase m_captionControl; private DockPaneCaptionBase CaptionControl { get { return m_captionControl; } } private DockPaneStripBase m_tabStripControl; public DockPaneStripBase TabStripControl { get { return m_tabStripControl; } } internal protected DockPane(IDockContent content, DockState visibleState, bool show) { InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show) { if (floatWindow == null) throw new ArgumentNullException(nameof(floatWindow)); InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show); } internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show) { if (previousPane == null) throw (new ArgumentNullException(nameof(previousPane))); InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show) { InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show); } private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show) { if (dockState == DockState.Hidden || dockState == DockState.Unknown) throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState); if (content == null) throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent); if (content.DockHandler.DockPanel == null) throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel); SuspendLayout(); SetStyle(ControlStyles.Selectable, false); m_isFloat = (dockState == DockState.Float); m_contents = new DockContentCollection(); m_displayingContents = new DockContentCollection(this); m_dockPanel = content.DockHandler.DockPanel; m_dockPanel.AddPane(this); m_splitter = content.DockHandler.DockPanel.Theme.Extender.DockPaneSplitterControlFactory.CreateSplitterControl(this); m_nestedDockingStatus = new NestedDockingStatus(this); m_captionControl = DockPanel.Theme.Extender.DockPaneCaptionFactory.CreateDockPaneCaption(this); m_tabStripControl = DockPanel.Theme.Extender.DockPaneStripFactory.CreateDockPaneStrip(this); Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl }); DockPanel.SuspendLayout(true); if (flagBounds) FloatWindow = DockPanel.Theme.Extender.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else if (prevPane != null) DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion); SetDockState(dockState); if (show) content.DockHandler.Pane = this; else if (this.IsFloat) content.DockHandler.FloatPane = this; else content.DockHandler.PanelPane = this; ResumeLayout(); DockPanel.ResumeLayout(true, true); } private bool m_isDisposing; protected override void Dispose(bool disposing) { if (disposing) { // IMPORTANT: avoid nested call into this method on Mono. // https://github.com/dockpanelsuite/dockpanelsuite/issues/16 if (Win32Helper.IsRunningOnMono) { if (m_isDisposing) return; m_isDisposing = true; } m_dockState = DockState.Unknown; if (NestedPanesContainer != null) NestedPanesContainer.NestedPanes.Remove(this); if (DockPanel != null) { DockPanel.RemovePane(this); m_dockPanel = null; } Splitter.Dispose(); if (m_autoHidePane != null) m_autoHidePane.Dispose(); } base.Dispose(disposing); } private IDockContent m_activeContent = null; public virtual IDockContent ActiveContent { get { return m_activeContent; } set { if (ActiveContent == value) return; if (value != null) { if (!DisplayingContents.Contains(value)) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } else { if (DisplayingContents.Count != 0) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } IDockContent oldValue = m_activeContent; if (DockPanel.ActiveAutoHideContent == oldValue) DockPanel.ActiveAutoHideContent = null; m_activeContent = value; if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) { if (m_activeContent != null) m_activeContent.DockHandler.Form.BringToFront(); } else { if (m_activeContent != null) m_activeContent.DockHandler.SetVisible(); if (oldValue != null && DisplayingContents.Contains(oldValue)) oldValue.DockHandler.SetVisible(); if (IsActivated && m_activeContent != null) m_activeContent.DockHandler.Activate(); } if (FloatWindow != null) FloatWindow.SetText(); if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) RefreshChanges(false); // delayed layout to reduce screen flicker else RefreshChanges(); if (m_activeContent != null) TabStripControl.EnsureTabVisible(m_activeContent); } } internal void ClearLastActiveContent() { m_activeContent = null; } private bool m_allowDockDragAndDrop = true; public virtual bool AllowDockDragAndDrop { get { return m_allowDockDragAndDrop; } set { m_allowDockDragAndDrop = value; } } private IDisposable m_autoHidePane = null; internal IDisposable AutoHidePane { get { return m_autoHidePane; } set { m_autoHidePane = value; } } private object m_autoHideTabs = null; internal object AutoHideTabs { get { return m_autoHideTabs; } set { m_autoHideTabs = value; } } private object TabPageContextMenu { get { IDockContent content = ActiveContent; if (content == null) return null; if (content.DockHandler.TabPageContextMenuStrip != null) return content.DockHandler.TabPageContextMenuStrip; #if NET35 || NET40 else if (content.DockHandler.TabPageContextMenu != null) return content.DockHandler.TabPageContextMenu; #endif else return null; } } internal bool HasTabPageContextMenu { get { return TabPageContextMenu != null; } } internal void ShowTabPageContextMenu(Control control, Point position) { object menu = TabPageContextMenu; if (menu == null) return; ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip; if (contextMenuStrip != null) { contextMenuStrip.Show(control, position); return; } #if NET35 || NET40 ContextMenu contextMenu = menu as ContextMenu; if (contextMenu != null) contextMenu.Show(this, position); #endif } private Rectangle CaptionRectangle { get { if (!HasCaption) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x, y, width; x = rectWindow.X; y = rectWindow.Y; width = rectWindow.Width; int height = CaptionControl.MeasureHeight(); return new Rectangle(x, y, width, height); } } internal protected virtual Rectangle ContentRectangle { get { Rectangle rectWindow = DisplayingRectangle; Rectangle rectCaption = CaptionRectangle; Rectangle rectTabStrip = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height); if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top) y += rectTabStrip.Height; int width = rectWindow.Width; int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height; return new Rectangle(x, y, width, height); } } internal Rectangle TabStripRectangle { get { if (Appearance == AppearanceStyle.ToolWindow) return TabStripRectangle_ToolWindow; else return TabStripRectangle_Document; } } private Rectangle TabStripRectangle_ToolWindow { get { if (DisplayingContents.Count <= 1 || IsAutoHide) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int x = rectWindow.X; int y = rectWindow.Bottom - height; Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(x, y)) y = rectCaption.Y + rectCaption.Height; return new Rectangle(x, y, width, height); } } private Rectangle TabStripRectangle_Document { get { if (DisplayingContents.Count == 0) return Rectangle.Empty; if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x = rectWindow.X; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int y = 0; if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) y = rectWindow.Height - height; else y = rectWindow.Y; return new Rectangle(x, y, width, height); } } public virtual string CaptionText { get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; } } private DockContentCollection m_contents; public DockContentCollection Contents { get { return m_contents; } } private DockContentCollection m_displayingContents; public DockContentCollection DisplayingContents { get { return m_displayingContents; } } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } private bool HasCaption { get { if (DockState == DockState.Document || DockState == DockState.Hidden || DockState == DockState.Unknown || (DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1)) return false; else return true; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } } internal void SetIsActivated(bool value) { if (m_isActivated == value) return; m_isActivated = value; if (DockState != DockState.Document) RefreshChanges(false); OnIsActivatedChanged(EventArgs.Empty); } private bool m_isActiveDocumentPane = false; public bool IsActiveDocumentPane { get { return m_isActiveDocumentPane; } } internal void SetIsActiveDocumentPane(bool value) { if (m_isActiveDocumentPane == value) return; m_isActiveDocumentPane = value; if (DockState == DockState.Document) RefreshChanges(); OnIsActiveDocumentPaneChanged(EventArgs.Empty); } public bool IsActivePane { get { return this == DockPanel.ActivePane; } } public bool IsDockStateValid(DockState dockState) { foreach (IDockContent content in Contents) if (!content.DockHandler.IsDockStateValid(dockState)) return false; return true; } public bool IsAutoHide { get { return DockHelper.IsDockStateAutoHide(DockState); } } public AppearanceStyle Appearance { get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; } } public Rectangle DisplayingRectangle { get { return ClientRectangle; } } public void Activate() { if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent) DockPanel.ActiveAutoHideContent = ActiveContent; else if (!IsActivated && ActiveContent != null) ActiveContent.DockHandler.Activate(); } internal void AddContent(IDockContent content) { if (Contents.Contains(content)) return; Contents.Add(content); } internal void Close() { Dispose(); } public void CloseActiveContent() { CloseContent(ActiveContent); } internal void CloseContent(IDockContent content) { if (content == null) return; if (!content.DockHandler.CloseButton) return; DockPanel dockPanel = DockPanel; dockPanel.SuspendLayout(true); try { if (content.DockHandler.HideOnClose) { content.DockHandler.Hide(); NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } else { content.DockHandler.Close(); // TODO: fix layout here for #519 } } finally { dockPanel.ResumeLayout(true, true); } } private HitTestResult GetHitTest(Point ptMouse) { Point ptMouseClient = PointToClient(ptMouse); Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Caption, -1); Rectangle rectContent = ContentRectangle; if (rectContent.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Content, -1); Rectangle rectTabStrip = TabStripRectangle; if (rectTabStrip.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse))); return new HitTestResult(HitTestArea.None, -1); } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } } private void SetIsHidden(bool value) { if (m_isHidden == value) return; m_isHidden = value; if (DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } else if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } protected override void OnLayout(LayoutEventArgs e) { SetIsHidden(DisplayingContents.Count == 0); if (!IsHidden) { CaptionControl.Bounds = CaptionRectangle; TabStripControl.Bounds = TabStripRectangle; SetContentBounds(); foreach (IDockContent content in Contents) { if (DisplayingContents.Contains(content)) if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible) content.DockHandler.FlagClipWindow = false; } } base.OnLayout(e); } internal void SetContentBounds() { Rectangle rectContent = ContentRectangle; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent)); Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height); foreach (IDockContent content in Contents) if (content.DockHandler.Pane == this) { if (content == ActiveContent) content.DockHandler.Form.Bounds = rectContent; else content.DockHandler.Form.Bounds = rectInactive; } } internal void RefreshChanges() { RefreshChanges(true); } private void RefreshChanges(bool performLayout) { if (IsDisposed) return; CaptionControl.RefreshChanges(); TabStripControl.RefreshChanges(); if (DockState == DockState.Float && FloatWindow != null) FloatWindow.RefreshChanges(); if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } if (performLayout) PerformLayout(); } internal void RemoveContent(IDockContent content) { if (!Contents.Contains(content)) return; Contents.Remove(content); } public void SetContentIndex(IDockContent content, int index) { int oldIndex = Contents.IndexOf(content); if (oldIndex == -1) throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent)); if (index < 0 || index > Contents.Count - 1) if (index != -1) throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Contents.Count - 1 && index == -1) return; Contents.Remove(content); if (index == -1) Contents.Add(content); else if (oldIndex < index) Contents.AddAt(content, index - 1); else Contents.AddAt(content, index); RefreshChanges(); } private void SetParent() { if (DockState == DockState.Unknown || DockState == DockState.Hidden) { SetParent(null); Splitter.Parent = null; } else if (DockState == DockState.Float) { SetParent(FloatWindow); Splitter.Parent = FloatWindow; } else if (DockHelper.IsDockStateAutoHide(DockState)) { SetParent(DockPanel.AutoHideControl); Splitter.Parent = null; } else { SetParent(DockPanel.DockWindows[DockState]); Splitter.Parent = Parent; } } private void SetParent(Control value) { if (Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Parent = value; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (contentFocused != null) contentFocused.DockHandler.Activate(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public new void Show() { Activate(); } internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) { if (!dragSource.CanDockTo(this)) return; Point ptMouse = Control.MousePosition; HitTestResult hitTestResult = GetHitTest(ptMouse); if (hitTestResult.HitArea == HitTestArea.Caption) dockOutline.Show(this, -1); else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1) dockOutline.Show(this, hitTestResult.Index); } internal void ValidateActiveContent() { if (ActiveContent == null) { if (DisplayingContents.Count != 0) ActiveContent = DisplayingContents[0]; return; } if (DisplayingContents.IndexOf(ActiveContent) >= 0) return; IDockContent prevVisible = null; for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--) if (Contents[i].DockHandler.DockState == DockState) { prevVisible = Contents[i]; break; } IDockContent nextVisible = null; for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++) if (Contents[i].DockHandler.DockState == DockState) { nextVisible = Contents[i]; break; } if (prevVisible != null) ActiveContent = prevVisible; else if (nextVisible != null) ActiveContent = nextVisible; else ActiveContent = null; } private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActivatedChangedEvent = new object(); public event EventHandler IsActivatedChanged { add { Events.AddHandler(IsActivatedChangedEvent, value); } remove { Events.RemoveHandler(IsActivatedChangedEvent, value); } } protected virtual void OnIsActivatedChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActiveDocumentPaneChangedEvent = new object(); public event EventHandler IsActiveDocumentPaneChanged { add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); } remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); } } protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent]; if (handler != null) handler(this, e); } public DockWindow DockWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; } set { DockWindow oldValue = DockWindow; if (oldValue == value) return; DockTo(value); } } public FloatWindow FloatWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; } set { FloatWindow oldValue = FloatWindow; if (oldValue == value) return; DockTo(value); } } private NestedDockingStatus m_nestedDockingStatus; public NestedDockingStatus NestedDockingStatus { get { return m_nestedDockingStatus; } } private bool m_isFloat; public bool IsFloat { get { return m_isFloat; } } public INestedPanesContainer NestedPanesContainer { get { if (NestedDockingStatus.NestedPanes == null) return null; else return NestedDockingStatus.NestedPanes.Container; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { SetDockState(value); } } public DockPane SetDockState(DockState value) { if (value == DockState.Unknown || value == DockState.Hidden) throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState); if ((value == DockState.Float) == this.IsFloat) { InternalSetDockState(value); return this; } if (DisplayingContents.Count == 0) return null; IDockContent firstContent = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) { firstContent = content; break; } } if (firstContent == null) return null; firstContent.DockHandler.DockState = value; DockPane pane = firstContent.DockHandler.Pane; DockPanel.SuspendLayout(true); for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) content.DockHandler.Pane = pane; } DockPanel.ResumeLayout(true, true); return pane; } private void InternalSetDockState(DockState value) { if (m_dockState == value) return; DockState oldDockState = m_dockState; INestedPanesContainer oldContainer = NestedPanesContainer; m_dockState = value; SuspendRefreshStateChange(); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); if (!IsFloat) DockWindow = DockPanel.DockWindows[DockState]; else if (FloatWindow == null) FloatWindow = DockPanel.Theme.Extender.FloatWindowFactory.CreateFloatWindow(DockPanel, this); if (contentFocused != null) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.Activate(contentFocused); } } ResumeRefreshStateChange(oldContainer, oldDockState); } private int m_countRefreshStateChange = 0; private void SuspendRefreshStateChange() { m_countRefreshStateChange++; DockPanel.SuspendLayout(true); } private void ResumeRefreshStateChange() { m_countRefreshStateChange--; System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0); DockPanel.ResumeLayout(true, true); } private bool IsRefreshStateChangeSuspended { get { return m_countRefreshStateChange != 0; } } private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { ResumeRefreshStateChange(); RefreshStateChange(oldContainer, oldDockState); } private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { if (IsRefreshStateChangeSuspended) return; SuspendRefreshStateChange(); DockPanel.SuspendLayout(true); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); SetParent(); if (ActiveContent != null) ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane); foreach (IDockContent content in Contents) { if (content.DockHandler.Pane == this) content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane); } if (oldContainer != null) { Control oldContainerControl = (Control)oldContainer; if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed) oldContainerControl.PerformLayout(); } if (DockHelper.IsDockStateAutoHide(oldDockState)) DockPanel.RefreshActiveAutoHideContent(); if (NestedPanesContainer.DockState == DockState) ((Control)NestedPanesContainer).PerformLayout(); if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshActiveAutoHideContent(); if (DockHelper.IsDockStateAutoHide(oldDockState) || DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } ResumeRefreshStateChange(); if (contentFocused != null) contentFocused.DockHandler.Activate(); DockPanel.ResumeLayout(true, true); if (oldDockState != DockState) OnDockStateChanged(EventArgs.Empty); } private IDockContent GetFocusedContent() { IDockContent contentFocused = null; foreach (IDockContent content in Contents) { if (content.DockHandler.Form.ContainsFocus) { contentFocused = content; break; } } return contentFocused; } public DockPane DockTo(INestedPanesContainer container) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); DockAlignment alignment; if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight) alignment = DockAlignment.Bottom; else alignment = DockAlignment.Right; return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5); } public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); if (container.IsFloat == this.IsFloat) { InternalAddToDockList(container, previousPane, alignment, proportion); return this; } IDockContent firstContent = GetFirstContent(container.DockState); if (firstContent == null) return null; DockPane pane; DockPanel.DummyContent.DockPanel = DockPanel; if (container.IsFloat) pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true); else pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true); pane.DockTo(container, previousPane, alignment, proportion); SetVisibleContentsToPane(pane); DockPanel.DummyContent.DockPanel = null; return pane; } private void SetVisibleContentsToPane(DockPane pane) { SetVisibleContentsToPane(pane, ActiveContent); } private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(pane.DockState)) { content.DockHandler.Pane = pane; i--; } } if (activeContent.DockHandler.Pane == pane) pane.ActiveContent = activeContent; } private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion) { if ((container.DockState == DockState.Float) != IsFloat) throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer); int count = container.NestedPanes.Count; if (container.NestedPanes.Contains(this)) count--; if (prevPane == null && count > 0) throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane); if (prevPane != null && !container.NestedPanes.Contains(prevPane)) throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane); if (prevPane == this) throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane); INestedPanesContainer oldContainer = NestedPanesContainer; DockState oldDockState = DockState; container.NestedPanes.Add(this); NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion); if (DockHelper.IsDockWindowState(DockState)) m_dockState = container.DockState; RefreshStateChange(oldContainer, oldDockState); } public void SetNestedDockingProportion(double proportion) { NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion); if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } public DockPane Float() { DockPanel.SuspendLayout(true); IDockContent activeContent = ActiveContent; DockPane floatPane = GetFloatPaneFromContents(); if (floatPane == null) { IDockContent firstContent = GetFirstContent(DockState.Float); if (firstContent == null) { DockPanel.ResumeLayout(true, true); return null; } floatPane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true); } SetVisibleContentsToPane(floatPane, activeContent); if (PatchController.EnableFloatSplitterFix == true) { if (IsHidden) { NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } } DockPanel.ResumeLayout(true, true); return floatPane; } private DockPane GetFloatPaneFromContents() { DockPane floatPane = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (!content.DockHandler.IsDockStateValid(DockState.Float)) continue; if (floatPane != null && content.DockHandler.FloatPane != floatPane) return null; else floatPane = content.DockHandler.FloatPane; } return floatPane; } private IDockContent GetFirstContent(DockState dockState) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(dockState)) return content; } return null; } public void RestoreToPanel() { DockPanel.SuspendLayout(true); IDockContent activeContent = DockPanel.ActiveContent; for (int i = DisplayingContents.Count - 1; i >= 0; i--) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.CheckDockState(false) != DockState.Unknown) content.DockHandler.IsFloat = false; } DockPanel.ResumeLayout(true, true); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE) Activate(); base.WndProc(ref m); } #region IDockDragSource Members #region IDragSource Members Control IDragSource.DragControl { get { return this; } } public IDockContent MouseOverTab { get; set; } #endregion bool IDockDragSource.IsDockStateValid(DockState dockState) { return IsDockStateValid(dockState); } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (pane == this) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Point location = PointToScreen(new Point(0, 0)); Size size; DockPane floatPane = ActiveContent.DockHandler.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + DockPanel.Theme.Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1) FloatWindow = DockPanel.Theme.Extender.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else FloatWindow.Bounds = floatWindowBounds; DockState = DockState.Float; NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { IDockContent activeContent = ActiveContent; for (int i = Contents.Count - 1; i >= 0; i--) { IDockContent c = Contents[i]; if (c.DockHandler.DockState == DockState) { c.DockHandler.Pane = pane; if (contentIndex != -1) pane.SetContentIndex(c, contentIndex); } } pane.ActiveContent = activeContent; } else { if (dockStyle == DockStyle.Left) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5); DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, nameof(panel)); if (dockStyle == DockStyle.Top) DockState = DockState.DockTop; else if (dockStyle == DockStyle.Bottom) DockState = DockState.DockBottom; else if (dockStyle == DockStyle.Left) DockState = DockState.DockLeft; else if (dockStyle == DockStyle.Right) DockState = DockState.DockRight; else if (dockStyle == DockStyle.Fill) DockState = DockState.Document; } #endregion #region cachedLayoutArgs leak workaround /// <summary> /// There's a bug in the WinForms layout engine /// that can result in a deferred layout to not /// properly clear out the cached layout args after /// the layout operation is performed. /// Specifically, this bug is hit when the bounds of /// the Pane change, initiating a layout on the parent /// (DockWindow) which is where the bug hits. /// To work around it, when a pane loses the DockWindow /// as its parent, that parent DockWindow needs to /// perform a layout to flush the cached args, if they exist. /// </summary> private DockWindow _lastParentWindow; protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); var newParent = Parent as DockWindow; if (newParent != _lastParentWindow) { if (_lastParentWindow != null) _lastParentWindow.PerformLayout(); _lastParentWindow = newParent; } } #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.Buffers; using System.IO; using System.Threading; using System.Threading.Tasks; namespace System.Security.Cryptography { public class CryptoStream : Stream, IDisposable { // Member variables private readonly Stream _stream; private readonly ICryptoTransform _transform; private readonly CryptoStreamMode _transformMode; private byte[] _inputBuffer; // read from _stream before _Transform private int _inputBufferIndex; private int _inputBlockSize; private byte[] _outputBuffer; // buffered output of _Transform private int _outputBufferIndex; private int _outputBlockSize; private bool _canRead; private bool _canWrite; private bool _finalBlockTransformed; private SemaphoreSlim _lazyAsyncActiveSemaphore; private readonly bool _leaveOpen; // Constructors public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : this(stream, transform, mode, false) { } public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, bool leaveOpen) { _stream = stream; _transformMode = mode; _transform = transform; _leaveOpen = leaveOpen; switch (_transformMode) { case CryptoStreamMode.Read: if (!(_stream.CanRead)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotReadable, nameof(stream))); _canRead = true; break; case CryptoStreamMode.Write: if (!(_stream.CanWrite)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotWritable, nameof(stream))); _canWrite = true; break; default: throw new ArgumentException(SR.Argument_InvalidValue); } InitializeBuffer(); } public override bool CanRead { get { return _canRead; } } // For now, assume we can never seek into the middle of a cryptostream // and get the state right. This is too strict. public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return _canWrite; } } public override long Length { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } set { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public bool HasFlushedFinalBlock { get { return _finalBlockTransformed; } } // The flush final block functionality used to be part of close, but that meant you couldn't do something like this: // MemoryStream ms = new MemoryStream(); // CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); // cs.Write(foo, 0, foo.Length); // cs.Close(); // and get the encrypted data out of ms, because the cs.Close also closed ms and the data went away. // so now do this: // cs.Write(foo, 0, foo.Length); // cs.FlushFinalBlock() // which can only be called once // byte[] ciphertext = ms.ToArray(); // cs.Close(); public void FlushFinalBlock() { if (_finalBlockTransformed) throw new NotSupportedException(SR.Cryptography_CryptoStream_FlushFinalBlockTwice); // We have to process the last block here. First, we have the final block in _InputBuffer, so transform it byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex); _finalBlockTransformed = true; // Now, write out anything sitting in the _OutputBuffer... if (_canWrite && _outputBufferIndex > 0) { _stream.Write(_outputBuffer, 0, _outputBufferIndex); _outputBufferIndex = 0; } // Write out finalBytes if (_canWrite) _stream.Write(finalBytes, 0, finalBytes.Length); // If the inner stream is a CryptoStream, then we want to call FlushFinalBlock on it too, otherwise just Flush. CryptoStream innerCryptoStream = _stream as CryptoStream; if (innerCryptoStream != null) { if (!innerCryptoStream.HasFlushedFinalBlock) { innerCryptoStream.FlushFinalBlock(); } } else { _stream.Flush(); } // zeroize plain text material before returning if (_inputBuffer != null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); if (_outputBuffer != null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); return; } public override void Flush() { return; } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(CryptoStream)) return base.FlushAsync(cancellationToken); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckReadArguments(buffer, offset, count); return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = AsyncActiveSemaphore; await semaphore.WaitAsync().ForceAsync(); try { return await ReadAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); // ConfigureAwait not needed as ForceAsync was used } finally { semaphore.Release(); } } public override int ReadByte() { // If we have enough bytes in the buffer such that reading 1 will still leave bytes // in the buffer, then take the faster path of simply returning the first byte. // (This unfortunately still involves shifting down the bytes in the buffer, as it // does in Read. If/when that's fixed for Read, it should be fixed here, too.) if (_outputBufferIndex > 1) { byte b = _outputBuffer[0]; Buffer.BlockCopy(_outputBuffer, 1, _outputBuffer, 0, _outputBufferIndex - 1); _outputBufferIndex -= 1; return b; } // Otherwise, fall back to the more robust but expensive path of using the base // Stream.ReadByte to call Read. return base.ReadByte(); } public override void WriteByte(byte value) { // If there's room in the input buffer such that even with this byte we wouldn't // complete a block, simply add the byte to the input buffer. if (_inputBufferIndex + 1 < _inputBlockSize) { _inputBuffer[_inputBufferIndex++] = value; return; } // Otherwise, the logic is complicated, so we simply fall back to the base // implementation that'll use Write. base.WriteByte(value); } public override int Read(byte[] buffer, int offset, int count) { CheckReadArguments(buffer, offset, count); return ReadAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).GetAwaiter().GetResult(); } private void CheckReadArguments(byte[] buffer, int offset, int count) { if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); } private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync) { // read <= count bytes from the input stream, transforming as we go. // Basic idea: first we deliver any bytes we already have in the // _OutputBuffer, because we know they're good. Then, if asked to deliver // more bytes, we read & transform a block at a time until either there are // no bytes ready or we've delivered enough. int bytesToDeliver = count; int currentOutputIndex = offset; if (_outputBufferIndex != 0) { // we have some already-transformed bytes in the output buffer if (_outputBufferIndex <= count) { Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, _outputBufferIndex); bytesToDeliver -= _outputBufferIndex; currentOutputIndex += _outputBufferIndex; int toClear = _outputBuffer.Length - _outputBufferIndex; CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear)); _outputBufferIndex = 0; } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, count); Buffer.BlockCopy(_outputBuffer, count, _outputBuffer, 0, _outputBufferIndex - count); _outputBufferIndex -= count; int toClear = _outputBuffer.Length - _outputBufferIndex; CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear)); return (count); } } // _finalBlockTransformed == true implies we're at the end of the input stream // if we got through the previous if block then _OutputBufferIndex = 0, meaning // we have no more transformed bytes to give // so return count-bytesToDeliver, the amount we were able to hand back // eventually, we'll just always return 0 here because there's no more to read if (_finalBlockTransformed) { return (count - bytesToDeliver); } // ok, now loop until we've delivered enough or there's nothing available int amountRead = 0; int numOutputBytes; // OK, see first if it's a multi-block transform and we can speed up things int blocksToProcess = bytesToDeliver / _outputBlockSize; if (blocksToProcess > 1 && _transform.CanTransformMultipleBlocks) { int numWholeBlocksInBytes = blocksToProcess * _inputBlockSize; byte[] tempInputBuffer = ArrayPool<byte>.Shared.Rent(numWholeBlocksInBytes); byte[] tempOutputBuffer = null; try { amountRead = useAsync ? await _stream.ReadAsync(new Memory<byte>(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex), cancellationToken) : // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread _stream.Read(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex); int totalInput = _inputBufferIndex + amountRead; // If there's still less than a block, copy the new data into the hold buffer and move to the slow read. if (totalInput < _inputBlockSize) { Buffer.BlockCopy(tempInputBuffer, _inputBufferIndex, _inputBuffer, _inputBufferIndex, amountRead); _inputBufferIndex = totalInput; } else { // Copy any held data into tempInputBuffer now that we know we're proceeding Buffer.BlockCopy(_inputBuffer, 0, tempInputBuffer, 0, _inputBufferIndex); CryptographicOperations.ZeroMemory(new Span<byte>(_inputBuffer, 0, _inputBufferIndex)); amountRead += _inputBufferIndex; _inputBufferIndex = 0; // Make amountRead an integral multiple of _InputBlockSize int numWholeReadBlocks = amountRead / _inputBlockSize; int numWholeReadBlocksInBytes = numWholeReadBlocks * _inputBlockSize; int numIgnoredBytes = amountRead - numWholeReadBlocksInBytes; if (numIgnoredBytes != 0) { _inputBufferIndex = numIgnoredBytes; Buffer.BlockCopy(tempInputBuffer, numWholeReadBlocksInBytes, _inputBuffer, 0, numIgnoredBytes); } tempOutputBuffer = ArrayPool<byte>.Shared.Rent(numWholeReadBlocks * _outputBlockSize); numOutputBytes = _transform.TransformBlock(tempInputBuffer, 0, numWholeReadBlocksInBytes, tempOutputBuffer, 0); Buffer.BlockCopy(tempOutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); // Clear what was written while we know how much that was CryptographicOperations.ZeroMemory(new Span<byte>(tempOutputBuffer, 0, numOutputBytes)); ArrayPool<byte>.Shared.Return(tempOutputBuffer); tempOutputBuffer = null; bytesToDeliver -= numOutputBytes; currentOutputIndex += numOutputBytes; } } finally { // If we rented and then an exception happened we don't know how much was written to, // clear the whole thing and return it. if (tempOutputBuffer != null) { CryptographicOperations.ZeroMemory(tempOutputBuffer); ArrayPool<byte>.Shared.Return(tempOutputBuffer); tempOutputBuffer = null; } CryptographicOperations.ZeroMemory(new Span<byte>(tempInputBuffer, 0, numWholeBlocksInBytes)); ArrayPool<byte>.Shared.Return(tempInputBuffer); tempInputBuffer = null; } } // try to fill _InputBuffer so we have something to transform while (bytesToDeliver > 0) { while (_inputBufferIndex < _inputBlockSize) { amountRead = useAsync ? await _stream.ReadAsync(new Memory<byte>(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex), cancellationToken) : // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread _stream.Read(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex); // first, check to see if we're at the end of the input stream if (amountRead == 0) goto ProcessFinalBlock; _inputBufferIndex += amountRead; } numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0); _inputBufferIndex = 0; if (bytesToDeliver >= numOutputBytes) { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, 0, numOutputBytes)); currentOutputIndex += numOutputBytes; bytesToDeliver -= numOutputBytes; } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _outputBufferIndex = numOutputBytes - bytesToDeliver; Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex); int toClear = _outputBuffer.Length - _outputBufferIndex; CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear)); return count; } } return count; ProcessFinalBlock: // if so, then call TransformFinalBlock to get whatever is left byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex); // now, since _OutputBufferIndex must be 0 if we're in the while loop at this point, // reset it to be what we just got back _outputBuffer = finalBytes; _outputBufferIndex = finalBytes.Length; // set the fact that we've transformed the final block _finalBlockTransformed = true; // now, return either everything we just got or just what's asked for, whichever is smaller if (bytesToDeliver < _outputBufferIndex) { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _outputBufferIndex -= bytesToDeliver; Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex); int toClear = _outputBuffer.Length - _outputBufferIndex; CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear)); return (count); } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, _outputBufferIndex); bytesToDeliver -= _outputBufferIndex; _outputBufferIndex = 0; CryptographicOperations.ZeroMemory(_outputBuffer); return (count - bytesToDeliver); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckWriteArguments(buffer, offset, count); return WriteAsyncInternal(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); private async Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = AsyncActiveSemaphore; await semaphore.WaitAsync().ForceAsync(); try { await WriteAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); // ConfigureAwait not needed due to earlier ForceAsync } finally { semaphore.Release(); } } public override void Write(byte[] buffer, int offset, int count) { CheckWriteArguments(buffer, offset, count); WriteAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).GetAwaiter().GetResult(); } private void CheckWriteArguments(byte[] buffer, int offset, int count) { if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); } private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync) { // write <= count bytes to the output stream, transforming as we go. // Basic idea: using bytes in the _InputBuffer first, make whole blocks, // transform them, and write them out. Cache any remaining bytes in the _InputBuffer. int bytesToWrite = count; int currentInputIndex = offset; // if we have some bytes in the _InputBuffer, we have to deal with those first, // so let's try to make an entire block out of it if (_inputBufferIndex > 0) { if (count >= _inputBlockSize - _inputBufferIndex) { // we have enough to transform at least a block, so fill the input block Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex); currentInputIndex += (_inputBlockSize - _inputBufferIndex); bytesToWrite -= (_inputBlockSize - _inputBufferIndex); _inputBufferIndex = _inputBlockSize; // Transform the block and write it out } else { // not enough to transform a block, so just copy the bytes into the _InputBuffer // and return Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, count); _inputBufferIndex += count; return; } } // If the OutputBuffer has anything in it, write it out if (_outputBufferIndex > 0) { if (useAsync) await _stream.WriteAsync(new ReadOnlyMemory<byte>(_outputBuffer, 0, _outputBufferIndex), cancellationToken); // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread else _stream.Write(_outputBuffer, 0, _outputBufferIndex); _outputBufferIndex = 0; } // At this point, either the _InputBuffer is full, empty, or we've already returned. // If full, let's process it -- we now know the _OutputBuffer is empty int numOutputBytes; if (_inputBufferIndex == _inputBlockSize) { numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0); // write out the bytes we just got if (useAsync) await _stream.WriteAsync(new ReadOnlyMemory<byte>(_outputBuffer, 0, numOutputBytes), cancellationToken); // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread else _stream.Write(_outputBuffer, 0, numOutputBytes); // reset the _InputBuffer _inputBufferIndex = 0; } while (bytesToWrite > 0) { if (bytesToWrite >= _inputBlockSize) { // We have at least an entire block's worth to transform int numWholeBlocks = bytesToWrite / _inputBlockSize; // If the transform will handle multiple blocks at once, do that if (_transform.CanTransformMultipleBlocks && numWholeBlocks > 1) { int numWholeBlocksInBytes = numWholeBlocks * _inputBlockSize; byte[] tempOutputBuffer = ArrayPool<byte>.Shared.Rent(numWholeBlocks * _outputBlockSize); numOutputBytes = 0; try { numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, numWholeBlocksInBytes, tempOutputBuffer, 0); if (useAsync) { await _stream.WriteAsync(new ReadOnlyMemory<byte>(tempOutputBuffer, 0, numOutputBytes), cancellationToken); // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread } else { _stream.Write(tempOutputBuffer, 0, numOutputBytes); } currentInputIndex += numWholeBlocksInBytes; bytesToWrite -= numWholeBlocksInBytes; } finally { CryptographicOperations.ZeroMemory(new Span<byte>(tempOutputBuffer, 0, numOutputBytes)); ArrayPool<byte>.Shared.Return(tempOutputBuffer); tempOutputBuffer = null; } } else { // do it the slow way numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, _inputBlockSize, _outputBuffer, 0); if (useAsync) await _stream.WriteAsync(new ReadOnlyMemory<byte>(_outputBuffer, 0, numOutputBytes), cancellationToken); // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread else _stream.Write(_outputBuffer, 0, numOutputBytes); currentInputIndex += _inputBlockSize; bytesToWrite -= _inputBlockSize; } } else { // In this case, we don't have an entire block's worth left, so store it up in the // input buffer, which by now must be empty. Buffer.BlockCopy(buffer, currentInputIndex, _inputBuffer, 0, bytesToWrite); _inputBufferIndex += bytesToWrite; return; } } return; } public void Clear() { Close(); } protected override void Dispose(bool disposing) { try { if (disposing) { if (!_finalBlockTransformed) { FlushFinalBlock(); } if (!_leaveOpen) { _stream.Dispose(); } } } finally { try { // Ensure we don't try to transform the final block again if we get disposed twice // since it's null after this _finalBlockTransformed = true; // we need to clear all the internal buffers if (_inputBuffer != null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); if (_outputBuffer != null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); _inputBuffer = null; _outputBuffer = null; _canRead = false; _canWrite = false; } finally { base.Dispose(disposing); } } } // Private methods private void InitializeBuffer() { if (_transform != null) { _inputBlockSize = _transform.InputBlockSize; _inputBuffer = new byte[_inputBlockSize]; _outputBlockSize = _transform.OutputBlockSize; _outputBuffer = new byte[_outputBlockSize]; } } private SemaphoreSlim AsyncActiveSemaphore { get { // Lazily-initialize _lazyAsyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _lazyAsyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } } } }
using System; using System.Collections; using System.Collections.Generic; using Xunit; public static class xUnitSpecificationExtensions { public static void ShouldBeFalse(this bool condition) { ShouldBeFalse(condition, string.Empty); } public static void ShouldBeFalse(this bool condition, string message) { Assert.False(condition, message); } public static void ShouldBeTrue(this bool condition) { ShouldBeTrue(condition, string.Empty); } public static void ShouldBeTrue(this bool condition, string message) { Assert.True(condition, message); } public static T ShouldEqual<T>(this T actual, T expected) { Assert.Equal(expected, actual); return actual; } public static T ShouldEqual<T>(this T actual, T expected, IEqualityComparer<T> comparer) { Assert.Equal(expected, actual, comparer); return actual; } public static string ShouldEqual(this string actual, string expected, StringComparer comparer) { Assert.Equal(expected, actual, comparer); return actual; } public static T ShouldNotEqual<T>(this T actual, T expected) { Assert.NotEqual(expected, actual); return actual; } public static string ShouldNotEqual(this string actual, string expected, StringComparer comparer) { Assert.NotEqual(expected, actual, comparer); return actual; } public static T ShouldNotEqual<T>(this T actual, T expected, IEqualityComparer<T> comparer) { Assert.NotEqual(expected, actual, comparer); return actual; } public static void ShouldBeNull(this object anObject) { Assert.Null(anObject); } public static T ShouldNotBeNull<T>(this T anObject) { Assert.NotNull(anObject); return anObject; } public static object ShouldBeTheSameAs(this object actual, object expected) { Assert.Same(expected, actual); return actual; } public static object ShouldNotBeTheSameAs(this object actual, object expected) { Assert.NotSame(expected, actual); return actual; } public static T ShouldBeOfType<T>(this T actual, Type expected) { Assert.IsType(expected, actual); return actual; } public static T ShouldNotBeOfType<T>(this T actual, Type expected) { Assert.IsNotType(expected, actual); return actual; } public static IEnumerable ShouldBeEmpty(this IEnumerable collection) { Assert.Empty(collection); return collection; } public static IEnumerable ShouldNotBeEmpty(this IEnumerable collection) { Assert.NotEmpty(collection); return collection; } public static string ShouldContain(this string actualString, string expectedSubString) { Assert.Contains(expectedSubString, actualString); return actualString; } public static string ShouldContain(this string actualString, string expectedSubString, StringComparison comparisonType) { Assert.Contains(expectedSubString, actualString, comparisonType); return actualString; } public static IEnumerable<string> ShouldContain(this IEnumerable<string> collection, string expected, StringComparer comparer) { Assert.Contains(expected, collection, comparer); return collection; } public static IEnumerable<T> ShouldContain<T>(this IEnumerable<T> collection, T expected) { Assert.Contains(expected, collection); return collection; } public static IEnumerable<T> ShouldContain<T>(this IEnumerable<T> collection, T expected, IEqualityComparer<T> equalityComparer) { Assert.Contains(expected, collection, equalityComparer); return collection; } public static string ShouldNotContain(this string actualString, string expectedSubString) { Assert.DoesNotContain(expectedSubString, actualString); return actualString; } public static string ShouldNotContain(this string actualString, string expectedSubString, StringComparison comparisonType) { Assert.DoesNotContain(expectedSubString, actualString, comparisonType); return actualString; } public static IEnumerable<string> ShouldNotContain(this IEnumerable<string> collection, string expected, StringComparer comparer) { Assert.DoesNotContain(expected, collection, comparer); return collection; } public static IEnumerable<T> ShouldNotContain<T>(this IEnumerable<T> collection, T expected) { Assert.DoesNotContain(expected, collection); return collection; } public static IEnumerable<T> ShouldNotContain<T>(this IEnumerable<T> collection, T expected, IEqualityComparer<T> equalityComparer) { Assert.DoesNotContain(expected, collection, equalityComparer); return collection; } //public static Exception ShouldBeThrownBy(this Type exceptionType, Assert.ThrowsDelegate method) //{ // return Assert.Throws(exceptionType, method); //} //public static void ShouldNotThrow(this Assert.ThrowsDelegate method) //{ // Assert.DoesNotThrow(method); //} public static T IsInRange<T>(this T actual, T low, T high) where T : IComparable { Assert.InRange(actual, low, high); return actual; } public static T IsInRange<T>(this T actual, T low, T high, IComparer<T> comparer) { Assert.InRange(actual, low, high, comparer); return actual; } public static T IsNotInRange<T>(this T actual, T low, T high) where T : IComparable { Assert.NotInRange(actual, low, high); return actual; } public static T IsNotInRange<T>(this T actual, T low, T high, IComparer<T> comparer) { Assert.NotInRange(actual, low, high, comparer); return actual; } public static IEnumerable IsEmpty(this IEnumerable collection) { Assert.Empty(collection); return collection; } public static T IsType<T>(this T actual, Type expectedType) { Assert.IsType(expectedType, actual); return actual; } public static T IsNotType<T>(this T actual, Type expectedType) { Assert.IsNotType(expectedType, actual); return actual; } public static T IsAssignableFrom<T>(this T actual, Type expectedType) { Assert.IsAssignableFrom(expectedType, actual); return actual; } /* Consider implementing these later public static string ShouldBeEqualIgnoringCase(this string actual, string expected) { StringAssert.AreEqualIgnoringCase(expected, actual); return actual; } public static string ShouldStartWith(this string actual, string expected) { StringAssert.StartsWith(expected, actual); return actual; } public static string ShouldEndWith(this string actual, string expected) { StringAssert.EndsWith(expected, actual); return actual; } public static void ShouldBeSurroundedWith(this string actual, string expectedStartDelimiter, string expectedEndDelimiter) { StringAssert.StartsWith(expectedStartDelimiter, actual); StringAssert.EndsWith(expectedEndDelimiter, actual); } public static void ShouldBeSurroundedWith(this string actual, string expectedDelimiter) { StringAssert.StartsWith(expectedDelimiter, actual); StringAssert.EndsWith(expectedDelimiter, actual); } public static void ShouldContainErrorMessage(this Exception exception, string expected) { StringAssert.Contains(expected, exception.Message); } */ }
// Copyright (c) 2011, Eric Maupin // 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 Gablarski nor the names of its // contributors may be used to endorse or promote products // or services derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS // AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. using System; using System.Collections.Generic; using System.Linq; using Gablarski.Client; using Cadenza; using Tempest; namespace Gablarski { [Flags] public enum UserStatus : byte { Normal = 0, MutedMicrophone = 1, MutedSound = 2, AFK = 4 } /// <summary> /// Represents a joined user. /// </summary> public class UserInfo : IUserInfo { internal UserInfo() { } internal UserInfo (IUserInfo info) { if (info == null) throw new ArgumentNullException ("info"); UserId = info.UserId; Username = info.Username; Nickname = info.Nickname; Phonetic = info.Phonetic; CurrentChannelId = info.CurrentChannelId; IsMuted = info.IsMuted; Status = info.Status; Comment = info.Comment; } internal UserInfo (string nickname, string username, int userId, int currentChannelId, bool muted) : this (nickname, null, username, userId, currentChannelId, muted) { } internal UserInfo (IUserInfo user, bool muted) : this (user.Nickname, user.Phonetic, user.Username, user.UserId, user.CurrentChannelId, muted, user.Comment, user.Status) { } internal UserInfo (IUserInfo user, int currentChannelId) : this (user.Nickname, user.Phonetic, user.Username, user.UserId, currentChannelId, user.IsMuted, user.Comment, user.Status) { } internal UserInfo (IUserInfo user, string comment) : this (user.Nickname, user.Phonetic, user.Username, user.UserId, user.CurrentChannelId, user.IsMuted, comment, user.Status) { } internal UserInfo (IUserInfo user, UserStatus status) : this (user.Nickname, user.Phonetic, user.Username, user.UserId, user.CurrentChannelId, user.IsMuted, user.Comment, status) { } internal UserInfo (string nickname, string phonetic, IUserInfo info) : this (nickname, phonetic, info.Username, info.UserId, info.CurrentChannelId, info.IsMuted) { } internal UserInfo (string nickname, string phonetic, string username, int userId, int currentChannelId, bool muted) : this(nickname, phonetic, username, userId, currentChannelId, muted, null, UserStatus.Normal) { } internal UserInfo (string nickname, string phonetic, string username, int userId, int currentChannelId, bool muted, string comment, UserStatus status) { //if (nickname.IsNullOrWhitespace()) // throw new ArgumentNullException ("nickname"); if (username.IsNullOrWhitespace()) throw new ArgumentNullException ("username"); if (userId == 0) throw new ArgumentException ("userId"); if (currentChannelId < 0) throw new ArgumentOutOfRangeException ("currentChannelId"); Nickname = nickname; Phonetic = phonetic; Username = username; UserId = userId; CurrentChannelId = currentChannelId; IsMuted = muted; Comment = comment; Status = status; } internal UserInfo (string username, int userId, int currentChannelId, bool muted) { if (username.IsNullOrWhitespace()) throw new ArgumentNullException ("username"); if (userId == 0) throw new ArgumentException ("userId"); if (currentChannelId < 0) throw new ArgumentOutOfRangeException ("currentChannelId"); Username = username; UserId = userId; CurrentChannelId = currentChannelId; IsMuted = muted; } internal UserInfo (ISerializationContext context, IValueReader reader) { if (reader == null) throw new ArgumentNullException("reader"); Deserialize (context, reader); } public int UserId { get; protected set; } /// <summary> /// Gets whether the user is registered or is a guest. /// </summary> public bool IsRegistered { get { return (UserId > 0); } } /// <summary> /// Gets the user's unique username. <see cref="Nickname"/> if unregistered. /// </summary> public string Username { get; protected set; } /// <summary> /// Gets the Id of the channel the user is currently in. /// </summary> public int CurrentChannelId { get; protected set; } /// <summary> /// Gets the user's nickname. /// </summary> public string Nickname { get; protected set; } /// <summary> /// Gets the user's phonetic. /// </summary> public string Phonetic { get; protected set; } /// <summary> /// Gets whether the user is muted or not. /// </summary> public bool IsMuted { get; protected set; } public UserStatus Status { get; protected set; } public string Comment { get; protected set; } public void Serialize (ISerializationContext context, IValueWriter writer) { writer.WriteInt32 (UserId); writer.WriteString (Username); writer.WriteInt32 (CurrentChannelId); writer.WriteString (Nickname); writer.WriteString (Phonetic); writer.WriteBool (IsMuted); writer.WriteByte ((byte)Status); writer.WriteString (Comment); } public void Deserialize (ISerializationContext context, IValueReader reader) { UserId = reader.ReadInt32(); Username = reader.ReadString(); CurrentChannelId = reader.ReadInt32(); Nickname = reader.ReadString(); Phonetic = reader.ReadString(); IsMuted = reader.ReadBool(); Status = (UserStatus)reader.ReadByte(); Comment = reader.ReadString(); } public override int GetHashCode() { return this.Username.GetHashCode(); } public override bool Equals (object obj) { var info = (obj as IUserInfo); if (info != null) return Username == info.Username; var cu = (obj as CurrentUser); if (cu != null) return (Username == cu.Username); return false; } public bool Equals (IUserInfo other) { if (ReferenceEquals (null, other)) return false; if (ReferenceEquals (this, other)) return true; return Equals (other.Username, this.Username); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Internal.NativeCrypto; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Internal.Cryptography.Pal { internal sealed partial class CertificatePal : IDisposable, ICertificatePal { public static ICertificatePal FromBlob(byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(rawData, null, password, keyStorageFlags); } public static ICertificatePal FromFile(String fileName, String password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(null, fileName, password, keyStorageFlags); } private static ICertificatePal FromBlobOrFile(byte[] rawData, String fileName, String password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(rawData != null || fileName != null); bool loadFromFile = (fileName != null); PfxCertStoreFlags pfxCertStoreFlags = MapKeyStorageFlags(keyStorageFlags); bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet)); CertEncodingType msgAndCertEncodingType; ContentType contentType; FormatType formatType; SafeCertStoreHandle hCertStore = null; SafeCryptMsgHandle hCryptMsg = null; SafeCertContextHandle pCertContext = null; try { unsafe { fixed (byte* pRawData = rawData) { fixed (char* pFileName = fileName) { CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(loadFromFile ? 0 : rawData.Length, pRawData); CertQueryObjectType objectType = loadFromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB; void* pvObject = loadFromFile ? (void*)pFileName : (void*)&certBlob; bool success = Interop.crypt32.CryptQueryObject( objectType, pvObject, X509ExpectedContentTypeFlags, X509ExpectedFormatTypeFlags, 0, out msgAndCertEncodingType, out contentType, out formatType, out hCertStore, out hCryptMsg, out pCertContext ); if (!success) { int hr = Marshal.GetHRForLastWin32Error(); throw hr.ToCryptographicException(); } } } if (contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED || contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED) { pCertContext = GetSignerInPKCS7Store(hCertStore, hCryptMsg); } else if (contentType == ContentType.CERT_QUERY_CONTENT_PFX) { if (loadFromFile) rawData = File.ReadAllBytes(fileName); pCertContext = FilterPFXStore(rawData, password, pfxCertStoreFlags); } CertificatePal pal = new CertificatePal(pCertContext, deleteKeyContainer: !persistKeySet); pCertContext = null; return pal; } } finally { if (hCertStore != null) hCertStore.Dispose(); if (hCryptMsg != null) hCryptMsg.Dispose(); if (pCertContext != null) pCertContext.Dispose(); } } private static SafeCertContextHandle GetSignerInPKCS7Store(SafeCertStoreHandle hCertStore, SafeCryptMsgHandle hCryptMsg) { // make sure that there is at least one signer of the certificate store int dwSigners; int cbSigners = sizeof(int); if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_COUNT_PARAM, 0, out dwSigners, ref cbSigners)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (dwSigners == 0) throw ErrorCode.CRYPT_E_SIGNER_NOT_FOUND.ToCryptographicException(); // get the first signer from the store, and use that as the loaded certificate int cbData = 0; if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, null, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; byte[] cmsgSignerBytes = new byte[cbData]; if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, cmsgSignerBytes, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; CERT_INFO certInfo = default(CERT_INFO); unsafe { fixed (byte* pCmsgSignerBytes = cmsgSignerBytes) { CMSG_SIGNER_INFO_Partial* pCmsgSignerInfo = (CMSG_SIGNER_INFO_Partial*)pCmsgSignerBytes; certInfo.Issuer.cbData = pCmsgSignerInfo->Issuer.cbData; certInfo.Issuer.pbData = pCmsgSignerInfo->Issuer.pbData; certInfo.SerialNumber.cbData = pCmsgSignerInfo->SerialNumber.cbData; certInfo.SerialNumber.pbData = pCmsgSignerInfo->SerialNumber.pbData; } SafeCertContextHandle pCertContext = null; if (!Interop.crypt32.CertFindCertificateInStore(hCertStore, CertFindType.CERT_FIND_SUBJECT_CERT, &certInfo, ref pCertContext)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return pCertContext; } } private static SafeCertContextHandle FilterPFXStore(byte[] rawData, String password, PfxCertStoreFlags pfxCertStoreFlags) { SafeCertStoreHandle hStore; unsafe { fixed (byte* pbRawData = rawData) { CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(rawData.Length, pbRawData); hStore = Interop.crypt32.PFXImportCertStore(ref certBlob, password, pfxCertStoreFlags); if (hStore.IsInvalid) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; } } try { // Find the first cert with private key. If none, then simply take the very first cert. Along the way, delete the keycontainers // of any cert we don't accept. SafeCertContextHandle pCertContext = SafeCertContextHandle.InvalidHandle; SafeCertContextHandle pEnumContext = null; while (Interop.crypt32.CertEnumCertificatesInStore(hStore, ref pEnumContext)) { if (pEnumContext.ContainsPrivateKey) { if ((!pCertContext.IsInvalid) && pCertContext.ContainsPrivateKey) { // We already found our chosen one. Free up this one's key and move on. SafeCertContextHandleWithKeyContainerDeletion.DeleteKeyContainer(pEnumContext); } else { // Found our first cert that has a private key. Set him up as our chosen one but keep iterating // as we need to free up the keys of any remaining certs. pCertContext.Dispose(); pCertContext = pEnumContext.Duplicate(); } } else { if (pCertContext.IsInvalid) pCertContext = pEnumContext.Duplicate(); // Doesn't have a private key but hang on to it anyway in case we don't find any certs with a private key. } } if (pCertContext.IsInvalid) { // For compat, setting "hr" to ERROR_INVALID_PARAMETER even though ERROR_INVALID_PARAMETER is not actually an HRESULT. throw ErrorCode.ERROR_INVALID_PARAMETER.ToCryptographicException(); } return pCertContext; } finally { hStore.Dispose(); } } private static PfxCertStoreFlags MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) { if ((keyStorageFlags & (X509KeyStorageFlags)~0x1F) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, "keyStorageFlags"); PfxCertStoreFlags pfxCertStoreFlags = 0; if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_KEYSET; else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_MACHINE_KEYSET; if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_EXPORTABLE; if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_PROTECTED; // In the full .NET Framework loading a PFX then adding the key to the Windows Certificate Store would // enable a native application compiled against CAPI to find that private key and interoperate with it. // // For CoreFX this behavior is being retained. // // For .NET Native (UWP) the API used to delete the private key (if it wasn't added to a store) is not // allowed to be called if the key is stored in CAPI. So for UWP force the key to be stored in the // CNG Key Storage Provider, then deleting the key with CngKey.Delete will clean up the file on disk, too. #if NETNATIVE pfxCertStoreFlags |= PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP; #endif return pfxCertStoreFlags; } private const ExpectedContentTypeFlags X509ExpectedContentTypeFlags = ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PFX; private const ExpectedFormatTypeFlags X509ExpectedFormatTypeFlags = ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_ALL; } }
using Discord; using Discord.Commands; using System.IO; using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Configuration; using Cleverbot.Net; using System.Security.Cryptography;//for the killswitch using System.Linq;//for the killswitch class Program { static void Main(string[] args) => new Program().Start(); private DiscordClient _client; public void Start() { _client = new DiscordClient(); _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity} - {DateTime.UtcNow.Hour}:{DateTime.UtcNow.Minute}:{DateTime.UtcNow.Second}] {e.Source}: {e.Message}"); CleverbotSession session = null; _client.UsingCommands(x => { x.PrefixChar = '+'; x.AllowMentionPrefix = true; x.HelpMode = HelpMode.Public; }); char p = '+'; // var sepchar = Path.DirectorySeparatorChar; string topic = "Ready to play a Mini TWOW!"; _client.GetService<CommandService>().CreateCommand("botok") //create command .Alias("ping", "status") // add some aliases .Description("Checks if the bot is online.") //add description, it will be shown when +help is used .Do(async e => { if (IsMTWOWChannel(e.Server.Id, e.Channel.Id)) await e.Channel.SendMessage($"bot is online \ud83d\udc4c"); }); _client.GetService<CommandService>().CreateCommand("kill") //killswitch .Alias("shutdown") .Description("Shuts down the bot if correct parameter is given") .Parameter("keyword", ParameterType.Multiple) .Do(e => { string keyhash = "0a7a27bedd1f822ac176d55217c0cdc9e8573f173d2b1a525e3607a7614a29b7"; try { if (e.Channel.IsPrivate && sha256_hash(e.GetArg("keyword")) == keyhash) { System.Environment.Exit(1); } } catch { } }); _client.GetService<CommandService>().CreateCommand("prepare") .Alias("setup") .Description("Prepares the current channel for a Mini TWOW.") .Do(async e => { User bot = e.Server.GetUser(_client.CurrentUser.Id); if (bot.GetPermissions(e.Channel).ManageChannel) { if (e.User.GetPermissions(e.Channel).ManageChannel) { Clear("data", e.Server.Id); SaveLine("data", e.Channel.Id.ToString(), e.Server.Id, 1); SaveLine("data", "0", e.Server.Id, 2); SaveLine("data", "null", e.Server.Id, 3); Clear("users", e.Server.Id); //see wiki for dev notes/file layout await e.Channel.Edit(e.Channel.Name, $"{topic}\n{e.Channel.Topic.Replace($"{topic}", "")}", e.Channel.Position); await e.Channel.SendMessage($"This channel is now ready to play Mini TWOWs!"); } else { await e.Channel.SendMessage($"You must have the `MANAGE_CHANNELS` permission to use this command!"); } } else { await e.Channel.SendMessage($"Please give the bot permissions to manage the channel!"); } }); _client.GetService<CommandService>().CreateCommand("create") .Alias("make") .Description("Creates a Mini TWOW game.") .Do(async e => { ulong mtChannel = 000000000000000000; string data = LoadLine("data", e.Server.Id, 1); bool parseResult = ulong.TryParse(data, out mtChannel); if (parseResult) { if (e.Channel.Id == mtChannel && e.Server.GetUser(_client.CurrentUser.Id).GetPermissions(e.Channel).SendMessages) { int gamestatus = 100; data = LoadLine("data", e.Server.Id, 2); bool newParseResult = int.TryParse(data, out gamestatus); if (newParseResult) { if (gamestatus == 0) { SaveLine("data", "1", e.Server.Id, 2); SaveLine("data", e.User.Id.ToString(), e.Server.Id, 3); Clear("users", e.Server.Id); await e.Channel.SendMessage($"You have successfully created a Mini TWOW game! Run `{p}join` to join the game, and run `{p}start` when you're ready to start the game."); } else { await e.Channel.SendMessage($"A game is already running. Please wait for it to finish!"); } } else { await e.Channel.SendMessage($"The data file has been corrupted. Please ask a user with `MANAGE_CHANNELS` perms to do `{p}prepare`."); } } else { // await e.Channel.SendMessage($"Please go to <#{mtChannel}> to start a Mini TWOW!"); } } else { await e.Channel.SendMessage($"Please get a user with `MANAGE_CHANNELS` permissions to run the `{p}prepare` command before starting a Mini TWOW."); } }); _client.GetService<CommandService>().CreateCommand("join") .Description("Joins an active Mini TWOW game.") .Do(async e => { try { if (IsMTWOWChannel(e.Server.Id, e.Channel.Id)) { int gamestatus = 100; string data = LoadLine("data", e.Server.Id, 2); bool parseResult = int.TryParse(data, out gamestatus); if (parseResult) { if (gamestatus == 1) { string[] users = LoadFile("users", e.Server.Id); if (users == null) { string newUsers = $"{e.User.Id.ToString()}\n"; SaveFile("users", newUsers, e.Server.Id); await e.Channel.SendMessage($"You have successfully joined the game."); } bool inGame = false; foreach (string user in users) { ulong userID = 000000000000000000; bool parse = ulong.TryParse(user, out userID); if (parse) inGame |= userID == e.User.Id; } if (inGame) await e.Channel.SendMessage($"You are already in the game!"); else { string newUsers = users.ToString(); newUsers += $"{e.User.Id.ToString()}\n"; SaveFile("users", newUsers, e.Server.Id); await e.Channel.SendMessage($"You have successfully joined the game."); } } else if (gamestatus == 0) { await e.Channel.SendMessage($"No game is currently running. Type `{p}create` to create a game!"); } else { await e.Channel.SendMessage($"It is too late to join the game!"); } } else { await e.Channel.SendMessage($"The data file has been corrupted. Please ask a user with `MANAGE_CHANNELS` permissions to do `{p}prepare`."); } } } catch (Exception error) { Console.WriteLine($"[ERROR] somethin borked during {p}join: {error.ToString()}"); } }); _client.GetService<CommandService>().CreateCommand("chat") .Description("Talk with the bot") .Parameter("sentence", ParameterType.Unparsed) .Do(async e => { try { if (session == null) { string ChatUser = File.ReadAllLines("logins.txt")[1]; string ChatKey = File.ReadAllLines("logins.txt")[2]; session = await CleverbotSession.NewSessionAsync(ChatUser, ChatKey); } string response = await session.SendAsync(e.GetArg("sentence")); await e.Channel.SendMessage(response); } catch (Exception error) { Console.WriteLine($"[ERROR] An issue occured while trying to +chat: {error.ToString()}"); } }); _client.GetService<CommandService>().CreateGroup("test", cgb => { cgb.CreateCommand("save") .Description("Multi-server data test") .Parameter("data", ParameterType.Unparsed) .Do(async e => { //Save("data", e.GetArg("data"), e.Server.Id, 1); //await e.Channel.SendMessage($"data saved"); await e.Channel.SendMessage($"no"); }); cgb.CreateCommand("load") .Description("Multi-server data test") .Parameter("line", ParameterType.Required) .Do(async e => { try { /* int i = 0; // line number bool success = int.TryParse(e.GetArg("line"), out i); // output line number to line number if (success) // check if line number was parsed successfully { string data = Load("data", e.Server.Id, i); // run Load with required data if (data != null) // check if operation was successful await e.Channel.SendMessage(data); // output line else if it failed... await e.Channel.SendMessage("file/line didnt exist"); // ...then say it failed } else { await e.Channel.SendMessage($"failed to parse input ({e.GetArg("line")})"); // input wasn't an int }*/ await e.Channel.SendMessage($"no"); } catch (Exception error) { await e.Channel.SendMessage($"error: {error.ToString()}"); } }); }); _client.Ready += (s, e) => { Console.WriteLine($"[{DateTime.UtcNow.Hour}:{DateTime.UtcNow.Minute}:{DateTime.UtcNow.Second}] Connected as {_client.CurrentUser.Name}#{_client.CurrentUser.Discriminator}"); }; _client.ExecuteAndWait(async () => { string token = File.ReadAllLines("logins.txt")[0]; await _client.Connect(token, TokenType.Bot); }); } public void SaveLine(string filename, string data, ulong server, int linenumber) { var sepchar = Path.DirectorySeparatorChar; // get operating system's directory seperation character var path = $"{Directory.GetCurrentDirectory() + sepchar + server.ToString() + sepchar}"; // get data save directory var datafile = $"{path + filename}.txt"; // get config file Directory.CreateDirectory(path); // create directory StringBuilder newconfig = new StringBuilder(); // create empty "text file" in memory if (File.Exists(datafile)) // checks if data file exists { if (new FileInfo(datafile).Length >= 2) // checks if data file has data { string[] config = File.ReadAllLines(datafile); // read all lines of the text file int currentline = 1; // set current line in the text file foreach (String line in config) { if (currentline == linenumber) { newconfig.Append(data + Environment.NewLine); } // replace line 1 of data with custom stuff else { newconfig.Append(line + Environment.NewLine); } // add other lines to file currentline++; // increase line number } if (linenumber - config.Length == 1) { newconfig.Append(data + Environment.NewLine); } } else { newconfig.Append(data + Environment.NewLine); } // file has nothing so just add data to first line } else { newconfig.Append(data + Environment.NewLine); } // file doesn't exist so create it with input File.WriteAllText(datafile, newconfig.ToString()); // save changes to file } public string LoadLine(string filename, ulong server, int line) { line -= 1; var sepchar = Path.DirectorySeparatorChar; // Grab the current operating system's seperation char. (eg. windows: \, linux: /) var path = $"{Directory.GetCurrentDirectory() + sepchar + server.ToString() + sepchar}"; // get directory of data file var datafile = $"{path + filename}.txt"; // get data file Directory.CreateDirectory(path); // create directory if it doesn't exist if (File.Exists(datafile)) // check if file exists { var config = File.ReadAllLines(datafile); // read config if (!string.IsNullOrWhiteSpace(config[line])) return config[line]; // return line else return null; } else { return null; // can't load if file doesn't exist } } public void SaveFile(string filename, string data, ulong server) { var sepchar = Path.DirectorySeparatorChar; // get operating system's directory seperation character var path = $"{Directory.GetCurrentDirectory() + sepchar + server.ToString() + sepchar}"; // get data save directory var datafile = $"{path + filename}.txt"; // get config file Directory.CreateDirectory(path); // create directory File.WriteAllText(datafile, data); // save changes to file } public string[] LoadFile(string filename, ulong server) { var sepchar = Path.DirectorySeparatorChar; // Grab the current operating system's seperation char. (eg. windows: \, linux: /) var path = $"{Directory.GetCurrentDirectory() + sepchar + server.ToString() + sepchar}"; // get directory of data file var datafile = $"{path + filename}.txt"; // get data file Directory.CreateDirectory(path); // create directory if it doesn't exist if (File.Exists(datafile)) // check if file exists { var config = File.ReadAllLines(datafile); // read config if (config.Length > 0) return config; // return file return null; // file had no lines } return null; // can't load if file doesn't exist } public void Clear(string filename, ulong server) { var sepchar = Path.DirectorySeparatorChar; // get operating system's directory seperation character var path = $"{Directory.GetCurrentDirectory() + sepchar + server.ToString() + sepchar}"; // get data save directory var datafile = $"{path + filename}data.txt"; // get config file Directory.CreateDirectory(path); // create directory File.WriteAllText(datafile, null); } public bool IsMTWOWChannel(ulong server, ulong channel) { ulong mtChannel = 000000000000000000; string data = LoadLine("data", server, 1); bool parseResult = ulong.TryParse(data, out mtChannel); if (parseResult) { if (channel == mtChannel) return true; return false; } return false; } public static void VoteCount(ulong server, string twow, int elim, int prize) {//framework is here, modify as needed string counter = ConfigurationManager.AppSettings.Get("Counter");//change these settings in App.config string python = ConfigurationManager.AppSettings.Get("PyPath"); ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python); myProcessStartInfo.UseShellExecute = false; myProcessStartInfo.RedirectStandardOutput = true; myProcessStartInfo.Arguments = counter + " "+server+"/"+twow+" -e "+elim+" -t "+prize; Process myProcess = new Process(); myProcess.StartInfo = myProcessStartInfo; myProcess.Start(); myProcess.WaitForExit(); myProcess.Close(); } public static void GenerateBooksona(ulong server, string name) { string bookMaker = ConfigurationManager.AppSettings.Get("BookMaker");//change these settings in App.config string python = ConfigurationManager.AppSettings.Get("PyPath"); ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python); myProcessStartInfo.UseShellExecute = false; myProcessStartInfo.RedirectStandardOutput = true; myProcessStartInfo.Arguments = bookMaker + " " + server + "/booksonas " + name; Process myProcess = new Process(); myProcess.StartInfo = myProcessStartInfo; myProcess.Start(); myProcess.WaitForExit(); myProcess.Close(); } public static String sha256_hash(String value)//for the killswitch { using (SHA256 hash = SHA256Managed.Create()) { return String.Concat(hash .ComputeHash(Encoding.UTF8.GetBytes(value)) .Select(item => item.ToString("x2"))); } } }
/* Copyright(c) 2009, Stefan Simek Copyright(c) 2016, Vladyslav Taranov 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. */ #if !PHONE8 using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; #if FEAT_IKVM using IKVM.Reflection; using IKVM.Reflection.Emit; using Type = IKVM.Reflection.Type; using MissingMethodException = System.MissingMethodException; using MissingMemberException = System.MissingMemberException; using DefaultMemberAttribute = System.Reflection.DefaultMemberAttribute; using Attribute = IKVM.Reflection.CustomAttributeData; using BindingFlags = IKVM.Reflection.BindingFlags; #else using System.Reflection; using System.Reflection.Emit; using Universe = System.AppDomain; #endif namespace TriAxis.RunSharp { public class AssemblyGen : ICodeGenBasicContext { readonly List<TypeGen> _types = new List<TypeGen>(); List<AttributeGen> _assemblyAttributes; List<AttributeGen> _moduleAttributes; string _ns; internal AssemblyBuilder AssemblyBuilder { get; set; } internal ModuleBuilder ModuleBuilder { get; set; } public ExpressionFactory ExpressionFactory { get; private set; } public StaticFactory StaticFactory { get; private set; } internal void AddType(TypeGen tg) { _types.Add(tg); } class NamespaceContext : IDisposable { readonly AssemblyGen _ag; readonly string _oldNs; public NamespaceContext(AssemblyGen ag) { _ag = ag; _oldNs = ag._ns; } public void Dispose() { _ag._ns = _oldNs; } } public IDisposable Namespace(string name) { NamespaceContext nc = new NamespaceContext(this); _ns = Qualify(name); return nc; } string Qualify(string name) { if (_ns == null) return name; else return _ns + "." + name; } #region Modifiers TypeAttributes _attrs; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public AssemblyGen Public { get { _attrs |= TypeAttributes.Public; return this; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public AssemblyGen Private { get { _attrs |= TypeAttributes.NotPublic; return this; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public AssemblyGen Sealed { get { _attrs |= TypeAttributes.Sealed; return this; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public AssemblyGen Abstract { get { _attrs |= TypeAttributes.Abstract; return this; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public AssemblyGen NoBeforeFieldInit { get { _attrs |= TypeAttributes.BeforeFieldInit; return this; } } #endregion #region Custom Attributes public AssemblyGen Attribute(AttributeType type) { BeginAttribute(type); return this; } public AssemblyGen Attribute(AttributeType type, params object[] args) { BeginAttribute(type, args); return this; } public AttributeGen<AssemblyGen> BeginAttribute(AttributeType type) { return BeginAttribute(type, EmptyArray<object>.Instance); } public AttributeGen<AssemblyGen> BeginAttribute(AttributeType type, params object[] args) { return AttributeGen<AssemblyGen>.CreateAndAdd(this, ref _assemblyAttributes, AttributeTargets.Assembly, type, args, TypeMapper); } public AssemblyGen ModuleAttribute(AttributeType type) { BeginModuleAttribute(type); return this; } public AssemblyGen ModuleAttribute(AttributeType type, params object[] args) { BeginModuleAttribute(type, args); return this; } public AttributeGen<AssemblyGen> BeginModuleAttribute(AttributeType type) { return BeginModuleAttribute(type, EmptyArray<object>.Instance); } public AttributeGen<AssemblyGen> BeginModuleAttribute(AttributeType type, params object[] args) { return AttributeGen<AssemblyGen>.CreateAndAdd(this, ref _moduleAttributes, AttributeTargets.Module, type, args, TypeMapper); } #endregion #region Types public TypeGen Class(string name) { return Class(name, TypeMapper.MapType(typeof(object))); } #if FEAT_IKVM public TypeGen Class(System.Type baseType, string name) { return Class(name, TypeMapper.MapType(baseType)); } #endif public TypeGen Class(string name, Type baseType) { return Class(name, baseType, Type.EmptyTypes); } #if FEAT_IKVM public TypeGen Class(string name, System.Type baseType, params Type[] interfaces) { return Class(name, TypeMapper.MapType(baseType), interfaces); } #endif public TypeGen Class(string name, Type baseType, params Type[] interfaces) { TypeGen tg = new TypeGen(this, Qualify(name), (_attrs | TypeAttributes.Class) ^ TypeAttributes.BeforeFieldInit, baseType, interfaces, TypeMapper); _attrs = 0; return tg; } public TypeGen Struct(string name) { return Struct(name, Type.EmptyTypes); } public TypeGen Struct(string name, params Type[] interfaces) { TypeGen tg = new TypeGen(this, Qualify(name), (_attrs | TypeAttributes.Sealed | TypeAttributes.SequentialLayout) ^ TypeAttributes.BeforeFieldInit, TypeMapper.MapType(typeof(ValueType)), interfaces, TypeMapper); _attrs = 0; return tg; } public TypeGen Interface(string name) { return Interface(name, Type.EmptyTypes); } public TypeGen Interface(string name, params Type[] interfaces) { TypeGen tg = new TypeGen(this, Qualify(name), (_attrs | TypeAttributes.Interface | TypeAttributes.Abstract) & ~(TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit), null, interfaces, TypeMapper); _attrs = 0; return tg; } #if FEAT_IKVM public DelegateGen Delegate(System.Type returnType, string name) { return Delegate(TypeMapper.MapType(returnType), name); } #endif public DelegateGen Delegate(Type returnType, string name) { return new DelegateGen(this, Qualify(name), returnType, (_attrs | TypeAttributes.Sealed) & ~(TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit)); } #endregion #region Construction AssemblyBuilderAccess _access; public ITypeMapper TypeMapper { get; private set; } public Universe Universe { get; private set; } #if !FEAT_IKVM public AssemblyGen(string name, CompilerOptions options, ITypeMapper typeMapper = null) { Initialize(AppDomain.CurrentDomain, name, #if !SILVERLIGHT !Helpers.IsNullOrEmpty(options.OutputPath) ? AssemblyBuilderAccess.RunAndSave : #endif AssemblyBuilderAccess.Run, options, typeMapper); } public AssemblyGen(AppDomain domain, string name, CompilerOptions options, ITypeMapper typeMapper = null) { Initialize(domain, name, AssemblyBuilderAccess.Run, options, typeMapper); } #else public AssemblyGen(string assemblyName, CompilerOptions options) : this(new Universe(), assemblyName, options) { } public AssemblyGen(Universe universe, string assemblyName, CompilerOptions options, ITypeMapper typeMapper = null) { Initialize(universe, assemblyName, AssemblyBuilderAccess.Save, options, typeMapper); } private byte[] FromHex(string value) { if (Helpers.IsNullOrEmpty(value)) throw new ArgumentNullException("value"); int len = value.Length / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) { result[i] = Convert.ToByte(value.Substring(i * 2, 2), 16); } return result; } #endif string _fileName; void Initialize(Universe universe, string assemblyName, AssemblyBuilderAccess access, CompilerOptions options, ITypeMapper typeMapper = null) { if (universe == null) throw new ArgumentNullException(nameof(universe)); if (options == null) throw new ArgumentNullException(nameof(options)); _compilerOptions = options; if (typeMapper == null) #if FEAT_IKVM typeMapper = new TypeMapper(universe); #else typeMapper = new TypeMapper(); #endif ExpressionFactory = new ExpressionFactory(typeMapper); StaticFactory = new StaticFactory(typeMapper); #if SILVERLIGHT bool save = false; #else bool save = (access & AssemblyBuilderAccess.Save) != 0; #endif string path = options.OutputPath; if (path == null && save) throw new ArgumentNullException("options.OutputPath"); Universe = universe; TypeMapper = typeMapper; _access = access; if (Helpers.IsNullOrEmpty(assemblyName)) { if (save) throw new ArgumentNullException(nameof(assemblyName)); assemblyName = Guid.NewGuid().ToString(); } string moduleName = path == null ? assemblyName : assemblyName + Path.GetExtension(path); _fileName = path; AssemblyName an = new AssemblyName(); an.Name = assemblyName; AssemblyBuilder = #if !SILVERLIGHT path != null ? Universe.DefineDynamicAssembly(an, access, Path.GetDirectoryName(path)) : #endif Universe.DefineDynamicAssembly(an, access); #if FEAT_IKVM if (!Helpers.IsNullOrEmpty(options.KeyFile)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(File.OpenRead(options.KeyFile))); } else if (!Helpers.IsNullOrEmpty(options.KeyContainer)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(options.KeyContainer)); } else if (!Helpers.IsNullOrEmpty(options.PublicKey)) { AssemblyBuilder.__SetAssemblyPublicKey(FromHex(options.PublicKey)); } if (!Helpers.IsNullOrEmpty(options.ImageRuntimeVersion) && options.MetaDataVersion != 0) { AssemblyBuilder.__SetImageRuntimeVersion(options.ImageRuntimeVersion, options.MetaDataVersion); } ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, path, options.SymbolInfo); #else if (save) { #if !SILVERLIGHT ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, Path.GetFileName(path)); #else throw new NotSupportedException("Can't save on this platform"); #endif } else ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName); #endif } public void Save() { Complete(); #if !SILVERLIGHT if ((_access & AssemblyBuilderAccess.Save) != 0) #if FEAT_IKVM AssemblyBuilder.Save(_fileName); #else AssemblyBuilder.Save(Path.GetFileName(_fileName)); #endif #endif } public Assembly GetAssembly() { Complete(); return AssemblyBuilder; } private void WriteAssemblyAttributes(CompilerOptions options, string assemblyName, AssemblyBuilder asm) { if (!Helpers.IsNullOrEmpty(options.TargetFrameworkName)) { // get [TargetFramework] from mscorlib/equivalent and burn into the new assembly Type versionAttribType = null; try { // this is best-endeavours only versionAttribType = TypeMapper.GetType("System.Runtime.Versioning.TargetFrameworkAttribute", TypeMapper.MapType(typeof(string)).Assembly); } catch { /* don't stress */ } if (versionAttribType != null) { PropertyInfo[] props; object[] propValues; if (Helpers.IsNullOrEmpty(options.TargetFrameworkDisplayName)) { props = new PropertyInfo[0]; propValues = new object[0]; } else { props = new PropertyInfo[1] { versionAttribType.GetProperty("FrameworkDisplayName") }; propValues = new object[1] { options.TargetFrameworkDisplayName }; } CustomAttributeBuilder builder = new CustomAttributeBuilder( versionAttribType.GetConstructor(new Type[] { TypeMapper.MapType(typeof(string)) }), new object[] { options.TargetFrameworkName }, props, propValues); asm.SetCustomAttribute(builder); } } // copy assembly:InternalsVisibleTo Type internalsVisibleToAttribType = null; #if !FX11 try { internalsVisibleToAttribType = TypeMapper.MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute)); } catch { /* best endeavors only */ } #endif if (internalsVisibleToAttribType != null) { List<string> internalAssemblies = new List<string>(); List<Assembly> consideredAssemblies = new List<Assembly>(); foreach (Type type in _types) { Assembly assembly = type.Assembly; if (consideredAssemblies.IndexOf(assembly) >= 0) continue; consideredAssemblies.Add(assembly); AttributeMap[] assemblyAttribsMap = AttributeMap.Create(TypeMapper, assembly); for (int i = 0; i < assemblyAttribsMap.Length; i++) { if (assemblyAttribsMap[i].AttributeType != internalsVisibleToAttribType) continue; object privelegedAssemblyObj; assemblyAttribsMap[i].TryGet("AssemblyName", out privelegedAssemblyObj); string privelegedAssemblyName = (string)privelegedAssemblyObj; if (privelegedAssemblyName == assemblyName || Helpers.IsNullOrEmpty(privelegedAssemblyName)) continue; // ignore if (internalAssemblies.IndexOf(privelegedAssemblyName) >= 0) continue; // seen it before internalAssemblies.Add(privelegedAssemblyName); CustomAttributeBuilder builder = new CustomAttributeBuilder( internalsVisibleToAttribType.GetConstructor(new Type[] { TypeMapper.MapType(typeof(string)) }), new object[] { privelegedAssemblyName }); asm.SetCustomAttribute(builder); } } } } CompilerOptions _compilerOptions; public void Complete() { foreach (TypeGen tg in _types) tg.Complete(); AttributeGen.ApplyList(ref _assemblyAttributes, AssemblyBuilder.SetCustomAttribute); AttributeGen.ApplyList(ref _moduleAttributes, ModuleBuilder.SetCustomAttribute); WriteAssemblyAttributes(_compilerOptions, GetAssemblyName(), AssemblyBuilder); } string GetAssemblyName() { #if !SILVERLIGHT return AssemblyBuilder.GetName().Name; #else return AssemblyBuilder.GetName(false).Name; #endif } #endregion } } #endif
//WordSlide //Copyright (C) 2008-2012 Jonathan Ray <asky314159@gmail.com> //WordSlide is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //A copy of the GNU General Public License should be in the //Installer directory of this source tree. If not, see //<http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace WordSlideEngine { /// <summary> /// The DisplaySlideSet class is able to load and store data about a slide set for display on the /// screen. For the version of this class used in the editor, see EditableSlideSet. /// </summary> public class DisplaySlideSet : SlideSet { /// <summary> /// Stores the value of the index of the current slide. Used to determine which text to return /// when the current slide is requested. /// </summary> private int slideindex = 0; /// <summary> /// Stores the value of the index of the current sub-slide. Used to determine which text to /// return when the current sub-slide is requested. /// </summary> private int subslideindex = 0; /// <summary> /// Determines whether the DisplaySlideSet contains actual slides, or is just a placeholder for /// a blank slide. /// </summary> private bool blank; /// <summary> /// Determines whether or not to return a generic chorus slide or the actual current slide when /// it is requested. /// </summary> private bool showchorus; /// <summary> /// Provides access to the path to the loaded slide set. Identifies this slide set uniquely when /// the user is setting up a slide show. /// </summary> public string Path { get { return path; } } /// <summary> /// Determines whether the DisplaySlideSet contains actual slides, or is just a placeholder for /// a blank slide. /// </summary> public bool Blank { get { return blank; } } /// <summary> /// Returns a DisplaySlide containing the contents of the current slide. Will display a generic /// chorus slide when the chorus override is enabled. /// </summary> public DisplaySlide currentSlide { get { if (showchorus) return chorusSlide; else return thisSlide; } } /// <summary> /// Returns a DisplaySlide containing the text of the song's chorus. Is returned from currentSlide /// when the chorus override is enabled. /// </summary> private DisplaySlide chorusSlide { get { DisplaySlide ret = new DisplaySlide(); ret.firstslide = false; ret.title = ""; ret.by = ""; ret.copyright = ""; ret.lastslide = false; ret.text = ((chorus == -1) ? "" : texts[chorus]); ret.blank = ((chorus == -1) ? true : false); return ret; } } /// <summary> /// Returns a DisplaySlide containing the contents of the current slide. /// </summary> private DisplaySlide thisSlide { get { DisplaySlide ret = new DisplaySlide(); ret.firstslide = ((slideindex == 0) && (subslideindex == 0)); ret.title = name; ret.by = byline; ret.copyright = copyright; ret.lastslide = ((slideindex + 1 == order.Length) && (subslideindex + 1 == getSubSlideCount())); ret.text = getSubSlide(); //texts[order[slideindex]]; ret.blank = blank; return ret; } } /// <summary> /// Creates a generic DisplaySlideSet to act as a placeholder for a single blank slide. /// </summary> public DisplaySlideSet() { name = ""; path = ""; blank = true; showchorus = false; } /// <summary> /// Creates a DisplaySlideSet that is to be loaded from a SLD file located in the program's slide /// set folder. /// </summary> /// <param name="filepath">The full path to the SLD file to be loaded.</param> public DisplaySlideSet(string filepath) { blank = false; showchorus = false; path = filepath; getTitle(); } /// <summary> /// Returns either the title of the slide set or text indicating the DisplaySlideSet contains a /// blank slide placeholer. Provided for UI functionality. /// </summary> /// <returns>The title of the slide set.</returns> public override string ToString() { if (!blank) { return base.ToString(); } else { return "<Blank Slide>"; } } /// <summary> /// Populates the properties of the DisplaySlideSet with either data from its SLD file or a set /// of placeholder data. Must be called before the DisplaySlideSet can be used. /// </summary> public new void loadFile() { if (!blank) { base.loadFile(); } else { byline = ""; texts = new string[1]; texts[0] = ""; order = new int[1]; order[0] = 0; } } /// <summary> /// Increments the currently displayed slide index unless the current slide is the last slide /// in the set. /// </summary> /// <returns>False if the slide incremented normally, true if the current slide is the final one in the set.</returns> public bool incrementSlide() { showchorus = false; if (!incrementSubSlide()) { if (slideindex + 1 > order.Length - 1) return false; slideindex++; subslideindex = 0; } return true; } /// <summary> /// Decrements the currently displayed slide index unless the current slide is the first slide /// in the set. /// </summary> /// <returns>False is the slide decremented normally, true is the current slide is the first one in the set.</returns> public bool decrementSlide() { showchorus = false; if (!decrementSubSlide()) { if (slideindex - 1 < 0) return false; slideindex--; subslideindex = (getSubSlideCount() - 1); } return true; } /// <summary> /// Toggles the chorus override. When the override is active, the currentSlide property returns /// a generic chorus slide instead of the actual current slide. /// </summary> public void chorusOverride() { showchorus = !showchorus; } /// <summary> /// Determines which section of the current block of text to return, based on the slide set's /// number of lines per slide and the current sub-slide position. /// </summary> /// <returns>The string containing the text of the current sub-slide.</returns> private string getSubSlide() { string[] temp = texts[order[slideindex]].Split("\n".ToCharArray(), StringSplitOptions.None); string ret = ""; int lps = this.getLinesPerSlide(); for (int x = (lps * subslideindex); x < ((temp.Length < ((lps * subslideindex) + lps)) ? temp.Length : ((lps * subslideindex) + lps)); x++) { try { ret += temp[x]; } catch { ret = temp.Length.ToString() + " " + lps + " " + subslideindex + " " + x.ToString(); x = 100; } } return ret; } /// <summary> /// Attempt to move to the next slide, unless the current slide is the final one in the set. /// </summary> /// <returns>Whether the attempted increment was successful.</returns> public bool incrementVerse() { showchorus = false; if (slideindex + 1 > order.Length - 1) return false; slideindex++; subslideindex = 0; return true; } /// <summary> /// Attempt to move to the previous slide, unless the current slide is the first one in the set. /// </summary> /// <returns>Whether the attemped decrement was successful.</returns> public bool decrementVerse() { showchorus = false; if (slideindex - 1 < 0) return false; slideindex--; subslideindex = 0; return true; } /// <summary> /// Attempt to move to the next sub-slide, unless the current sub-slide is the last one in the set. /// </summary> /// <returns>Whether the attemped increment was successful.</returns> private bool incrementSubSlide() { if (subslideindex < getSubSlideCount() - 1) { subslideindex++; return true; } return false; } /// <summary> /// Attempt to move to the previous sub-slide, unless the current sub-slide is the first one /// in the set. /// </summary> /// <returns>Whether the attemped decrement was successful.</returns> private bool decrementSubSlide() { if (subslideindex > 0) { subslideindex--; return true; } return false; } /// <summary> /// Based on the lines of text on the current slide and the set's number of lines per slide, /// calculate the number of subslides in the current slide. /// </summary> /// <returns>The number of sub-slides in the current slide.</returns> private int getSubSlideCount() { if (blank) return 0; int lines = 1; for (int x = 0; x < texts[order[slideindex]].Length; x++) { if(texts[order[slideindex]][x]=='\n') lines++; } return (int)System.Math.Ceiling(((decimal)lines / this.getLinesPerSlide())); } private int getLinesPerSlide() { return (locallinesperslide[order[slideindex]] == 0 ? linesperslide : locallinesperslide[order[slideindex]]); } } }
using System; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using ITGlobal.CommandLine; using ITGlobal.CommandLine.Parsing; using Serilog; using Serilog.Events; namespace ITGlobal.MarkDocs.Tools { public static class Program { public static string Version => typeof(Program) .GetTypeInfo() .Assembly .GetCustomAttribute<AssemblyInformationalVersionAttribute>() .InformationalVersion; public static int Main(string[] args) { var parser = CliParser.NewTreeParser(); parser.ExecutableName("markdocs"); parser.HelpText("Markdocs command line tool"); parser.SuppressLogo(); var cacheDir = parser.Option("cache").HelpText("Path to cache directory"); var verbosity = parser.RepeatableSwitch('v', "verbose").HelpText("Enable verbose output"); var quiet = parser.Switch('q', "quiet").HelpText("Enable quiet output"); var version = parser.Switch("version").HelpText("Display version number"); parser.BeforeExecute(ctx => { if (version) { Console.Out.WriteLine(Version); ctx.Break(); } SetupLogger(verbosity, quiet); }); LintCommand.Setup(parser, cacheDir, quiet); BuildCommand.Setup(parser, cacheDir, quiet); ServeCommand.Setup(parser, cacheDir, verbosity, quiet); return TerminalErrorHandler.Handle(() => parser.Parse(args).Run()); } public static string DetectTempDir(string tempPath, string source = null, string suffix = null) { string path; if (!string.IsNullOrWhiteSpace(tempPath)) { path = Path.GetFullPath(tempPath); if (path != tempPath) { Log.Debug("Cache path \"{Path}\" resolved to \"{FullPath}\"", tempPath, path); } } else { path = Path.Combine(Path.GetTempPath(), "markdocs"); if (!string.IsNullOrWhiteSpace(suffix)) { path = Path.Combine(path, suffix); } if (!string.IsNullOrWhiteSpace(source)) { string hash; using (var md5 = MD5.Create()) { hash = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(source))) .Replace("-", "") .ToLowerInvariant(); } path = Path.Combine(path, hash); } Log.Warning("Auto-detected cache path \"{Path}\"", path); } Directory.CreateDirectory(path); return path; } public static void PrintReport(ICompilationReport report, bool summary = false, bool quiet = false) { if (quiet) { foreach (var (filename, list) in report.Messages) { foreach (var error in list) { Console.Error.Write(filename); if (error.LineNumber != null) { Console.Error.Write($":{error.LineNumber.Value + 1}"); } Console.Error.Write(": "); switch (error.Type) { case CompilationReportMessageType.Warning: Console.Error.Write("warning: ".Yellow()); break; case CompilationReportMessageType.Error: Console.Error.Write("error: ".Red()); break; default: Console.Error.Write($"{error.Type:G}: ".Magenta()); break; } Console.Error.WriteLine(error.Message); } } return; } Console.Error.WriteLine(); Console.Error.WriteLine("Compilation report".Cyan()); Console.Error.WriteLine("==================".DarkCyan()); Console.Error.WriteLine(); if (report.Messages.Count == 0) { Console.Error.WriteLine("Everything is OK".Green()); } else { foreach (var (filename, list) in report.Messages) { Console.Error.WriteLine($"* ./{filename}".White()); foreach (var error in list) { Console.Error.Write(" "); if (error.LineNumber != null) { Console.Error.Write($"(at {error.LineNumber.Value + 1}) ".DarkGray()); } switch (error.Type) { case CompilationReportMessageType.Warning: Console.Error.Write("WARNING: ".Yellow()); break; case CompilationReportMessageType.Error: Console.Error.Write("ERROR: ".Red()); break; default: Console.Error.Write($"{error.Type:G}: ".Magenta()); break; } Console.Error.WriteLine(error.Message); } } } Console.Error.WriteLine(); if (summary) { var errors = report.Messages.Values.Sum(_ => _.Count(x => x.Type == CompilationReportMessageType.Error)); ; var warnings = report.Messages.Values.Sum(_ => _.Count(x => x.Type == CompilationReportMessageType.Warning)); Console.Error.WriteLine("Summary".Yellow()); Console.Error.WriteLine("-------".DarkYellow()); Console.Error.WriteLine($" {errors} error(s)"); Console.Error.WriteLine($" {warnings} warning(s)"); Console.Error.WriteLine(); } } private static void SetupLogger(int verbosity, bool quiet) { const string outputTemplate = "[{Level:u3} {ThreadId}] {Message:lj}{NewLine}{Exception}"; var configuration = new LoggerConfiguration(); configuration.Enrich.FromLogContext(); configuration.Enrich.WithThreadId(); configuration.Filter.ByExcluding(ExcludePredicate); configuration.WriteTo.Console( outputTemplate: outputTemplate, standardErrorFromLevel: LogEventLevel.Verbose ); if (quiet) { configuration.MinimumLevel.Fatal(); } else { switch (verbosity) { case 0: configuration.MinimumLevel.Error(); break; case 1: configuration.MinimumLevel.Information(); break; case 2: configuration.MinimumLevel.Debug(); break; default: configuration.MinimumLevel.Verbose(); break; } } Log.Logger = configuration.CreateLogger(); bool ExcludePredicate(LogEvent e) { if (e.Properties.TryGetValue("SourceContext", out var value) && value is ScalarValue scalarValue && scalarValue.Value is string sourceContext) { if (sourceContext.StartsWith("Microsoft.") || sourceContext.StartsWith("System.")) { return e.Level <= LogEventLevel.Information; } } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // OrderPreservingPipeliningSpoolingTask.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Parallel; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { internal class OrderPreservingPipeliningSpoolingTask<TOutput, TKey> : SpoolingTaskBase { private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks. private readonly QueryOperatorEnumerator<TOutput, TKey> _partition; // The source partition. private readonly bool[] _consumerWaiting; // Whether a consumer is waiting on a particular producer private readonly bool[] _producerWaiting; // Whether a particular producer is waiting on the consumer private readonly bool[] _producerDone; // Whether each producer is done private readonly int _partitionIndex; // Index of the partition owned by this task. private readonly Queue<Pair<TKey, TOutput>>[] _buffers; // The buffer for the results private readonly object _bufferLock; // A lock for the buffer /// <summary> /// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer. /// If false, the producer will make each result available to the consumer immediately after it is /// produced. /// </summary> private readonly bool _autoBuffered; /// <summary> /// The number of elements to accumulate on the producer before copying the elements to the /// producer-consumer buffer. This constant is only used in the AutoBuffered mode. /// /// Experimentally, 16 appears to be sufficient buffer size to compensate for the synchronization /// cost. /// </summary> private const int PRODUCER_BUFFER_AUTO_SIZE = 16; /// <summary> /// Constructor /// </summary> internal OrderPreservingPipeliningSpoolingTask( QueryOperatorEnumerator<TOutput, TKey> partition, QueryTaskGroupState taskGroupState, bool[] consumerWaiting, bool[] producerWaiting, bool[] producerDone, int partitionIndex, Queue<Pair<TKey, TOutput>>[] buffers, object bufferLock, bool autoBuffered) : base(partitionIndex, taskGroupState) { Debug.Assert(partition != null); Debug.Assert(taskGroupState != null); Debug.Assert(consumerWaiting != null); Debug.Assert(producerWaiting != null && producerWaiting.Length == consumerWaiting.Length); Debug.Assert(producerDone != null && producerDone.Length == consumerWaiting.Length); Debug.Assert(buffers != null && buffers.Length == consumerWaiting.Length); Debug.Assert(partitionIndex >= 0 && partitionIndex < consumerWaiting.Length); _partition = partition; _taskGroupState = taskGroupState; _producerDone = producerDone; _consumerWaiting = consumerWaiting; _producerWaiting = producerWaiting; _partitionIndex = partitionIndex; _buffers = buffers; _bufferLock = bufferLock; _autoBuffered = autoBuffered; } /// <summary> /// This method is responsible for enumerating results and enqueuing them to /// the output buffer as appropriate. Each base class implements its own. /// </summary> protected override void SpoolingWork() { TOutput element = default(TOutput)!; TKey key = default(TKey)!; int chunkSize = _autoBuffered ? PRODUCER_BUFFER_AUTO_SIZE : 1; Pair<TKey, TOutput>[] chunk = new Pair<TKey, TOutput>[chunkSize]; var partition = _partition; CancellationToken cancelToken = _taskGroupState.CancellationState.MergedCancellationToken; int lastChunkSize; do { lastChunkSize = 0; while (lastChunkSize < chunkSize && partition.MoveNext(ref element!, ref key)) { chunk[lastChunkSize] = new Pair<TKey, TOutput>(key, element); lastChunkSize++; } if (lastChunkSize == 0) break; lock (_bufferLock) { // Check if the query has been cancelled. if (cancelToken.IsCancellationRequested) { break; } for (int i = 0; i < lastChunkSize; i++) { _buffers[_partitionIndex].Enqueue(chunk[i]); } if (_consumerWaiting[_partitionIndex]) { Monitor.Pulse(_bufferLock); _consumerWaiting[_partitionIndex] = false; } // If the producer buffer is too large, wait. // Note: we already checked for cancellation after acquiring the lock on this producer. // That guarantees that the consumer will eventually wake up the producer. if (_buffers[_partitionIndex].Count >= OrderPreservingPipeliningMergeHelper<TOutput, TKey>.MAX_BUFFER_SIZE) { _producerWaiting[_partitionIndex] = true; Monitor.Wait(_bufferLock); } } } while (lastChunkSize == chunkSize); } /// <summary> /// Creates and begins execution of a new set of spooling tasks. /// </summary> public static void Spool( QueryTaskGroupState groupState, PartitionedStream<TOutput, TKey> partitions, bool[] consumerWaiting, bool[] producerWaiting, bool[] producerDone, Queue<Pair<TKey, TOutput>>[] buffers, object[] bufferLocks, TaskScheduler taskScheduler, bool autoBuffered) { Debug.Assert(groupState != null); Debug.Assert(partitions != null); Debug.Assert(producerDone != null && producerDone.Length == partitions.PartitionCount); Debug.Assert(buffers != null && buffers.Length == partitions.PartitionCount); Debug.Assert(bufferLocks != null); int degreeOfParallelism = partitions.PartitionCount; // Initialize the buffers and buffer locks. for (int i = 0; i < degreeOfParallelism; i++) { buffers[i] = new Queue<Pair<TKey, TOutput>>(OrderPreservingPipeliningMergeHelper<TOutput, TKey>.INITIAL_BUFFER_SIZE); bufferLocks[i] = new object(); } // Ensure all tasks in this query are parented under a common root. Because this // is a pipelined query, we detach it from the parent (to avoid blocking the calling // thread), and run the query on a separate thread. Task rootTask = new Task( () => { for (int i = 0; i < degreeOfParallelism; i++) { QueryTask asyncTask = new OrderPreservingPipeliningSpoolingTask<TOutput, TKey>( partitions[i], groupState, consumerWaiting, producerWaiting, producerDone, i, buffers, bufferLocks[i], autoBuffered); asyncTask.RunAsynchronously(taskScheduler); } }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // And schedule it for execution. This is done after beginning to ensure no thread tries to // end the query before its root task has been recorded properly. rootTask.Start(taskScheduler); // We don't call QueryEnd here; when we return, the query is still executing, and the // last enumerator to be disposed of will call QueryEnd for us. } /// <summary> /// Dispose the underlying enumerator and wake up the consumer if necessary. /// </summary> protected override void SpoolingFinally() { // Let the consumer know that this producer is done. lock (_bufferLock) { _producerDone[_partitionIndex] = true; if (_consumerWaiting[_partitionIndex]) { Monitor.Pulse(_bufferLock); _consumerWaiting[_partitionIndex] = false; } } // Call the base implementation. base.SpoolingFinally(); // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _partition.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.AspNetCore.SignalR.StackExchangeRedis; using Microsoft.AspNetCore.SignalR.Tests; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using StackExchange.Redis; namespace Microsoft.AspNetCore.SignalR.Microbenchmarks { public class RedisHubLifetimeManagerBenchmark { private RedisHubLifetimeManager<TestHub> _manager1; private RedisHubLifetimeManager<TestHub> _manager2; private TestClient[] _clients; private object[] _args; private readonly List<string> _excludedConnectionIds = new List<string>(); private readonly List<string> _sendIds = new List<string>(); private readonly List<string> _groups = new List<string>(); private readonly List<string> _users = new List<string>(); private const int ClientCount = 20; [Params(2, 20)] public int ProtocolCount { get; set; } // Re-enable micro-benchmark when https://github.com/aspnet/SignalR/issues/3088 is fixed // [GlobalSetup] public void GlobalSetup() { var server = new TestRedisServer(); var logger = NullLogger<RedisHubLifetimeManager<TestHub>>.Instance; var protocols = GenerateProtocols(ProtocolCount).ToArray(); var options = Options.Create(new RedisOptions() { ConnectionFactory = _ => Task.FromResult<IConnectionMultiplexer>(new TestConnectionMultiplexer(server)) }); var resolver = new DefaultHubProtocolResolver(protocols, NullLogger<DefaultHubProtocolResolver>.Instance); _manager1 = new RedisHubLifetimeManager<TestHub>(logger, options, resolver); _manager2 = new RedisHubLifetimeManager<TestHub>(logger, options, resolver); async Task ConnectClient(TestClient client, IHubProtocol protocol, string userId, string groupName) { await _manager2.OnConnectedAsync(HubConnectionContextUtils.Create(client.Connection, protocol, userId)); await _manager2.AddToGroupAsync(client.Connection.ConnectionId, "Everyone"); await _manager2.AddToGroupAsync(client.Connection.ConnectionId, groupName); } // Connect clients _clients = new TestClient[ClientCount]; var tasks = new Task[ClientCount]; for (var i = 0; i < _clients.Length; i++) { var protocol = protocols[i % ProtocolCount]; _clients[i] = new TestClient(protocol: protocol); string group; string user; if ((i % 2) == 0) { group = "Evens"; user = "EvenUser"; _excludedConnectionIds.Add(_clients[i].Connection.ConnectionId); } else { group = "Odds"; user = "OddUser"; _sendIds.Add(_clients[i].Connection.ConnectionId); } tasks[i] = ConnectClient(_clients[i], protocol, user, group); _ = ConsumeAsync(_clients[i]); } Task.WaitAll(tasks); _groups.Add("Evens"); _groups.Add("Odds"); _users.Add("EvenUser"); _users.Add("OddUser"); _args = new object[] { "Foo" }; } private IEnumerable<IHubProtocol> GenerateProtocols(int protocolCount) { for (var i = 0; i < protocolCount; i++) { yield return ((i % 2) == 0) ? new WrappedHubProtocol($"json_{i}", new NewtonsoftJsonHubProtocol()) : new WrappedHubProtocol($"messagepack_{i}", new MessagePackHubProtocol()); } } private async Task ConsumeAsync(TestClient testClient) { while (await testClient.ReadAsync() != null) { // Just dump the message } } //[Benchmark] public async Task SendAll() { await _manager1.SendAllAsync("Test", _args); } //[Benchmark] public async Task SendGroup() { await _manager1.SendGroupAsync("Everyone", "Test", _args); } //[Benchmark] public async Task SendUser() { await _manager1.SendUserAsync("EvenUser", "Test", _args); } //[Benchmark] public async Task SendConnection() { await _manager1.SendConnectionAsync(_clients[0].Connection.ConnectionId, "Test", _args); } //[Benchmark] public async Task SendConnections() { await _manager1.SendConnectionsAsync(_sendIds, "Test", _args); } //[Benchmark] public async Task SendAllExcept() { await _manager1.SendAllExceptAsync("Test", _args, _excludedConnectionIds); } //[Benchmark] public async Task SendGroupExcept() { await _manager1.SendGroupExceptAsync("Everyone", "Test", _args, _excludedConnectionIds); } //[Benchmark] public async Task SendGroups() { await _manager1.SendGroupsAsync(_groups, "Test", _args); } //[Benchmark] public async Task SendUsers() { await _manager1.SendUsersAsync(_users, "Test", _args); } public class TestHub : Hub { } private class WrappedHubProtocol : IHubProtocol { private readonly string _name; private readonly IHubProtocol _innerProtocol; public string Name => _name; public int Version => _innerProtocol.Version; public TransferFormat TransferFormat => _innerProtocol.TransferFormat; public WrappedHubProtocol(string name, IHubProtocol innerProtocol) { _name = name; _innerProtocol = innerProtocol; } public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, out HubMessage message) { return _innerProtocol.TryParseMessage(ref input, binder, out message); } public void WriteMessage(HubMessage message, IBufferWriter<byte> output) { _innerProtocol.WriteMessage(message, output); } public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message) { return HubProtocolExtensions.GetMessageBytes(this, message); } public bool IsVersionSupported(int version) { return _innerProtocol.IsVersionSupported(version); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; namespace System.Net.Security { public enum EncryptionPolicy { // Prohibit null ciphers (current system defaults) RequireEncryption = 0, // Add null ciphers to current system defaults AllowNoEncryption, // Request null ciphers only NoEncryption } // A user delegate used to verify remote SSL certificate. public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); // A user delegate used to select local SSL certificate. public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers); // Internal versions of the above delegates. internal delegate bool RemoteCertValidationCallback(string host, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors); internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2 remoteCertificate, string[] acceptableIssuers); public class SslStream : AuthenticatedStream { private SslState _sslState; private RemoteCertificateValidationCallback _userCertificateValidationCallback; private LocalCertificateSelectionCallback _userCertificateSelectionCallback; private object _remoteCertificateOrBytes; public SslStream(Stream innerStream) : this(innerStream, false, null, null) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen) : this(innerStream, leaveInnerStreamOpen, null, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen) { if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), "encryptionPolicy"); } _userCertificateValidationCallback = userCertificateValidationCallback; _userCertificateSelectionCallback = userCertificateSelectionCallback; RemoteCertValidationCallback _userCertValidationCallbackWrapper = new RemoteCertValidationCallback(UserCertValidationCallbackWrapper); LocalCertSelectionCallback _userCertSelectionCallbackWrapper = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); _sslState = new SslState(innerStream, _userCertValidationCallbackWrapper, _userCertSelectionCallbackWrapper, encryptionPolicy); } private bool UserCertValidationCallbackWrapper(string hostName, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { _remoteCertificateOrBytes = certificate == null ? null : certificate.RawData; if (_userCertificateValidationCallback == null) { if (!_sslState.RemoteCertRequired) { sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNotAvailable; } return (sslPolicyErrors == SslPolicyErrors.None); } else { return _userCertificateValidationCallback(this, certificate, chain, sslPolicyErrors); } } private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return _userCertificateSelectionCallback(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers); } // // Client side auth. // public virtual void AuthenticateAsClient(string targetHost) { AuthenticateAsClient(targetHost, new X509CertificateCollection(), SecurityProtocol.DefaultSecurityProtocols, false); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation); _sslState.ProcessAuthentication(null); } internal virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(targetHost, new X509CertificateCollection(), SecurityProtocol.DefaultSecurityProtocols, false, asyncCallback, asyncState); } internal virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { _sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation); LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback); _sslState.ProcessAuthentication(result); return result; } internal virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) { _sslState.EndProcessAuthentication(asyncResult); } // // Server side auth. // public virtual void AuthenticateAsServer(X509Certificate serverCertificate) { AuthenticateAsServer(serverCertificate, false, SecurityProtocol.DefaultSecurityProtocols, false); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); _sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation); _sslState.ProcessAuthentication(null); } internal virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.DefaultSecurityProtocols, false, asyncCallback, asyncState); } internal virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState) { _sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation); LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback); _sslState.ProcessAuthentication(result); return result; } internal virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) { _sslState.EndProcessAuthentication(asyncResult); } public TransportContext TransportContext { get { return new SslStreamContext(this); } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { return _sslState.GetChannelBinding(kind); } #region Task-based async public methods public virtual Task AuthenticateAsClientAsync(string targetHost) { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, targetHost, null); } public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate) { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, serverCertificate, null); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols); return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsServer, null); } #endregion public override bool IsAuthenticated { get { return _sslState.IsAuthenticated; } } public override bool IsMutuallyAuthenticated { get { return _sslState.IsMutuallyAuthenticated; } } public override bool IsEncrypted { get { return IsAuthenticated; } } public override bool IsSigned { get { return IsAuthenticated; } } public override bool IsServer { get { return _sslState.IsServer; } } public virtual SslProtocols SslProtocol { get { return _sslState.SslProtocol; } } public virtual bool CheckCertRevocationStatus { get { return _sslState.CheckCertRevocationStatus; } } public virtual X509Certificate LocalCertificate { get { return _sslState.LocalCertificate; } } public virtual X509Certificate RemoteCertificate { get { _sslState.CheckThrow(true); object chkCertificateOrBytes = _remoteCertificateOrBytes; if (chkCertificateOrBytes != null && chkCertificateOrBytes.GetType() == typeof(byte[])) { return (X509Certificate)(_remoteCertificateOrBytes = new X509Certificate((byte[])chkCertificateOrBytes)); } else { return chkCertificateOrBytes as X509Certificate; } } } public virtual CipherAlgorithmType CipherAlgorithm { get { return _sslState.CipherAlgorithm; } } public virtual int CipherStrength { get { return _sslState.CipherStrength; } } public virtual HashAlgorithmType HashAlgorithm { get { return _sslState.HashAlgorithm; } } public virtual int HashStrength { get { return _sslState.HashStrength; } } public virtual ExchangeAlgorithmType KeyExchangeAlgorithm { get { return _sslState.KeyExchangeAlgorithm; } } public virtual int KeyExchangeStrength { get { return _sslState.KeyExchangeStrength; } } // // Stream contract implementation. // public override bool CanSeek { get { return false; } } public override bool CanRead { get { return _sslState.IsAuthenticated && InnerStream.CanRead; } } public override bool CanTimeout { get { return InnerStream.CanTimeout; } } public override bool CanWrite { get { return _sslState.IsAuthenticated && InnerStream.CanWrite; } } public override int ReadTimeout { get { return InnerStream.ReadTimeout; } set { InnerStream.ReadTimeout = value; } } public override int WriteTimeout { get { return InnerStream.WriteTimeout; } set { InnerStream.WriteTimeout = value; } } public override long Length { get { return InnerStream.Length; } } public override long Position { get { return InnerStream.Position; } set { throw new NotSupportedException(SR.net_noseek); } } public override void SetLength(long value) { InnerStream.SetLength(value); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } public override void Flush() { _sslState.Flush(); } protected override void Dispose(bool disposing) { try { _sslState.Close(); } finally { base.Dispose(disposing); } } public override int Read(byte[] buffer, int offset, int count) { return _sslState.SecureStream.Read(buffer, offset, count); } public void Write(byte[] buffer) { _sslState.SecureStream.Write(buffer, 0, buffer.Length); } public override void Write(byte[] buffer, int offset, int count) { _sslState.SecureStream.Write(buffer, offset, count); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Baseline.Dates; using Jasper.Logging; using Jasper.Persistence.Durability; using Jasper.Persistence.Testing.Marten; using Jasper.Tcp; using Jasper.Tracking; using Jasper.Util; using Microsoft.Extensions.Hosting; using Shouldly; using TestingSupport; using Xunit; namespace Jasper.Persistence.Testing { public abstract class DurableFixture<TTriggerHandler, TItemCreatedHandler> : IAsyncLifetime { private IHost theReceiver; private IHost theSender; public async Task InitializeAsync() { var receiverPort = PortFinder.GetAvailablePort(); var senderPort = PortFinder.GetAvailablePort(); var senderRegistry = new JasperOptions(); senderRegistry.Handlers .DisableConventionalDiscovery() .IncludeType<CascadeReceiver>() .IncludeType<ScheduledMessageHandler>(); senderRegistry.Extensions.UseMessageTrackingTestingSupport(); senderRegistry.Endpoints.Publish(x => { x.Message<TriggerMessage>(); x.Message<ItemCreated>(); x.Message<Question>(); x.Message<ScheduledMessage>(); x.ToPort(receiverPort).Durably(); }); senderRegistry.Endpoints.ListenAtPort(senderPort).DurablyPersistedLocally(); configureSender(senderRegistry); theSender = JasperHost.For(senderRegistry); await theSender.RebuildMessageStorage(); var receiverRegistry = new JasperOptions(); receiverRegistry.Extensions.UseMessageTrackingTestingSupport(); receiverRegistry.Handlers.DisableConventionalDiscovery() .IncludeType<TTriggerHandler>() .IncludeType<TItemCreatedHandler>() .IncludeType<QuestionHandler>() .IncludeType<ScheduledMessageHandler>(); receiverRegistry.Endpoints.ListenAtPort(receiverPort).DurablyPersistedLocally(); receiverRegistry.Extensions.UseMessageTrackingTestingSupport(); configureReceiver(receiverRegistry); theReceiver = JasperHost.For(receiverRegistry); await theReceiver.RebuildMessageStorage(); await initializeStorage(theSender, theReceiver); } public Task DisposeAsync() { theSender?.Dispose(); theReceiver?.Dispose(); return Task.CompletedTask; } private async Task cleanDatabase() { await initializeStorage(theSender, theReceiver); ScheduledMessageHandler.Reset(); } protected virtual async Task initializeStorage(IHost sender, IHost receiver) { await theSender.RebuildMessageStorage(); await theReceiver.RebuildMessageStorage(); } protected abstract void configureReceiver(JasperOptions receiverOptions); protected abstract void configureSender(JasperOptions senderOptions); [Fact] public async Task can_send_message_end_to_end() { await cleanDatabase(); var trigger = new TriggerMessage {Name = Guid.NewGuid().ToString()}; await theSender .TrackActivity() .AlsoTrack(theReceiver) .WaitForMessageToBeReceivedAt<CascadedMessage>(theSender) .SendMessageAndWait(trigger); } protected abstract ItemCreated loadItem(IHost receiver, Guid id); protected abstract Task withContext(IHost sender, IExecutionContext context, Func<IExecutionContext, Task> action); private Task send(Func<IExecutionContext, Task> action) { return withContext(theSender, theSender.Get<IExecutionContext>(), action); } [Fact] public async Task can_send_items_durably_through_persisted_channels() { await cleanDatabase(); var item = new ItemCreated { Name = "Shoe", Id = Guid.NewGuid() }; await theSender.TrackActivity().AlsoTrack(theReceiver).SendMessageAndWait(item); await Task.Delay(500.Milliseconds()); await assertReceivedItemMatchesSent(item); await assertIncomingEnvelopesIsZero(); var senderCounts = await assertNoPersistedOutgoingEnvelopes(); senderCounts.Outgoing.ShouldBe(0, "There are still persisted, outgoing messages"); } private async Task<PersistedCounts> assertNoPersistedOutgoingEnvelopes() { var senderCounts = await theSender.Get<IEnvelopePersistence>().Admin.GetPersistedCounts(); if (senderCounts.Outgoing > 0) { await Task.Delay(500.Milliseconds()); senderCounts = await theSender.Get<IEnvelopePersistence>().Admin.GetPersistedCounts(); } return senderCounts; } private async Task assertReceivedItemMatchesSent(ItemCreated item) { var received = loadItem(theReceiver, item.Id); if (received == null) await Task.Delay(500.Milliseconds()); received = loadItem(theReceiver, item.Id); received.Name.ShouldBe(item.Name, "The persisted item does not match"); } private async Task assertIncomingEnvelopesIsZero() { var receiverCounts = await theReceiver.Get<IEnvelopePersistence>().Admin.GetPersistedCounts(); if (receiverCounts.Incoming > 0) { await Task.Delay(500.Milliseconds()); receiverCounts = await theReceiver.Get<IEnvelopePersistence>().Admin.GetPersistedCounts(); } receiverCounts.Incoming.ShouldBe(0, "There are still persisted, incoming messages"); } [Fact] public async Task can_schedule_job_durably() { await cleanDatabase(); var item = new ItemCreated { Name = "Shoe", Id = Guid.NewGuid() }; await send(async c => { await c.Schedule(item, 1.Hours()); }); var persistor = theSender.Get<IEnvelopePersistence>(); var counts = await persistor.Admin.GetPersistedCounts(); counts.Scheduled.ShouldBe(1, $"counts.Scheduled = {counts.Scheduled}, should be 1"); } protected abstract IReadOnlyList<Envelope> loadAllOutgoingEnvelopes(IHost sender); [Fact] public async Task<bool> send_scheduled_message() { await cleanDatabase(); var message1 = new ScheduledMessage {Id = 1}; var message2 = new ScheduledMessage {Id = 22}; var message3 = new ScheduledMessage {Id = 3}; await send(async c => { await c.ScheduleSend(message1, 2.Hours()); await c.ScheduleSend(message2, 5.Seconds()); await c.ScheduleSend(message3, 2.Hours()); }); ScheduledMessageHandler.ReceivedMessages.Count.ShouldBe(0); await ScheduledMessageHandler.Received; ScheduledMessageHandler.ReceivedMessages.Single() .Id.ShouldBe(22); return true; } [Fact] public async Task<bool> schedule_job_locally() { await cleanDatabase(); var message1 = new ScheduledMessage {Id = 1}; var message2 = new ScheduledMessage {Id = 2}; var message3 = new ScheduledMessage {Id = 3}; await send(async c => { await c.Schedule(message1, 2.Hours()); await c.Schedule(message2, 5.Seconds()); await c.Schedule(message3, 2.Hours()); }); ScheduledMessageHandler.ReceivedMessages.Count.ShouldBe(0); await ScheduledMessageHandler.Received; ScheduledMessageHandler.ReceivedMessages.Single() .Id.ShouldBe(2); return true; } [Fact] public async Task<bool> can_send_durably_with_receiver_down() { await cleanDatabase(); // Shutting it down theReceiver.Dispose(); theReceiver = null; var item = new ItemCreated { Name = "Shoe", Id = Guid.NewGuid() }; await send(c => c.Send(item)); var outgoing = loadAllOutgoingEnvelopes(theSender).SingleOrDefault(); outgoing.ShouldNotBeNull("No outgoing envelopes are persisted"); outgoing.MessageType.ShouldBe(typeof(ItemCreated).ToMessageTypeName(), $"Envelope message type expected {typeof(ItemCreated).ToMessageTypeName()}, but was {outgoing.MessageType}"); return true; } } public class TriggerMessage { public string Name { get; set; } } public class CascadedMessage { public string Name { get; set; } } public class CascadeReceiver { public void Handle(CascadedMessage message) { } } public class ItemCreated { public Guid Id; public string Name; } public class QuestionHandler { public Answer Handle(Question question) { return new Answer { Sum = question.X + question.Y, Product = question.X * question.Y }; } } public class Question { public int X; public int Y; } public class Answer { public int Product; public int Sum; } public class ScheduledMessage { public int Id { get; set; } } public class ScheduledMessageHandler { public static readonly IList<ScheduledMessage> ReceivedMessages = new List<ScheduledMessage>(); private static TaskCompletionSource<ScheduledMessage> _source; public static Task<ScheduledMessage> Received { get; private set; } public void Consume(ScheduledMessage message) { ReceivedMessages.Add(message); _source?.TrySetResult(message); } public static void Reset() { _source = new TaskCompletionSource<ScheduledMessage>(); Received = _source.Task; ReceivedMessages.Clear(); } } }
namespace Microsoft.Protocols.TestSuites.MS_ASCMD { using System; using System.Globalization; using System.Xml; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using Request = Microsoft.Protocols.TestSuites.Common.Request; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// This scenario is designed to test the Autodiscover command. /// </summary> [TestClass] public class S01_Autodiscover : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case is used to verify if the Type element value is set to 'MobileSync', the Name element should be returned. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S01_TC01_Autodiscover_TypeIsMobileSync() { Site.Assume.IsFalse(Common.GetSutVersion(this.Site) == SutVersion.ExchangeServer2007 && string.Equals(Common.GetConfigurationPropertyValue("TransportType", this.Site).ToUpper(CultureInfo.InvariantCulture), "HTTP"), "Autodiscover request should be passed only through HTTPS to Exchange Server 2007."); string acceptableResponseSchema = Common.GetConfigurationPropertyValue("AcceptableResponseSchema", Site); AutodiscoverRequest request = new AutodiscoverRequest { RequestData = new Request.Autodiscover { Request = new Request.RequestType { AcceptableResponseSchema = acceptableResponseSchema, EMailAddress = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain) } } }; AutodiscoverResponse response = CMDAdapter.Autodiscover(request, ContentTypeEnum.Xml); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(response.ResponseDataXML); XmlElement xmlElement = (XmlElement)xmlDoc.DocumentElement; string schemaNameSpace = xmlElement.GetElementsByTagName("Response")[0].NamespaceURI; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R703"); Site.CaptureRequirementIfAreEqual<string>( acceptableResponseSchema, schemaNameSpace, 703, @"[In AcceptableResponseSchema] The AcceptableResponseSchema element is a required child element of the Request element in Autodiscover command requests that indicates the schema in which the server MUST send the response."); Site.Assert.AreEqual<string>("MobileSync", ((Response.Response)response.ResponseData.Item).Action.Settings[0].Type, "The type of Action in Autodiscover command response should be MobileSync."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3482"); // If the Type element value is "MobileSync", then the Name element specifies the URL that conveys the protocol which specified by Url element. // Verify MS-ASCMD requirement: MS-ASCMD_R3482 Site.CaptureRequirementIfAreEqual<string>( ((Response.Response)response.ResponseData.Item).Action.Settings[0].Url, ((Response.Response)response.ResponseData.Item).Action.Settings[0].Name, 3482, @"[In Name(Autodiscover)] The Name element is an optional child element of the Server element in Autodiscover command responses that specifies a URL if the Type element (section 2.2.3.170.1) value is set to ""MobileSync""."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3484"); // If the Type element value is "MobileSync", then the Name element specifies the URL that conveys the protocol which specified by Url element. // Verify MS-ASCMD requirement: MS-ASCMD_R3484 Site.CaptureRequirementIfAreEqual<string>( ((Response.Response)response.ResponseData.Item).Action.Settings[0].Url, ((Response.Response)response.ResponseData.Item).Action.Settings[0].Name, 3484, @"[In Name(Autodiscover)] If the Type element value is ""MobileSync"", then the Name element specifies the URL that conveys the protocol."); if (Common.IsRequirementEnabled(5160, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5160"); // Verify MS-ASCMD requirement: MS-ASCMD_R5160 Site.CaptureRequirementIfAreEqual<string>( "en:en", ((Response.Response)response.ResponseData.Item).Culture, 5160, "[In Appendix A: Product Behavior] Implementation does return the form \"en:en\" of Culture element, regardless of the culture that is sent by the client. (<26> Section 2.2.3.38: In Exchange 2007, the Culture element always returns \"en:en\", regardless of the culture that is sent by the client.)"); } if (Common.IsRequirementEnabled(5823, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5823"); // Verify MS-ASCMD requirement: MS-ASCMD_R5823 Site.CaptureRequirementIfAreEqual<string>( "en:us", ((Response.Response)response.ResponseData.Item).Culture, 5823, "[In Appendix A: Product Behavior] Implementation does return the form \"en:us\" of Culture element. (Exchange 2010 and above follow this behavior.)"); } if (Common.IsRequirementEnabled(5718, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5718"); // If the Response element do not have an Error child element when set the Content-Type header to "text/xml", it indicates an error does not occur in the Autodiscover command framework that hosts the Autodiscovery implementation. // Verify MS-ASCMD requirement: MS-ASCMD_R5718 Site.CaptureRequirementIfIsNull( ((Response.Response)response.ResponseData.Item).Action.Error, 5718, "[In Appendix A: Product Behavior] When sending an Autodiscover command request to implementation, the Content-Type header does accept the following values: \"text/xml\". (Exchange 2007 and above follow this behavior.)"); } if (Common.IsRequirementEnabled(5123, this.Site)) { response = CMDAdapter.Autodiscover(request, ContentTypeEnum.Html); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5123"); // If the Response element do not have an Error child element when set the Content-Type header to "text/html", it indicates an error does not occur in the Autodiscover command framework that hosts the Autodiscovery implementation. // Verify MS-ASCMD requirement: MS-ASCMD_R5123 Site.CaptureRequirementIfIsNull( ((Response.Response)response.ResponseData.Item).Action.Error, 5123, "[In Appendix A: Product Behavior] When sending an Autodiscover command request to implementation, the Content-Type header does accept the following values: \"text/html\" [or \"text/xml\"]. (<1> Section 2.2.2.1: When sending an Autodiscover command request to Exchange 2007, the Content-Type header accepts the following values: \"text/html\" or \"text/xml\".)"); } } /// <summary> /// This test case is used to verify if Autodiscover failed, the server should return an error child element. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S01_TC02_Autodiscover_Fail() { Site.Assume.IsFalse(Common.GetSutVersion(this.Site) == SutVersion.ExchangeServer2007 && string.Equals(Common.GetConfigurationPropertyValue("TransportType", this.Site).ToUpper(CultureInfo.InvariantCulture), "HTTP"), "Autodiscover request should be passed only through HTTPS to Exchange Server 2007."); AutodiscoverRequest request = new AutodiscoverRequest { RequestData = new Request.Autodiscover { Request = new Request.RequestType { AcceptableResponseSchema = Common.GetConfigurationPropertyValue("AcceptableResponseSchema", this.Site), EMailAddress = Common.GetMailAddress("InvallidEmailAddress", this.User1Information.UserDomain) } } }; AutodiscoverResponse response = CMDAdapter.Autodiscover(request, ContentTypeEnum.Xml); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3818"); // An Error child element returned in Response element indicate an error occurs in the Autodiscover command framework that hosts the Autodiscovery implementation. // Verify MS-ASCMD requirement: MS-ASCMD_R3818 Site.CaptureRequirementIfIsNotNull( ((Response.Response)response.ResponseData.Item).Action.Error, 3818, @"[In Response(Autodiscover)] If an error occurs in the Autodiscover command framework that hosts the Autodiscovery implementation, then the Response element MUST have an Error child element."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4001"); // Verify MS-ASCMD requirement: MS-ASCMD_R4001 Site.CaptureRequirementIfAreNotEqual<string>( "1", ((Response.Response)response.ResponseData.Item).Action.Error.Status, 4001, @"[In Status(Autodiscover)] Because the Status element is only returned when the command encounters an error, the success status code is never included in a response message."); } /// <summary> /// This test case is used to verify the server returns 600, when more than one Request elements are present in an Autodiscover command request. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S01_TC03_ErrorCode_600() { Site.Assume.IsFalse(Common.GetSutVersion(this.Site) == SutVersion.ExchangeServer2007 && string.Equals(Common.GetConfigurationPropertyValue("TransportType", this.Site).ToUpper(CultureInfo.InvariantCulture), "HTTP"), "Autodiscover request should be passed only through HTTPS to Exchange Server 2007."); #region Calls Autodiscover command with two Request elements. AutodiscoverRequest request = new AutodiscoverRequest { RequestData = new Request.Autodiscover { Request = new Request.RequestType { AcceptableResponseSchema = Common.GetConfigurationPropertyValue("AcceptableResponseSchema", Site), EMailAddress = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain) } } }; string requestText = request.GetRequestDataSerializedXML(); int requestStartPosition = requestText.IndexOf("<Request>", StringComparison.OrdinalIgnoreCase); int requestEndPosition = requestText.IndexOf("</Autodiscover>", StringComparison.OrdinalIgnoreCase) - 1; string requestElementString = requestText.Substring(requestStartPosition, requestEndPosition - requestStartPosition + 1); requestText = requestText.Insert(requestEndPosition + 1, requestElementString); SendStringResponse response = this.CMDAdapter.SendStringRequest(CommandName.Autodiscover, null, requestText); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(response.ResponseDataXML); XmlElement xmlElement = (XmlElement)xmlDoc.DocumentElement; string errorCode = xmlElement.GetElementsByTagName("ErrorCode")[0].InnerText; // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3799"); Site.CaptureRequirementIfAreEqual<string>( "600", errorCode, 3799, @"[In Request(Autodiscover)] When more than one Request elements are present in an Autodiscover command request, the server returns an ErrorCode (section 2.2.3.61) value of 600."); // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2286"); // Send more than one request means the schema doesn't match the one that AcceptableResponseSchema element provides, // So R2286 can be captured. Site.CaptureRequirementIfAreEqual<string>( "600", errorCode, 2286, @"[In ErrorCode] [If the provider cannot be found, or ]if the AcceptableResponseSchema element (section 2.2.3.1) value cannot be matched, then the ErrorCode element is included in the command response."); // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2287"); Site.CaptureRequirementIfAreEqual<string>( "600", errorCode, 2287, @"[In ErrorCode] A value of 600 means an invalid request was sent to the server."); #endregion } /// <summary> /// This test case is used to verify the server returns 601, when more than one Request elements are present in an Autodiscover command request. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S01_TC04_ErrorCode_601() { Site.Assume.IsFalse(Common.GetSutVersion(this.Site) == SutVersion.ExchangeServer2007 && string.Equals(Common.GetConfigurationPropertyValue("TransportType", this.Site).ToUpper(CultureInfo.InvariantCulture), "HTTP"), "Autodiscover request should be passed only through HTTPS to Exchange Server 2007."); #region Calls Autodiscover command with two Request elements. AutodiscoverRequest request = new AutodiscoverRequest { RequestData = new Request.Autodiscover { Request = new Request.RequestType { AcceptableResponseSchema = Common.GetConfigurationPropertyValue("AcceptableResponseSchema", Site) + "XX", EMailAddress = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain) } } }; AutodiscoverResponse response = this.CMDAdapter.Autodiscover(request, ContentTypeEnum.Xml); // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2285"); Site.CaptureRequirementIfAreEqual<string>( "601", ((Response.AutodiscoverResponse)response.ResponseData.Item).Error.ErrorCode, 2285, @"[In ErrorCode] If the provider cannot be found, [or if the AcceptableResponseSchema element (section 2.2.3.1) value cannot be matched,] then the ErrorCode element is included in the command response."); // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R2288"); Site.CaptureRequirementIfAreEqual<string>( "601", ((Response.AutodiscoverResponse)response.ResponseData.Item).Error.ErrorCode, 2288, @"[In ErrorCode] A value of 601 means that a provider could not be found to handle the AcceptableResponseSchema element value that was specified."); #endregion } #endregion } }
#pragma warning disable 109, 114, 219, 429, 168, 162 public class ValueType : global::haxe.lang.Enum { static ValueType() { #line 50 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::ValueType.constructs = new global::Array<object>(new object[]{"TNull", "TInt", "TFloat", "TBool", "TObject", "TFunction", "TClass", "TEnum", "TUnknown"}); global::ValueType.TNull = new global::ValueType(((int) (0) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{})) ))) )); global::ValueType.TInt = new global::ValueType(((int) (1) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{})) ))) )); global::ValueType.TFloat = new global::ValueType(((int) (2) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{})) ))) )); global::ValueType.TBool = new global::ValueType(((int) (3) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{})) ))) )); global::ValueType.TObject = new global::ValueType(((int) (4) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{})) ))) )); global::ValueType.TFunction = new global::ValueType(((int) (5) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{})) ))) )); #line 59 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::ValueType.TUnknown = new global::ValueType(((int) (8) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{})) ))) )); } public ValueType(global::haxe.lang.EmptyObject empty) : base(global::haxe.lang.EmptyObject.EMPTY) { unchecked { } #line default } public ValueType(int index, global::Array<object> @params) : base(index, @params) { unchecked { } #line default } public static global::Array<object> constructs; public static global::ValueType TNull; public static global::ValueType TInt; public static global::ValueType TFloat; public static global::ValueType TBool; public static global::ValueType TObject; public static global::ValueType TFunction; public static global::ValueType TClass(global::System.Type c) { unchecked { #line 57 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return new global::ValueType(((int) (6) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{c})) ))) )); } #line default } public static global::ValueType TEnum(global::System.Type e) { unchecked { #line 58 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return new global::ValueType(((int) (7) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (new global::Array<object>(new object[]{e})) ))) )); } #line default } public static global::ValueType TUnknown; public static new object __hx_createEmpty() { unchecked { #line 50 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return new global::ValueType(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 50 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return new global::ValueType(((int) (global::haxe.lang.Runtime.toInt(arr[0])) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (arr[1]) ))) )); } #line default } } #pragma warning disable 109, 114, 219, 429, 168, 162 public class Type : global::haxe.lang.HxObject { public Type(global::haxe.lang.EmptyObject empty) { unchecked { #line 62 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" { } } #line default } public Type() { unchecked { #line 62 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::Type.__hx_ctor__Type(this); } #line default } public static void __hx_ctor__Type(global::Type __temp_me15) { unchecked { #line 62 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" { } } #line default } public static global::System.Type getClass<T>(T o) { if (o == null || o is haxe.lang.DynamicObject || o is System.Type) return null; return o.GetType(); } public static global::System.Type getEnum(object o) { if (o is System.Enum || o is haxe.lang.Enum) return o.GetType(); return null; } public static global::System.Type getSuperClass(global::System.Type c) { unchecked { #line 87 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::System.Type t = ((global::System.Type) (c) ); global::System.Type @base = t.BaseType; if (( ( global::haxe.lang.Runtime.typeEq(@base, default(global::System.Type)) || string.Equals(global::haxe.lang.Runtime.concat(global::Std.@string(@base), ""), "haxe.lang.HxObject") ) || string.Equals(global::haxe.lang.Runtime.concat(global::Std.@string(@base), ""), "System.Object") )) { #line 91 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return default(global::System.Type); } #line 94 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return ((global::System.Type) (@base) ); } #line default } public static string getClassName(global::System.Type c) { unchecked { #line 98 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" string ret = global::haxe.lang.Runtime.toString(((global::System.Type) (c) )); #line 104 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" switch (ret) { case "System.Int32": { #line 106 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return "Int"; } case "System.Double": { return "Float"; } case "System.String": { return "String"; } case "System.Object": { return "Dynamic"; } case "System.Type": { return "Class"; } default: { return global::haxe.lang.Runtime.toString(global::haxe.lang.StringExt.split(ret, "`")[0]); } } } #line default } public static string getEnumName(global::System.Type e) { unchecked { #line 117 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" string ret = global::haxe.lang.Runtime.toString(((global::System.Type) (e) )); #line 122 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" if (( ( ret.Length == 14 ) && string.Equals(ret, "System.Boolean") )) { return "Bool"; } return ret; } #line default } public static global::System.Type resolveClass(string name) { unchecked { #line 133 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::System.Type t = global::System.Type.GetType(global::haxe.lang.Runtime.toString(name)); if (global::haxe.lang.Runtime.typeEq(t, default(global::System.Type))) { #line 136 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" switch (name) { case "Int": { #line 138 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return ((global::System.Type) (typeof(int)) ); } case "Float": { return ((global::System.Type) (typeof(double)) ); } case "Class": { return ((global::System.Type) (typeof(global::System.Type)) ); } case "Dynamic": { return ((global::System.Type) (typeof(object)) ); } case "String": { return ((global::System.Type) (typeof(string)) ); } default: { return default(global::System.Type); } } } else { #line 145 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" if (( t.IsInterface && (((global::System.Type) (typeof(global::haxe.lang.IGenericObject)) )).IsAssignableFrom(((global::System.Type) (t) )) )) { t = default(global::System.Type); int i = 0; string ts = ""; while (( global::haxe.lang.Runtime.typeEq(t, default(global::System.Type)) && ( i < 18 ) )) { #line 151 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" i++; ts = global::haxe.lang.Runtime.concat(ts, global::haxe.lang.Runtime.concat((( (( i == 1 )) ? ("") : (",") )), "System.Object")); t = global::System.Type.GetType(global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(name, "`"), global::haxe.lang.Runtime.toString(i)), "["), ts), "]"))); } #line 156 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return ((global::System.Type) (t) ); } else { #line 158 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return ((global::System.Type) (t) ); } } } #line default } public static global::System.Type resolveEnum(string name) { if (name == "Bool") return typeof(bool); System.Type t = resolveClass(name); if (t != null && (t.BaseType.Equals(typeof(System.Enum)) || t.BaseType.Equals(typeof(haxe.lang.Enum)))) return t; return null; } public static T createInstance<T>(global::System.Type cl, global::Array args) { unchecked { #line 177 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" if (global::haxe.lang.Runtime.refEq(cl, typeof(string))) { return global::haxe.lang.Runtime.genericCast<T>(args[0]); } global::System.Type t = ((global::System.Type) (cl) ); if (t.IsInterface) { #line 183 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::System.Type cl1 = global::Type.resolveClass(global::Type.getClassName(cl)); #line 183 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" t = cl1; } #line 185 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::System.Reflection.ConstructorInfo[] ctors = t.GetConstructors(); return global::haxe.lang.Runtime.genericCast<T>(global::haxe.lang.Runtime.callMethod(default(object), ((global::System.Reflection.MethodBase[]) (ctors) ), ( ctors as global::System.Array ).Length, args)); } #line default } public static T createEmptyInstance<T>(global::System.Type cl) { unchecked { #line 191 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::System.Type t = ((global::System.Type) (cl) ); if (t.IsInterface) { #line 195 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::System.Type cl1 = global::Type.resolveClass(global::Type.getClassName(cl)); #line 195 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" t = cl1; } #line 198 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" if (global::Reflect.hasField(cl, "__hx_createEmpty")) { return global::haxe.lang.Runtime.genericCast<T>(global::haxe.lang.Runtime.callField(cl, "__hx_createEmpty", 2084789794, default(global::Array))); } return global::Type.createInstance<T>(cl, new global::Array<object>(new object[]{})); } #line default } public static T createEnum<T>(global::System.Type e, string constr, global::Array @params) { if (@params == null || @params[0] == null) { object ret = haxe.lang.Runtime.slowGetField(e, constr, true); if (ret is haxe.lang.Function) throw haxe.lang.HaxeException.wrap("Constructor " + constr + " needs parameters"); return (T) ret; } else { return (T) haxe.lang.Runtime.slowCallField(e, constr, @params); } } public static T createEnumIndex<T>(global::System.Type e, int index, global::Array @params) { unchecked { #line 220 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::Array<object> constr = global::Type.getEnumConstructs(e); return global::Type.createEnum<T>(e, global::haxe.lang.Runtime.toString(constr[index]), @params); } #line default } public static global::Array<object> getInstanceFields(global::System.Type c) { if (c == typeof(string)) { return haxe.lang.StringRefl.fields; } Array<object> ret = new Array<object>(); System.Reflection.MemberInfo[] mis = c.GetMembers(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy); for (int i = 0; i < mis.Length; i++) { if (mis[i] is System.Reflection.PropertyInfo) continue; string n = mis[i].Name; if (!n.StartsWith("__hx_") && n[0] != '.' && !n.Equals("Equals") && !n.Equals("ToString") && !n.Equals("GetHashCode") && !n.Equals("GetType")) ret.push(mis[i].Name); } return ret; } public static global::Array<object> getClassFields(global::System.Type c) { Array<object> ret = new Array<object>(); if (c == typeof(string)) { ret.push("fromCharCode"); return ret; } System.Reflection.MemberInfo[] mis = c.GetMembers(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); for (int i = 0; i < mis.Length; i++) { string n = mis[i].Name; if (!n.StartsWith("__hx_")) ret.push(mis[i].Name); } return ret; } public static global::Array<object> getEnumConstructs(global::System.Type e) { unchecked { #line 272 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" if (global::Reflect.hasField(e, "constructs")) { return ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (global::haxe.lang.Runtime.callField(global::haxe.lang.Runtime.getField(e, "constructs", 1744813180, true), "copy", 1103412149, default(global::Array))) ))) ); } return new Array<object>(System.Enum.GetNames(e)); } #line default } public static global::ValueType @typeof(object v) { if (v == null) return ValueType.TNull; System.Type t = v as System.Type; if (t != null) { //class type return ValueType.TObject; } t = v.GetType(); if (t.IsEnum) return ValueType.TEnum(t); if (t.IsValueType) { System.IConvertible vc = v as System.IConvertible; if (vc != null) { switch (vc.GetTypeCode()) { case System.TypeCode.Boolean: return ValueType.TBool; case System.TypeCode.Double: double d = vc.ToDouble(null); if (d >= int.MinValue && d <= int.MaxValue && d == vc.ToInt32(null)) return ValueType.TInt; else return ValueType.TFloat; case System.TypeCode.Int32: return ValueType.TInt; default: return ValueType.TClass(t); } } else { return ValueType.TClass(t); } } if (v is haxe.lang.IHxObject) { if (v is haxe.lang.DynamicObject) return ValueType.TObject; else if (v is haxe.lang.Enum) return ValueType.TEnum(t); return ValueType.TClass(t); } else if (v is haxe.lang.Function) { return ValueType.TFunction; } else { return ValueType.TClass(t); } } public static bool enumEq<T>(T a, T b) { if (a is haxe.lang.Enum) return a.Equals(b); else return haxe.lang.Runtime.eq(a, b); } public static string enumConstructor(object e) { if (e is System.Enum) return e + ""; else return ((haxe.lang.Enum) e).getTag(); } public static global::Array enumParameters(object e) { return ( e is System.Enum ) ? new Array<object>() : ((haxe.lang.Enum) e).@params; } public static int enumIndex(object e) { if (e is System.Enum) return ((System.IConvertible) e).ToInt32(null); else return ((haxe.lang.Enum) e).index; } public static global::Array<T> allEnums<T>(global::System.Type e) { unchecked { #line 375 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" global::Array<object> ctors = global::Type.getEnumConstructs(e); global::Array<T> ret = new global::Array<T>(new T[]{}); { #line 377 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" int _g = 0; #line 377 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" while (( _g < ctors.length )) { #line 377 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" string ctor = global::haxe.lang.Runtime.toString(ctors[_g]); #line 377 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" ++ _g; #line 379 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" T v = global::haxe.lang.Runtime.genericCast<T>(global::Reflect.field(e, ctor)); if (global::Std.@is(v, e)) { ret.push(v); } } } #line 384 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return ret; } #line default } public static new object __hx_createEmpty() { unchecked { #line 62 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return new global::Type(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 62 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Type.hx" return new global::Type(); } #line default } }
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 SAF.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; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using PlayFab.Internal; using UnityEngine; namespace PlayFab.Public { #if !UNITY_WSA && !UNITY_WP8 && !NETFX_CORE public interface IPlayFabLogger { IPAddress ip { get; set; } int port { get; set; } string url { get; set; } // Unity MonoBehaviour callbacks void OnEnable(); void OnDisable(); void OnDestroy(); } /// <summary> /// This is some unity-log capturing logic, and threading tools that allow logging to be caught and processed on another thread /// </summary> public abstract class PlayFabLoggerBase : IPlayFabLogger { private static readonly StringBuilder Sb = new StringBuilder(); private readonly Queue<string> LogMessageQueue = new Queue<string>(); private const int LOG_CACHE_INTERVAL_MS = 10000; private Thread _writeLogThread; private readonly object _threadLock = new object(); private static readonly TimeSpan _threadKillTimeout = TimeSpan.FromSeconds(60); private DateTime _threadKillTime = DateTime.UtcNow + _threadKillTimeout; // Kill the thread after 1 minute of inactivity private bool _isApplicationPlaying = true; private int _pendingLogsCount; public IPAddress ip { get; set; } public int port { get; set; } public string url { get; set; } protected PlayFabLoggerBase() { var gatherer = new PlayFabDataGatherer(); gatherer.GatherData(); var message = gatherer.GenerateReport(); lock (LogMessageQueue) { LogMessageQueue.Enqueue(message); } } public virtual void OnEnable() { PlayFabHttp.instance.StartCoroutine(RegisterLogger()); // Coroutine helper to set up log-callbacks } private IEnumerator RegisterLogger() { yield return new WaitForEndOfFrame(); // Effectively just a short wait before activating this registration if (!string.IsNullOrEmpty(PlayFabSettings.LoggerHost)) { #if UNITY_5 || UNITY_2017 Application.logMessageReceivedThreaded += HandleUnityLog; #else Application.RegisterLogCallback(HandleUnityLog); #endif } } public virtual void OnDisable() { if (!string.IsNullOrEmpty(PlayFabSettings.LoggerHost)) { #if UNITY_5 || UNITY_2017 Application.logMessageReceivedThreaded -= HandleUnityLog; #else Application.RegisterLogCallback(null); #endif } } public virtual void OnDestroy() { _isApplicationPlaying = false; } /// <summary> /// Logs are cached and written in bursts /// BeginUploadLog is called at the begining of each burst /// </summary> protected abstract void BeginUploadLog(); /// <summary> /// Logs are cached and written in bursts /// UploadLog is called for each cached log, between BeginUploadLog and EndUploadLog /// </summary> protected abstract void UploadLog(string message); /// <summary> /// Logs are cached and written in bursts /// EndUploadLog is called at the end of each burst /// </summary> protected abstract void EndUploadLog(); /// <summary> /// Handler to process Unity logs into our logging system /// </summary> /// <param name="message"></param> /// <param name="stacktrace"></param> /// <param name="type"></param> private void HandleUnityLog(string message, string stacktrace, LogType type) { if (!PlayFabSettings.EnableRealTimeLogging) return; Sb.Length = 0; if (type == LogType.Log || type == LogType.Warning) { Sb.Append(type).Append(": ").Append(message); message = Sb.ToString(); lock (LogMessageQueue) { LogMessageQueue.Enqueue(message); } } else if (type == LogType.Error || type == LogType.Exception) { Sb.Append(type).Append(": ").Append(message).Append("\n").Append(stacktrace).Append(StackTraceUtility.ExtractStackTrace()); message = Sb.ToString(); lock (LogMessageQueue) { LogMessageQueue.Enqueue(message); } } ActivateThreadWorker(); } private void ActivateThreadWorker() { lock (_threadLock) { if (_writeLogThread != null) { return; } _writeLogThread = new Thread(WriteLogThreadWorker); _writeLogThread.Start(); } } private void WriteLogThreadWorker() { try { bool active; lock (_threadLock) { // Kill the thread after 1 minute of inactivity _threadKillTime = DateTime.UtcNow + _threadKillTimeout; } var localLogQueue = new Queue<string>(); do { lock (LogMessageQueue) { _pendingLogsCount = LogMessageQueue.Count; while (LogMessageQueue.Count > 0) // Transfer the messages to the local queue localLogQueue.Enqueue(LogMessageQueue.Dequeue()); } BeginUploadLog(); while (localLogQueue.Count > 0) // Transfer the messages to the local queue UploadLog(localLogQueue.Dequeue()); EndUploadLog(); #region Expire Thread. // Check if we've been inactive lock (_threadLock) { var now = DateTime.UtcNow; if (_pendingLogsCount > 0 && _isApplicationPlaying) { // Still active, reset the _threadKillTime _threadKillTime = now + _threadKillTimeout; } // Kill the thread after 1 minute of inactivity active = now <= _threadKillTime; if (!active) { _writeLogThread = null; } // This thread will be stopped, so null this now, inside lock (_threadLock) } #endregion Thread.Sleep(LOG_CACHE_INTERVAL_MS); } while (active); } catch (Exception e) { Debug.LogException(e); _writeLogThread = null; } } } #else public interface IPlayFabLogger { string ip { get; set; } int port { get; set; } string url { get; set; } // Unity MonoBehaviour callbacks void OnEnable(); void OnDisable(); void OnDestroy(); } /// <summary> /// This is just a placeholder. WP8 doesn't support direct threading, but instead makes you use the await command. /// </summary> public abstract class PlayFabLoggerBase : IPlayFabLogger { public string ip { get; set; } public int port { get; set; } public string url { get; set; } // Unity MonoBehaviour callbacks public void OnEnable() { } public void OnDisable() { } public void OnDestroy() { } protected abstract void BeginUploadLog(); protected abstract void UploadLog(string message); protected abstract void EndUploadLog(); } #endif /// <summary> /// This translates the logs up to the PlayFab service via a PlayFab restful API /// TODO: PLAYFAB - attach these to the PlayFab API /// </summary> public class PlayFabLogger : PlayFabLoggerBase { /// <summary> /// Logs are cached and written in bursts /// BeginUploadLog is called at the begining of each burst /// </summary> protected override void BeginUploadLog() { } /// <summary> /// Logs are cached and written in bursts /// UploadLog is called for each cached log, between BeginUploadLog and EndUploadLog /// </summary> protected override void UploadLog(string message) { } /// <summary> /// Logs are cached and written in bursts /// EndUploadLog is called at the end of each burst /// </summary> protected override void EndUploadLog() { } } }